diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml new file mode 100644 index 000000000000..044c7c593c8d --- /dev/null +++ b/.github/workflows/integration-test.yml @@ -0,0 +1,54 @@ +name: CLI Tests +on: + pull_request: + push: + branches: + - master +jobs: + cleanup-runs: + runs-on: ubuntu-latest + steps: + - uses: rokroskar/workflow-run-cleanup-action@master + env: + GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" + if: "!startsWith(github.ref, 'refs/tags/') && github.ref != 'refs/heads/master'" + + protobuf: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: technote-space/get-diff-action@v1 + id: git_diff + with: + SUFFIX_FILTER: | + .go + .mod + .sum + - name: build-sim + run: | + make build-sim + if: "env.GIT_DIFF != ''" + - name: cli-test + run: | + make test-integration + if: "env.GIT_DIFF != ''" + + amino: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: technote-space/get-diff-action@v1 + id: git_diff + with: + SUFFIX_FILTER: | + .go + .mod + .sum + - name: build-sim + run: | + make build-sim-amino + if: "env.GIT_DIFF != ''" + - name: cli-test + run: | + make test-integration-amino + if: "env.GIT_DIFF != ''" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 85040ee3ddf4..9dfd8d76cda9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,9 +15,9 @@ jobs: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" if: "!startsWith(github.ref, 'refs/tags/') && github.ref != 'refs/heads/master'" - split-test-files: + split-test-files: runs-on: ubuntu-latest - steps: + steps: - uses: actions/checkout@v2 - name: Create a file with all the pkgs run: go list ./... > pkgs.txt @@ -29,15 +29,15 @@ jobs: name: '${{ github.sha }}-aa' path: ./xaa.txt - uses: actions/upload-artifact@v2 - with: + with: name: '${{ github.sha }}-ab' path: ./xab.txt - uses: actions/upload-artifact@v2 - with: + with: name: '${{ github.sha }}-ac' path: ./xac.txt - uses: actions/upload-artifact@v2 - with: + with: name: '${{ github.sha }}-ad' path: ./xad.txt @@ -53,7 +53,7 @@ jobs: SUFFIX_FILTER: | .go .mod - .sum + .sum - uses: actions/download-artifact@v2 with: name: '${{ github.sha }}-aa' @@ -76,8 +76,8 @@ jobs: - uses: codecov/codecov-action@v1 with: file: ./coverage.txt - fail_ci_if_error: true - if: "env.GIT_DIFF != ''" + fail_ci_if_error: true + if: "env.GIT_DIFF != ''" test-coverage-run-2: runs-on: ubuntu-latest @@ -91,7 +91,7 @@ jobs: SUFFIX_FILTER: | .go .mod - .sum + .sum - uses: actions/download-artifact@v2 with: name: '${{ github.sha }}-ab' @@ -114,8 +114,8 @@ jobs: - uses: codecov/codecov-action@v1 with: file: ./coverage.txt - fail_ci_if_error: true - if: "env.GIT_DIFF != ''" + fail_ci_if_error: true + if: "env.GIT_DIFF != ''" test-coverage-run-3: runs-on: ubuntu-latest @@ -129,7 +129,7 @@ jobs: SUFFIX_FILTER: | .go .mod - .sum + .sum - uses: actions/download-artifact@v2 with: name: '${{ github.sha }}-ac' @@ -152,8 +152,8 @@ jobs: - uses: codecov/codecov-action@v1 with: file: ./coverage.txt - fail_ci_if_error: true - if: "env.GIT_DIFF != ''" + fail_ci_if_error: true + if: "env.GIT_DIFF != ''" test-coverage-run-4: runs-on: ubuntu-latest @@ -167,7 +167,7 @@ jobs: SUFFIX_FILTER: | .go .mod - .sum + .sum - uses: actions/download-artifact@v2 with: name: '${{ github.sha }}-ad' @@ -190,13 +190,14 @@ jobs: - uses: codecov/codecov-action@v1 with: file: ./coverage.txt - fail_ci_if_error: true - if: "env.GIT_DIFF != ''" + fail_ci_if_error: true + if: "env.GIT_DIFF != ''" - integration-tests: + amino: runs-on: ubuntu-latest timeout-minutes: 10 steps: + - uses: actions/setup-go@v2-beta - uses: actions/checkout@v2 - uses: technote-space/get-diff-action@v1 id: git_diff @@ -205,11 +206,11 @@ jobs: .go .mod .sum - - name: build-sim + - name: build run: | - make build-sim + make build if: "env.GIT_DIFF != ''" - - name: cli-test + - name: unit tests run: | - make test-integration + go test ./... -mod=readonly -timeout 12m -race -coverprofile=coverage.txt -covermode=atomic -tags='ledger test_ledger_mock test_amino' if: "env.GIT_DIFF != ''" diff --git a/Makefile b/Makefile index e8e3f62e7d64..a995b2aa5910 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,11 @@ build-sim: go.sum go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/cmd/simd go build -mod=readonly $(BUILD_FLAGS) -o $(BUILDDIR) ./simapp/cmd/simcli +build-sim-amino: go.sum + mkdir -p $(BUILDDIR) + go build -mod=readonly $(BUILD_FLAGS) -tags test_amino -o $(BUILDDIR) ./simapp/cmd/simd + go build -mod=readonly $(BUILD_FLAGS) -tags test_amino -o $(BUILDDIR) ./simapp/cmd/simcli + .PHONY: \ build \ build-sim @@ -131,6 +136,9 @@ test-race: test-integration: build-sim BUILDDIR=$(BUILDDIR) go test -mod=readonly -p 4 -tags='ledger test_ledger_mock cli_test' -run ^TestCLI `go list ./.../cli/...` +test-integration-amino: build-sim-amino + BUILDDIR=$(BUILDDIR) go test -mod=readonly -p 4 -tags='ledger test_ledger_mock cli_test test_amino' -run ^TestCLI `go list ./.../cli/...` + .PHONY: test test-all test-ledger-mock test-ledger test-unit test-race test-sim-nondeterminism: diff --git a/baseapp/abci.go b/baseapp/abci.go index f2ae94f8f974..f114688d6803 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -376,12 +376,7 @@ func handleQueryApp(app *BaseApp, path []string, req abci.RequestQuery) abci.Res case "simulate": txBytes := req.Data - tx, err := app.txDecoder(txBytes) - if err != nil { - return sdkerrors.QueryResult(sdkerrors.Wrap(err, "failed to decode tx")) - } - - gInfo, res, err := app.Simulate(txBytes, tx) + gInfo, res, _, err := app.Simulate(txBytes) if err != nil { return sdkerrors.QueryResult(sdkerrors.Wrap(err, "failed to simulate tx")) } diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 36afc93cef15..3001686111cf 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -985,13 +985,13 @@ func TestSimulateTx(t *testing.T) { require.Nil(t, err) // simulate a message, check gas reported - gInfo, result, err := app.Simulate(txBytes, tx) + gInfo, result, _, err := app.Simulate(txBytes) require.NoError(t, err) require.NotNil(t, result) require.Equal(t, gasConsumed, gInfo.GasUsed) // simulate again, same result - gInfo, result, err = app.Simulate(txBytes, tx) + gInfo, result, _, err = app.Simulate(txBytes) require.NoError(t, err) require.NotNil(t, result) require.Equal(t, gasConsumed, gInfo.GasUsed) diff --git a/baseapp/helpers.go b/baseapp/helpers.go index c69a8ba82925..fbc5a2e8e8db 100644 --- a/baseapp/helpers.go +++ b/baseapp/helpers.go @@ -3,6 +3,8 @@ package baseapp import ( abci "github.com/tendermint/tendermint/abci/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -10,8 +12,13 @@ func (app *BaseApp) Check(tx sdk.Tx) (sdk.GasInfo, *sdk.Result, error) { return app.runTx(runTxModeCheck, nil, tx) } -func (app *BaseApp) Simulate(txBytes []byte, tx sdk.Tx) (sdk.GasInfo, *sdk.Result, error) { - return app.runTx(runTxModeSimulate, txBytes, tx) +func (app *BaseApp) Simulate(txBytes []byte) (sdk.GasInfo, *sdk.Result, sdk.Tx, error) { + tx, err := app.txDecoder(txBytes) + if err != nil { + return sdk.GasInfo{}, nil, nil, sdkerrors.Wrap(err, "failed to decode tx") + } + gi, r, err := app.runTx(runTxModeSimulate, txBytes, tx) + return gi, r, tx, err } func (app *BaseApp) Deliver(tx sdk.Tx) (sdk.GasInfo, *sdk.Result, error) { diff --git a/client/broadcast.go b/client/broadcast.go index 203a3677065c..84c8877fab86 100644 --- a/client/broadcast.go +++ b/client/broadcast.go @@ -16,7 +16,7 @@ import ( // based on the context parameters. The result of the broadcast is parsed into // an intermediate structure which is logged if the context has a logger // defined. -func (ctx Context) BroadcastTx(txBytes []byte) (res sdk.TxResponse, err error) { +func (ctx Context) BroadcastTx(txBytes []byte) (res *sdk.TxResponse, err error) { switch ctx.BroadcastMode { case flags.BroadcastSync: res, err = ctx.BroadcastTxSync(txBytes) @@ -28,7 +28,7 @@ func (ctx Context) BroadcastTx(txBytes []byte) (res sdk.TxResponse, err error) { res, err = ctx.BroadcastTxCommit(txBytes) default: - return sdk.TxResponse{}, fmt.Errorf("unsupported return type %s; supported types: sync, async, block", ctx.BroadcastMode) + return nil, fmt.Errorf("unsupported return type %s; supported types: sync, async, block", ctx.BroadcastMode) } return res, err @@ -84,16 +84,16 @@ func CheckTendermintError(err error, txBytes []byte) *sdk.TxResponse { // NOTE: This should ideally not be used as the request may timeout but the tx // may still be included in a block. Use BroadcastTxAsync or BroadcastTxSync // instead. -func (ctx Context) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) { +func (ctx Context) BroadcastTxCommit(txBytes []byte) (*sdk.TxResponse, error) { node, err := ctx.GetNode() if err != nil { - return sdk.TxResponse{}, err + return nil, err } res, err := node.BroadcastTxCommit(txBytes) if err != nil { if errRes := CheckTendermintError(err, txBytes); errRes != nil { - return *errRes, nil + return errRes, nil } return sdk.NewResponseFormatBroadcastTxCommit(res), err @@ -112,15 +112,15 @@ func (ctx Context) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) { // BroadcastTxSync broadcasts transaction bytes to a Tendermint node // synchronously (i.e. returns after CheckTx execution). -func (ctx Context) BroadcastTxSync(txBytes []byte) (sdk.TxResponse, error) { +func (ctx Context) BroadcastTxSync(txBytes []byte) (*sdk.TxResponse, error) { node, err := ctx.GetNode() if err != nil { - return sdk.TxResponse{}, err + return nil, err } res, err := node.BroadcastTxSync(txBytes) if errRes := CheckTendermintError(err, txBytes); errRes != nil { - return *errRes, nil + return errRes, nil } return sdk.NewResponseFormatBroadcastTx(res), err @@ -128,15 +128,15 @@ func (ctx Context) BroadcastTxSync(txBytes []byte) (sdk.TxResponse, error) { // BroadcastTxAsync broadcasts transaction bytes to a Tendermint node // asynchronously (i.e. returns immediately). -func (ctx Context) BroadcastTxAsync(txBytes []byte) (sdk.TxResponse, error) { +func (ctx Context) BroadcastTxAsync(txBytes []byte) (*sdk.TxResponse, error) { node, err := ctx.GetNode() if err != nil { - return sdk.TxResponse{}, err + return nil, err } res, err := node.BroadcastTxAsync(txBytes) if errRes := CheckTendermintError(err, txBytes); errRes != nil { - return *errRes, nil + return errRes, nil } return sdk.NewResponseFormatBroadcastTx(res), err diff --git a/client/flags/flags.go b/client/flags/flags.go index fb4438da722b..78e50c0447dd 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -70,6 +70,7 @@ const ( FlagPage = "page" FlagLimit = "limit" FlagUnsafeCORS = "unsafe-cors" + FlagSignMode = "sign-mode" ) // LineBreak can be included in a command list to provide a blank line @@ -122,6 +123,7 @@ func PostCommands(cmds ...*cobra.Command) []*cobra.Command { c.Flags().Bool(FlagOffline, false, "Offline mode (does not allow any online functionality") c.Flags().BoolP(FlagSkipConfirmation, "y", false, "Skip tx broadcasting prompt confirmation") c.Flags().String(FlagKeyringBackend, DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + c.Flags().String(FlagSignMode, "", "Choose sign mode (direct|amino-json), this is an advanced feature") // --gas can accept integers and "simulate" c.Flags().Var(&GasFlagVar, "gas", fmt.Sprintf( diff --git a/client/rpc/block.go b/client/rpc/block.go index 4fabdf3ab7b8..02cd53b59b46 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -5,6 +5,8 @@ import ( "net/http" "strconv" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/gorilla/mux" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -65,10 +67,10 @@ func getBlock(clientCtx client.Context, height *int64) ([]byte, error) { } if clientCtx.Indent { - return legacy.Cdc.MarshalJSONIndent(res, "", " ") + return legacy.MarshalJSONIndent(clientCtx.JSONMarshaler, res) } - return legacy.Cdc.MarshalJSON(res) + return clientCtx.JSONMarshaler.MarshalJSON(res) } // get the current blockchain height diff --git a/client/rpc/status.go b/client/rpc/status.go index b85a67c1302a..f5c3e54a91eb 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -4,6 +4,8 @@ import ( "fmt" "net/http" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" + "github.com/spf13/cobra" "github.com/spf13/viper" diff --git a/client/tx/factory.go b/client/tx/factory.go index 33508acbfa47..1568e60f62e9 100644 --- a/client/tx/factory.go +++ b/client/tx/factory.go @@ -3,6 +3,8 @@ package tx import ( "io" + types "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/spf13/viper" "github.com/cosmos/cosmos-sdk/client" @@ -26,6 +28,7 @@ type Factory struct { memo string fees sdk.Coins gasPrices sdk.DecCoins + signMode types.SignMode } func NewFactoryFromCLI(input io.Reader) Factory { @@ -39,6 +42,15 @@ func NewFactoryFromCLI(input io.Reader) Factory { panic(err) } + signModeStr := viper.GetString(flags.FlagSignMode) + signMode := types.SignMode_SIGN_MODE_UNSPECIFIED + switch signModeStr { + case "direct": + signMode = types.SignMode_SIGN_MODE_DIRECT + case "amino-json": + signMode = types.SignMode_SIGN_MODE_LEGACY_AMINO_JSON + } + f := Factory{ keybase: kb, accountNumber: viper.GetUint64(flags.FlagAccountNumber), @@ -48,6 +60,7 @@ func NewFactoryFromCLI(input io.Reader) Factory { simulateAndExecute: flags.GasFlagVar.Simulate, chainID: viper.GetString(flags.FlagChainID), memo: viper.GetString(flags.FlagMemo), + signMode: signMode, } f = f.WithFees(viper.GetString(flags.FlagFees)) diff --git a/client/tx/tx.go b/client/tx/tx.go index 234f5e986be8..112318d43739 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -8,12 +8,13 @@ import ( "os" "strings" + types "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/gogo/protobuf/jsonpb" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/rest" @@ -108,7 +109,12 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { } } - txBytes, err := Sign(txf, clientCtx.GetFromName(), clientkeys.DefaultKeyPass, tx) + err = Sign(txf, clientCtx.GetFromName(), tx) + if err != nil { + return err + } + + txBytes, err := clientCtx.TxGenerator.TxEncoder()(tx.GetTx()) if err != nil { return err } @@ -209,25 +215,19 @@ func BuildUnsignedTx(txf Factory, msgs ...sdk.Msg) (client.TxBuilder, error) { } } - clientFee := txf.txGenerator.NewFee() - clientFee.SetAmount(fees) - clientFee.SetGas(txf.gas) - - tx := txf.txGenerator.NewTx() - tx.SetMemo(txf.memo) + tx := txf.txGenerator.NewTxBuilder() - if err := tx.SetFee(clientFee); err != nil { + if err := tx.SetMsgs(msgs...); err != nil { return nil, err } + tx.SetMemo(txf.memo) + tx.SetFee(fees) + tx.SetGasLimit(txf.gas) if err := tx.SetSignatures(); err != nil { return nil, err } - if err := tx.SetMsgs(msgs...); err != nil { - return nil, err - } - return tx, nil } @@ -242,13 +242,13 @@ func BuildSimTx(txf Factory, msgs ...sdk.Msg) ([]byte, error) { // Create an empty signature literal as the ante handler will populate with a // sentinel pubkey. - sig := txf.txGenerator.NewSignature() + sig := client.SignatureBuilder{} if err := tx.SetSignatures(sig); err != nil { return nil, err } - return txf.txGenerator.MarshalTx(tx.GetTx()) + return txf.txGenerator.TxEncoder()(tx.GetTx()) } // CalculateGas simulates the execution of a transaction and returns the @@ -312,33 +312,62 @@ func PrepareFactory(clientCtx client.Context, txf Factory) (Factory, error) { // // Note, It is assumed the Factory has the necessary fields set that are required // by the CanonicalSignBytes call. -func Sign(txf Factory, name, passphrase string, tx client.TxBuilder) ([]byte, error) { +func Sign(txf Factory, name string, tx client.TxBuilder) error { if txf.keybase == nil { - return nil, errors.New("keybase must be set prior to signing a transaction") + return errors.New("keybase must be set prior to signing a transaction") + } + + signMode := txf.signMode + if signMode == types.SignMode_SIGN_MODE_UNSPECIFIED { + signMode = txf.txGenerator.SignModeHandler().DefaultMode() } - signBytes, err := tx.CanonicalSignBytes(txf.chainID, txf.accountNumber, txf.sequence) + key, err := txf.keybase.Key(name) if err != nil { - return nil, err + return err + } + + pubKey := key.GetPubKey() + + sigData := &types.SingleSignatureData{ + SignMode: signMode, + Signature: nil, + } + sig := client.SignatureBuilder{ + PubKey: pubKey, + Data: sigData, } - sigBytes, pubkey, err := txf.keybase.Sign(name, signBytes) + err = tx.SetSignatures(sig) if err != nil { - return nil, err + return err } - sig := txf.txGenerator.NewSignature() - sig.SetSignature(sigBytes) + signBytes, err := txf.txGenerator.SignModeHandler().GetSignBytes( + signMode, + types.SigningData{ + PublicKey: pubKey, + ChainID: txf.chainID, + AccountNumber: txf.accountNumber, + AccountSequence: txf.sequence, + }, tx.GetTx(), + ) + if err != nil { + return err + } - if err := sig.SetPubKey(pubkey); err != nil { - return nil, err + sigBytes, _, err := txf.keybase.Sign(name, signBytes) + if err != nil { + return err } + sigData.Signature = sigBytes + if err := tx.SetSignatures(sig); err != nil { - return nil, err + return err } - return txf.txGenerator.MarshalTx(tx.GetTx()) + return nil } // GasEstimateResponse defines a response definition for tx gas estimation. diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index f12916de569c..3f48adab5d77 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -16,7 +16,7 @@ import ( ) func NewTestTxGenerator() client.TxGenerator { - _, cdc := simapp.MakeCodecs() + _, _, cdc := simapp.MakeCodecs() return types.StdTxGenerator{Cdc: cdc} } @@ -105,5 +105,7 @@ func TestBuildUnsignedTx(t *testing.T) { tx, err := tx.BuildUnsignedTx(txf, msg) require.NoError(t, err) require.NotNil(t, tx) - require.Equal(t, []sdk.Signature{}, tx.GetSignatures()) + sigData, err := tx.GetTx().GetSignatureData() + require.NoError(t, err) + require.Empty(t, sigData) } diff --git a/client/tx_generator.go b/client/tx_generator.go index f840bd39e922..0e50ca083be2 100644 --- a/client/tx_generator.go +++ b/client/tx_generator.go @@ -3,7 +3,8 @@ package client import ( "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/types" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" ) type ( @@ -11,22 +12,14 @@ type ( // application-defined concrete transaction type. The type returned must // implement TxBuilder. TxGenerator interface { - NewTx() TxBuilder - NewFee() Fee - NewSignature() Signature - MarshalTx(tx types.Tx) ([]byte, error) - } - - Fee interface { - types.Fee - SetGas(uint64) - SetAmount(types.Coins) - } - - Signature interface { - types.Signature - SetPubKey(crypto.PubKey) error - SetSignature([]byte) + NewTxBuilder() TxBuilder + // WrapTxBuilder wraps an existing tx in a TxBuilder or returns an error + WrapTxBuilder(tx sdk.Tx) (TxBuilder, error) + TxEncoder() sdk.TxEncoder + TxDecoder() sdk.TxDecoder + TxJSONEncoder() sdk.TxEncoder + TxJSONDecoder() sdk.TxDecoder + SignModeHandler() types.SignModeHandler } // TxBuilder defines an interface which an application-defined concrete transaction @@ -34,18 +27,17 @@ type ( // signatures, and provide canonical bytes to sign over. The transaction must // also know how to encode itself. TxBuilder interface { - GetTx() types.Tx + GetTx() types.SigTx - SetMsgs(...types.Msg) error - GetSignatures() []types.Signature - SetSignatures(...Signature) error - GetFee() types.Fee - SetFee(Fee) error - GetMemo() string - SetMemo(string) + SetMsgs(msgs ...sdk.Msg) error + SetSignatures(signatures ...SignatureBuilder) error + SetMemo(memo string) + SetFee(amount sdk.Coins) + SetGasLimit(limit uint64) + } - // CanonicalSignBytes returns the canonical sign bytes to sign over, given a - // chain ID, along with an account and sequence number. - CanonicalSignBytes(cid string, num, seq uint64) ([]byte, error) + SignatureBuilder struct { + PubKey crypto.PubKey + Data types.SignatureData } ) diff --git a/codec/amino_codec.go b/codec/amino_codec.go index a7cf476bae88..f22b4a0fd31c 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -43,3 +43,11 @@ func (ac *AminoCodec) UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshale func (ac *AminoCodec) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) { ac.Codec.MustUnmarshalBinaryLengthPrefixed(bz, ptr) } + +func (ac *AminoCodec) MarshalAny(iface interface{}) ([]byte, error) { + return ac.Codec.MarshalBinaryBare(iface) +} + +func (ac *AminoCodec) UnmarshalAny(bz []byte, iface interface{}) error { + return ac.Codec.UnmarshalBinaryBare(bz, iface) +} diff --git a/codec/any.go b/codec/any.go deleted file mode 100644 index 91543b14ff52..000000000000 --- a/codec/any.go +++ /dev/null @@ -1,44 +0,0 @@ -package codec - -import ( - "fmt" - - "github.com/gogo/protobuf/proto" - - "github.com/cosmos/cosmos-sdk/codec/types" -) - -// MarshalAny is a convenience function for packing the provided value in an -// Any and then proto marshaling it to bytes -func MarshalAny(m Marshaler, x interface{}) ([]byte, error) { - msg, ok := x.(proto.Message) - if !ok { - return nil, fmt.Errorf("can't proto marshal %T", x) - } - - any := &types.Any{} - err := any.Pack(msg) - if err != nil { - return nil, err - } - - return m.MarshalBinaryBare(any) -} - -// UnmarshalAny is a convenience function for proto unmarshaling an Any from -// bz and then unpacking it to the interface pointer passed in as iface using -// the provided AnyUnpacker or returning an error -// -// Ex: -// var x MyInterface -// err := UnmarshalAny(unpacker, &x, bz) -func UnmarshalAny(m Marshaler, iface interface{}, bz []byte) error { - any := &types.Any{} - - err := m.UnmarshalBinaryBare(bz, any) - if err != nil { - return err - } - - return m.UnpackAny(any, iface) -} diff --git a/codec/any_test.go b/codec/any_test.go index dbca831008f8..9cc0d8e4d7ff 100644 --- a/codec/any_test.go +++ b/codec/any_test.go @@ -26,29 +26,29 @@ func TestMarshalAny(t *testing.T) { cdc := NewProtoCodec(registry) kitty := &testdata.Cat{Moniker: "Kitty"} - bz, err := MarshalAny(cdc, kitty) + bz, err := cdc.MarshalAny(kitty) require.NoError(t, err) var animal testdata.Animal // empty registry should fail - err = UnmarshalAny(cdc, &animal, bz) + err = cdc.UnmarshalAny(bz, &animal) require.Error(t, err) // wrong type registration should fail registry.RegisterImplementations((*testdata.Animal)(nil), &testdata.Dog{}) - err = UnmarshalAny(cdc, &animal, bz) + err = cdc.UnmarshalAny(bz, &animal) require.Error(t, err) // should pass registry = NewTestInterfaceRegistry() cdc = NewProtoCodec(registry) - err = UnmarshalAny(cdc, &animal, bz) + err = cdc.UnmarshalAny(bz, &animal) require.NoError(t, err) require.Equal(t, kitty, animal) // nil should fail registry = NewTestInterfaceRegistry() - err = UnmarshalAny(cdc, nil, bz) + err = cdc.UnmarshalAny(bz, nil) require.Error(t, err) } diff --git a/codec/codec.go b/codec/codec.go index dee51a9da789..83ad47d49b96 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -32,6 +32,14 @@ type ( UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) + // MarshalAny marshals the provided interface value as an Any for protobuf + // or as a concrete type with Amino + MarshalAny(iface interface{}) ([]byte, error) + + // UnmarshalAny marshals the provided interface value as an Any for protobuf + // or as a concrete type with Amino + UnmarshalAny(bz []byte, iface interface{}) error + JSONMarshaler types.AnyUnpacker } diff --git a/codec/hybrid_codec.go b/codec/hybrid_codec.go index 7fbd109a3db0..504443f5861f 100644 --- a/codec/hybrid_codec.go +++ b/codec/hybrid_codec.go @@ -1,6 +1,8 @@ package codec -import "github.com/cosmos/cosmos-sdk/codec/types" +import ( + "github.com/cosmos/cosmos-sdk/codec/types" +) // HybridCodec defines a codec that utilizes Protobuf for binary encoding // and Amino for JSON encoding. @@ -64,6 +66,14 @@ func (hc *HybridCodec) MustUnmarshalJSON(bz []byte, ptr interface{}) { hc.amino.MustUnmarshalJSON(bz, ptr) } +func (hc *HybridCodec) MarshalAny(iface interface{}) ([]byte, error) { + return hc.proto.MarshalAny(iface) +} + +func (hc *HybridCodec) UnmarshalAny(bz []byte, iface interface{}) error { + return hc.proto.UnmarshalAny(bz, iface) +} + func (hc *HybridCodec) UnpackAny(any *types.Any, iface interface{}) error { return hc.proto.UnpackAny(any, iface) } diff --git a/codec/legacy_global/amino.go b/codec/legacy_global/amino.go new file mode 100644 index 000000000000..6ee80edef743 --- /dev/null +++ b/codec/legacy_global/amino.go @@ -0,0 +1,33 @@ +package legacy_global + +import ( + "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/multisig" +) + +// Cdc defines a global generic sealed Amino codec to be used throughout sdk. It +// has all Tendermint crypto and evidence types registered. +// +// TODO: Consider removing this global. +var Cdc *codec.Codec + +func init() { + Cdc = codec.New() + RegisterCrypto(Cdc) + RegisterEvidences(Cdc) + Cdc.Seal() +} + +// RegisterCrypto registers all crypto dependency types with the provided Amino +// codec. +func RegisterCrypto(cdc *codec.Codec) { + multisig.RegisterAmino(cdc.Amino) +} + +// RegisterEvidences registers Tendermint evidence types with the provided Amino +// codec. +func RegisterEvidences(cdc *codec.Codec) { + types.RegisterEvidences(cdc.Amino) +} diff --git a/codec/proto_codec.go b/codec/proto_codec.go index 2c9825db704b..03c187e410d3 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "fmt" + "github.com/gogo/protobuf/proto" "strings" "github.com/cosmos/cosmos-sdk/codec/types" @@ -134,6 +135,32 @@ func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr interface{}) { } } +func (pc *ProtoCodec) MarshalAny(ptr interface{}) ([]byte, error) { + msg, ok := ptr.(proto.Message) + if !ok { + return nil, fmt.Errorf("can't proto marshal %T", ptr) + } + + any := &types.Any{} + err := any.Pack(msg) + if err != nil { + return nil, err + } + + return pc.MarshalBinaryBare(any) +} + +func (pc *ProtoCodec) UnmarshalAny(bz []byte, iface interface{}) error { + any := &types.Any{} + + err := pc.UnmarshalBinaryBare(bz, any) + if err != nil { + return err + } + + return pc.UnpackAny(any, iface) +} + func (pc *ProtoCodec) UnpackAny(any *types.Any, iface interface{}) error { return pc.anyUnpacker.UnpackAny(any, iface) } diff --git a/codec/types/any.go b/codec/types/any.go index abdd78dd8628..f7b6e79a13dd 100644 --- a/codec/types/any.go +++ b/codec/types/any.go @@ -83,6 +83,21 @@ func (any *Any) Pack(x proto.Message) error { return nil } +// UnsafePack packs the value x in the Any and instead of returning the error +// in the case of a packing failure, keeps the cached value. This should only +// be used in situations where compatibility is needed with amino. Amino-only +// values can safely be packed using this method when they will only be +// marshaled with amino and not protobuf +func UnsafePackAny(x interface{}) *Any { + if msg, ok := x.(proto.Message); ok { + any, err := NewAnyWithValue(msg) + if err != nil { + return any + } + } + return &Any{cachedValue: x} +} + // GetCachedValue returns the cached value from the Any if present func (any *Any) GetCachedValue() interface{} { return any.cachedValue diff --git a/codec/types/compat.go b/codec/types/compat.go index c9c24cdcf00f..bb9709e5ef43 100644 --- a/codec/types/compat.go +++ b/codec/types/compat.go @@ -6,6 +6,7 @@ import ( "runtime/debug" "github.com/gogo/protobuf/jsonpb" + "github.com/gogo/protobuf/proto" amino "github.com/tendermint/go-amino" diff --git a/crypto/codec/default.go b/crypto/codec/default.go new file mode 100644 index 000000000000..ffe382651b35 --- /dev/null +++ b/crypto/codec/default.go @@ -0,0 +1,86 @@ +package codec + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/crypto/multisig" + "github.com/cosmos/cosmos-sdk/crypto/types" + + "github.com/tendermint/tendermint/crypto" + ed255192 "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/crypto/secp256k1" + "github.com/tendermint/tendermint/crypto/sr25519" +) + +type DefaultPublicKeyCodec struct{} + +var _ types.PublicKeyCodec = DefaultPublicKeyCodec{} + +func (cdc DefaultPublicKeyCodec) Decode(key *types.PublicKey) (crypto.PubKey, error) { + switch key := key.Sum.(type) { + case *types.PublicKey_Secp256K1: + n := len(key.Secp256K1) + if n != secp256k1.PubKeySecp256k1Size { + return nil, fmt.Errorf("wrong length %d for secp256k1 public key", n) + } + var res secp256k1.PubKeySecp256k1 + copy(res[:], key.Secp256K1) + return res, nil + case *types.PublicKey_Ed25519: + n := len(key.Ed25519) + if n != ed255192.PubKeyEd25519Size { + return nil, fmt.Errorf("wrong length %d for ed25519 public key", n) + } + var res ed255192.PubKeyEd25519 + copy(res[:], key.Ed25519) + return res, nil + case *types.PublicKey_Sr25519: + n := len(key.Sr25519) + if n != sr25519.PubKeySr25519Size { + return nil, fmt.Errorf("wrong length %d for sr25519 public key", n) + } + var res sr25519.PubKeySr25519 + copy(res[:], key.Sr25519) + return res, nil + case *types.PublicKey_Multisig: + pubKeys := key.Multisig.PubKeys + resKeys := make([]crypto.PubKey, len(pubKeys)) + for i, k := range pubKeys { + dk, err := cdc.Decode(k) + if err != nil { + return nil, err + } + resKeys[i] = dk + } + return multisig.NewPubKeyMultisigThreshold(key.Multisig.K, resKeys), nil + default: + return nil, fmt.Errorf("can't encode PubKey of type %T", key) + } +} + +func (cdc DefaultPublicKeyCodec) Encode(key crypto.PubKey) (*types.PublicKey, error) { + switch key := key.(type) { + case secp256k1.PubKeySecp256k1: + return &types.PublicKey{Sum: &types.PublicKey_Secp256K1{Secp256K1: key[:]}}, nil + case ed255192.PubKeyEd25519: + return &types.PublicKey{Sum: &types.PublicKey_Ed25519{Ed25519: key[:]}}, nil + case sr25519.PubKeySr25519: + return &types.PublicKey{Sum: &types.PublicKey_Sr25519{Sr25519: key[:]}}, nil + case multisig.ThresholdMultisigPubKey: + pubKeys := key.PubKeys + resKeys := make([]*types.PublicKey, len(pubKeys)) + for i, k := range pubKeys { + dk, err := cdc.Encode(k) + if err != nil { + return nil, err + } + resKeys[i] = dk + } + return &types.PublicKey{Sum: &types.PublicKey_Multisig{Multisig: &types.PubKeyMultisigThreshold{ + K: key.K, + PubKeys: resKeys, + }}}, nil + default: + return nil, fmt.Errorf("can't encode PubKey of type %T", key) + } +} diff --git a/crypto/multisig/amino.go b/crypto/multisig/amino.go new file mode 100644 index 000000000000..2e1527046d71 --- /dev/null +++ b/crypto/multisig/amino.go @@ -0,0 +1,29 @@ +package multisig + +import ( + amino "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/crypto/multisig" + + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/crypto/secp256k1" + "github.com/tendermint/tendermint/crypto/sr25519" +) + +var cdc = amino.NewCodec() + +func init() { + RegisterAmino(cdc) +} + +func RegisterAmino(amino *amino.Codec) { + amino.RegisterInterface((*crypto.PubKey)(nil), nil) + amino.RegisterConcrete(ThresholdMultisigPubKey{}, + multisig.PubKeyMultisigThresholdAminoRoute, nil) + amino.RegisterConcrete(ed25519.PubKeyEd25519{}, + ed25519.PubKeyAminoName, nil) + amino.RegisterConcrete(sr25519.PubKeySr25519{}, + sr25519.PubKeyAminoName, nil) + amino.RegisterConcrete(secp256k1.PubKeySecp256k1{}, + secp256k1.PubKeyAminoName, nil) +} diff --git a/crypto/multisig/multisig.go b/crypto/multisig/multisig.go new file mode 100644 index 000000000000..a0ffa782dd10 --- /dev/null +++ b/crypto/multisig/multisig.go @@ -0,0 +1,17 @@ +package multisig + +import ( + "github.com/tendermint/tendermint/crypto" + + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +type GetSignBytesFunc func(mode types.SignMode) ([]byte, error) + +type MultisigPubKey interface { + crypto.PubKey + + VerifyMultisignature(getSignBytes GetSignBytesFunc, sig *types.MultiSignatureData) bool + GetPubKeys() []crypto.PubKey + Threshold() uint32 +} diff --git a/crypto/types/multisig/multisignature.go b/crypto/multisig/multisignature.go similarity index 58% rename from crypto/types/multisig/multisignature.go rename to crypto/multisig/multisignature.go index 2e21935f26ad..855f47c34f1a 100644 --- a/crypto/types/multisig/multisignature.go +++ b/crypto/multisig/multisignature.go @@ -7,20 +7,19 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto/types" + tx "github.com/cosmos/cosmos-sdk/types/tx" ) -// Multisignature is used to represent the signature object used in the multisigs. +// AminoMultisignature is used to represent the signature object used in the multisigs. // Sigs is a list of signatures, sorted by corresponding index. -type Multisignature struct { +type AminoMultisignature struct { BitArray *types.CompactBitArray Sigs [][]byte } -// NewMultisig returns a new Multisignature of size n. -func NewMultisig(n int) *Multisignature { - // Default the signature list to have a capacity of two, since we can - // expect that most multisigs will require multiple signers. - return &Multisignature{types.NewCompactBitArray(n), make([][]byte, 0, 2)} +// NewMultisig returns a new MultiSignatureData +func NewMultisig(n int) *tx.MultiSignatureData { + return &tx.MultiSignatureData{BitArray: types.NewCompactBitArray(n), Signatures: make([]tx.SignatureData, 0, n)} } // GetIndex returns the index of pk in keys. Returns -1 if not found @@ -35,29 +34,29 @@ func getIndex(pk crypto.PubKey, keys []crypto.PubKey) int { // AddSignature adds a signature to the multisig, at the corresponding index. // If the signature already exists, replace it. -func (mSig *Multisignature) AddSignature(sig []byte, index int) { +func AddSignature(mSig *tx.MultiSignatureData, sig tx.SignatureData, index int) { newSigIndex := mSig.BitArray.NumTrueBitsBefore(index) // Signature already exists, just replace the value there if mSig.BitArray.GetIndex(index) { - mSig.Sigs[newSigIndex] = sig + mSig.Signatures[newSigIndex] = sig return } mSig.BitArray.SetIndex(index, true) // Optimization if the index is the greatest index - if newSigIndex == len(mSig.Sigs) { - mSig.Sigs = append(mSig.Sigs, sig) + if newSigIndex == len(mSig.Signatures) { + mSig.Signatures = append(mSig.Signatures, sig) return } // Expand slice by one with a dummy element, move all elements after i // over by one, then place the new signature in that gap. - mSig.Sigs = append(mSig.Sigs, make([]byte, 0)) - copy(mSig.Sigs[newSigIndex+1:], mSig.Sigs[newSigIndex:]) - mSig.Sigs[newSigIndex] = sig + mSig.Signatures = append(mSig.Signatures, &tx.SingleSignatureData{}) + copy(mSig.Signatures[newSigIndex+1:], mSig.Signatures[newSigIndex:]) + mSig.Signatures[newSigIndex] = sig } // AddSignatureFromPubKey adds a signature to the multisig, at the index in // keys corresponding to the provided pubkey. -func (mSig *Multisignature) AddSignatureFromPubKey(sig []byte, pubkey crypto.PubKey, keys []crypto.PubKey) error { +func AddSignatureFromPubKey(mSig *tx.MultiSignatureData, sig tx.SignatureData, pubkey crypto.PubKey, keys []crypto.PubKey) error { index := getIndex(pubkey, keys) if index == -1 { keysStr := make([]string, len(keys)) @@ -68,11 +67,6 @@ func (mSig *Multisignature) AddSignatureFromPubKey(sig []byte, pubkey crypto.Pub return fmt.Errorf("provided key %X doesn't exist in pubkeys: \n%s", pubkey.Bytes(), strings.Join(keysStr, "\n")) } - mSig.AddSignature(sig, index) + AddSignature(mSig, sig, index) return nil } - -// Marshal the multisignature with amino -func (mSig *Multisignature) Marshal() []byte { - return cdc.MustMarshalBinaryBare(mSig) -} diff --git a/crypto/multisig/threshold_pubkey.go b/crypto/multisig/threshold_pubkey.go new file mode 100644 index 000000000000..f3addf3419cb --- /dev/null +++ b/crypto/multisig/threshold_pubkey.go @@ -0,0 +1,121 @@ +package multisig + +import ( + "github.com/tendermint/tendermint/crypto" + + txtypes "github.com/cosmos/cosmos-sdk/types/tx" +) + +// ThresholdMultisigPubKey implements a K of N threshold multisig. +type ThresholdMultisigPubKey struct { + K uint32 `json:"threshold"` + PubKeys []crypto.PubKey `json:"pubkeys"` +} + +func (pk ThresholdMultisigPubKey) Threshold() uint32 { + return pk.K +} + +var _ MultisigPubKey = ThresholdMultisigPubKey{} + +// NewPubKeyMultisigThreshold returns a new PubKeyMultisigThreshold. +// Panics if len(pubkeys) < k or 0 >= k. +func NewPubKeyMultisigThreshold(k uint32, pubkeys []crypto.PubKey) MultisigPubKey { + if k <= 0 { + panic("threshold k of n multisignature: k <= 0") + } + if len(pubkeys) < int(k) { + panic("threshold k of n multisignature: len(pubkeys) < k") + } + for _, pubkey := range pubkeys { + if pubkey == nil { + panic("nil pubkey") + } + } + return ThresholdMultisigPubKey{k, pubkeys} +} + +// VerifyBytes should not be used with this ThresholdMultisigPubKey, instead VerifyMultisignature +// must be used +func (pk ThresholdMultisigPubKey) VerifyBytes([]byte, []byte) bool { + return false +} + +func (pk ThresholdMultisigPubKey) VerifyMultisignature(getSignBytes GetSignBytesFunc, sig *txtypes.MultiSignatureData) bool { + bitarray := sig.BitArray + sigs := sig.Signatures + size := bitarray.Size() + // ensure bit array is the correct size + if len(pk.PubKeys) != size { + return false + } + // ensure size of signature list + if len(sigs) < int(pk.K) || len(sigs) > size { + return false + } + // ensure at least k signatures are set + if bitarray.NumTrueBitsBefore(size) < int(pk.K) { + return false + } + // index in the list of signatures which we are concerned with. + sigIndex := 0 + for i := 0; i < size; i++ { + if bitarray.GetIndex(i) { + si := sig.Signatures[sigIndex] + switch si := si.(type) { + case *txtypes.SingleSignatureData: + msg, err := getSignBytes(si.SignMode) + if err != nil { + return false + } + if !pk.PubKeys[i].VerifyBytes(msg, si.Signature) { + return false + } + case *txtypes.MultiSignatureData: + nestedMultisigPk, ok := pk.PubKeys[i].(MultisigPubKey) + if !ok { + return false + } + if !nestedMultisigPk.VerifyMultisignature(getSignBytes, si) { + return false + } + default: + return false + } + sigIndex++ + } + } + return true +} + +func (pk ThresholdMultisigPubKey) GetPubKeys() []crypto.PubKey { + return pk.PubKeys +} + +// Bytes returns the amino encoded version of the ThresholdMultisigPubKey +func (pk ThresholdMultisigPubKey) Bytes() []byte { + return cdc.MustMarshalBinaryBare(pk) +} + +// Address returns tmhash(ThresholdMultisigPubKey.Bytes()) +func (pk ThresholdMultisigPubKey) Address() crypto.Address { + return crypto.AddressHash(pk.Bytes()) +} + +// Equals returns true iff pk and other both have the same number of keys, and +// all constituent keys are the same, and in the same order. +func (pk ThresholdMultisigPubKey) Equals(other crypto.PubKey) bool { + otherKey, sameType := other.(ThresholdMultisigPubKey) + if !sameType { + return false + } + if pk.K != otherKey.K || len(pk.PubKeys) != len(otherKey.PubKeys) { + return false + } + for i := 0; i < len(pk.PubKeys); i++ { + if !pk.PubKeys[i].Equals(otherKey.PubKeys[i]) { + return false + } + } + return true +} diff --git a/crypto/types/multisig/threshold_pubkey_test.go b/crypto/multisig/threshold_pubkey_test.go similarity index 67% rename from crypto/types/multisig/threshold_pubkey_test.go rename to crypto/multisig/threshold_pubkey_test.go index cc4aa780b27a..79c442505f09 100644 --- a/crypto/types/multisig/threshold_pubkey_test.go +++ b/crypto/multisig/threshold_pubkey_test.go @@ -10,6 +10,8 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" "github.com/tendermint/tendermint/crypto/sr25519" + + types "github.com/cosmos/cosmos-sdk/types/tx" ) // This tests multisig functionality, but it expects the first k signatures to be valid @@ -18,11 +20,11 @@ func TestThresholdMultisigValidCases(t *testing.T) { pkSet1, sigSet1 := generatePubKeysAndSignatures(5, []byte{1, 2, 3, 4}) cases := []struct { msg []byte - k int + k uint32 pubkeys []crypto.PubKey signingIndices []int // signatures should be the same size as signingIndices. - signatures [][]byte + signatures []types.SignatureData passAfterKSignatures []bool }{ { @@ -37,73 +39,73 @@ func TestThresholdMultisigValidCases(t *testing.T) { for tcIndex, tc := range cases { multisigKey := NewPubKeyMultisigThreshold(tc.k, tc.pubkeys) multisignature := NewMultisig(len(tc.pubkeys)) + signBytesFn := func(mode types.SignMode) ([]byte, error) { return tc.msg, nil } - for i := 0; i < tc.k-1; i++ { + for i := uint32(0); i < tc.k-1; i++ { signingIndex := tc.signingIndices[i] require.NoError( t, - multisignature.AddSignatureFromPubKey(tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), + AddSignatureFromPubKey(multisignature, tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), ) - bz := multisignature.Marshal() require.False( t, - multisigKey.VerifyBytes(tc.msg, bz), + multisigKey.VerifyMultisignature(signBytesFn, multisignature), "multisig passed when i < k, tc %d, i %d", tcIndex, i, ) require.NoError( t, - multisignature.AddSignatureFromPubKey(tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), + AddSignatureFromPubKey(multisignature, tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), ) require.Equal( t, - i+1, - len(multisignature.Sigs), + int(i+1), + len(multisignature.Signatures), "adding a signature for the same pubkey twice increased signature count by 2, tc %d", tcIndex, ) } - bz := multisignature.Marshal() require.False( t, - multisigKey.VerifyBytes(tc.msg, bz), + multisigKey.VerifyMultisignature(signBytesFn, multisignature), "multisig passed with k - 1 sigs, tc %d", tcIndex, ) require.NoError( t, - multisignature.AddSignatureFromPubKey( + AddSignatureFromPubKey( + multisignature, tc.signatures[tc.signingIndices[tc.k]], tc.pubkeys[tc.signingIndices[tc.k]], tc.pubkeys, ), ) - bz = multisignature.Marshal() require.True( t, - multisigKey.VerifyBytes(tc.msg, bz), + multisigKey.VerifyMultisignature(signBytesFn, multisignature), "multisig failed after k good signatures, tc %d", tcIndex, ) - for i := tc.k + 1; i < len(tc.signingIndices); i++ { + for i := int(tc.k) + 1; i < len(tc.signingIndices); i++ { signingIndex := tc.signingIndices[i] require.NoError( t, - multisignature.AddSignatureFromPubKey(tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), + AddSignatureFromPubKey(multisignature, tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), ) - bz := multisignature.Marshal() require.Equal( t, - tc.passAfterKSignatures[i-tc.k-1], - multisigKey.VerifyBytes(tc.msg, bz), + tc.passAfterKSignatures[i-int(tc.k)-1], + multisigKey.VerifyMultisignature(func(mode types.SignMode) ([]byte, error) { + return tc.msg, nil + }, multisignature), "multisig didn't verify as expected after k sigs, tc %d, i %d", tcIndex, i, ) require.NoError( t, - multisignature.AddSignatureFromPubKey(tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), + AddSignatureFromPubKey(multisignature, tc.signatures[signingIndex], tc.pubkeys[signingIndex], tc.pubkeys), ) require.Equal( t, i+1, - len(multisignature.Sigs), + len(multisignature.Signatures), "adding a signature for the same pubkey twice increased signature count by 2, tc %d", tcIndex, ) } @@ -116,13 +118,13 @@ func TestThresholdMultisigDuplicateSignatures(t *testing.T) { pubkeys, sigs := generatePubKeysAndSignatures(5, msg) multisigKey := NewPubKeyMultisigThreshold(2, pubkeys) multisignature := NewMultisig(5) - bz := multisignature.Marshal() + signBytesFn := func(mode types.SignMode) ([]byte, error) { return msg, nil } - require.False(t, multisigKey.VerifyBytes(msg, bz)) - multisignature.AddSignatureFromPubKey(sigs[0], pubkeys[0], pubkeys) + require.False(t, multisigKey.VerifyMultisignature(signBytesFn, multisignature)) + AddSignatureFromPubKey(multisignature, sigs[0], pubkeys[0], pubkeys) // Add second signature manually - multisignature.Sigs = append(multisignature.Sigs, sigs[0]) - require.False(t, multisigKey.VerifyBytes(msg, bz)) + multisignature.Signatures = append(multisignature.Signatures, sigs[0]) + require.False(t, multisigKey.VerifyMultisignature(signBytesFn, multisignature)) } // TODO: Fully replace this test with table driven tests @@ -157,8 +159,8 @@ func TestPubKeyMultisigThresholdAminoToIface(t *testing.T) { ab, err := cdc.MarshalBinaryLengthPrefixed(multisigKey) require.NoError(t, err) - // like other crypto.Pubkey implementations (e.g. ed25519.PubKey), - // PubKey should be deserializable into a crypto.PubKey: + // like other crypto.Pubkey implementations (e.g. ed25519.ThresholdMultisigPubKey), + // ThresholdMultisigPubKey should be deserializable into a crypto.ThresholdMultisigPubKey: var pubKey crypto.PubKey err = cdc.UnmarshalBinaryLengthPrefixed(ab, &pubKey) require.NoError(t, err) @@ -166,9 +168,9 @@ func TestPubKeyMultisigThresholdAminoToIface(t *testing.T) { require.Equal(t, multisigKey, pubKey) } -func generatePubKeysAndSignatures(n int, msg []byte) (pubkeys []crypto.PubKey, signatures [][]byte) { +func generatePubKeysAndSignatures(n int, msg []byte) (pubkeys []crypto.PubKey, signatures []types.SignatureData) { pubkeys = make([]crypto.PubKey, n) - signatures = make([][]byte, n) + signatures = make([]types.SignatureData, n) for i := 0; i < n; i++ { var privkey crypto.PrivKey switch rand.Int63() % 3 { @@ -180,7 +182,8 @@ func generatePubKeysAndSignatures(n int, msg []byte) (pubkeys []crypto.PubKey, s privkey = sr25519.GenPrivKey() } pubkeys[i] = privkey.PubKey() - signatures[i], _ = privkey.Sign(msg) + sig, _ := privkey.Sign(msg) + signatures[i] = &types.SingleSignatureData{Signature: sig} } return } diff --git a/crypto/types/codec.go b/crypto/types/codec.go new file mode 100644 index 000000000000..1230a5a02dca --- /dev/null +++ b/crypto/types/codec.go @@ -0,0 +1,38 @@ +package types + +import ( + "github.com/tendermint/tendermint/crypto" +) + +type PublicKeyCodec interface { + Decode(key *PublicKey) (crypto.PubKey, error) + Encode(key crypto.PubKey) (*PublicKey, error) +} + +type publicKeyCodecCacheMiddleware struct { + cdc PublicKeyCodec +} + +func CacheWrapCodec(cdc PublicKeyCodec) PublicKeyCodec { + return publicKeyCodecCacheMiddleware{cdc: cdc} +} + +var _ PublicKeyCodec = publicKeyCodecCacheMiddleware{} + +func (p publicKeyCodecCacheMiddleware) Decode(key *PublicKey) (crypto.PubKey, error) { + res, err := p.cdc.Decode(key) + if err != nil { + return nil, err + } + key.cachedValue = res + return res, nil +} + +func (p publicKeyCodecCacheMiddleware) Encode(key crypto.PubKey) (*PublicKey, error) { + res, err := p.cdc.Encode(key) + if err != nil { + return nil, err + } + res.cachedValue = key + return res, nil +} diff --git a/crypto/types/types.go b/crypto/types/types.go new file mode 100644 index 000000000000..16cfbd36b840 --- /dev/null +++ b/crypto/types/types.go @@ -0,0 +1,42 @@ +package types + +import ( + "fmt" + + "github.com/tendermint/tendermint/crypto" +) + +// PublicKey specifies a public key +type PublicKey struct { + // sum specifies which type of public key is wrapped + // + // Types that are valid to be assigned to Sum: + // *PublicKey_Secp256K1 + // *PublicKey_Ed25519 + // *PublicKey_Sr25519 + // *PublicKey_Multisig + // *PublicKey_Secp256R1 + // *PublicKey_AminoMultisig + // *PublicKey_AnyPubkey + Sum isPublicKey_Sum `protobuf_oneof:"sum"` + + cachedValue crypto.PubKey +} + +// GetCachedPubKey returns the cached PubKey instance wrapped in the PublicKey. +// This will only be set if the PublicKeyCodec is cache-wrapped using CacheWrapCodec +func (pk PublicKey) GetCachedPubKey() crypto.PubKey { + return pk.cachedValue +} + +func DecodeMultisignatures(bz []byte) ([][]byte, error) { + multisig := MultiSignature{} + err := multisig.Unmarshal(bz) + if err != nil { + return nil, err + } + if len(multisig.XXX_unrecognized) > 0 { + return nil, fmt.Errorf("rejecting unrecognized fields found in MultiSignature") + } + return multisig.Signatures, nil +} diff --git a/crypto/types/types.pb.go b/crypto/types/types.pb.go index 6887feafd90f..db28309be5a2 100644 --- a/crypto/types/types.pb.go +++ b/crypto/types/types.pb.go @@ -24,20 +24,6 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// PublicKey specifies a public key -type PublicKey struct { - // sum specifies which type of public key is wrapped - // - // Types that are valid to be assigned to Sum: - // *PublicKey_Secp256K1 - // *PublicKey_Ed25519 - // *PublicKey_Sr25519 - // *PublicKey_Multisig - // *PublicKey_Secp256R1 - // *PublicKey_AnyPubkey - Sum isPublicKey_Sum `protobuf_oneof:"sum"` -} - func (m *PublicKey) Reset() { *m = PublicKey{} } func (m *PublicKey) String() string { return proto.CompactTextString(m) } func (*PublicKey) ProtoMessage() {} @@ -92,16 +78,20 @@ type PublicKey_Multisig struct { type PublicKey_Secp256R1 struct { Secp256R1 []byte `protobuf:"bytes,5,opt,name=secp256r1,proto3,oneof" json:"secp256r1,omitempty"` } +type PublicKey_AminoMultisig struct { + AminoMultisig *LegacyAminoPubKeyMultisigThreshold `protobuf:"bytes,6,opt,name=amino_multisig,json=aminoMultisig,proto3,oneof" json:"amino_multisig,omitempty"` +} type PublicKey_AnyPubkey struct { AnyPubkey *types.Any `protobuf:"bytes,15,opt,name=any_pubkey,json=anyPubkey,proto3,oneof" json:"any_pubkey,omitempty"` } -func (*PublicKey_Secp256K1) isPublicKey_Sum() {} -func (*PublicKey_Ed25519) isPublicKey_Sum() {} -func (*PublicKey_Sr25519) isPublicKey_Sum() {} -func (*PublicKey_Multisig) isPublicKey_Sum() {} -func (*PublicKey_Secp256R1) isPublicKey_Sum() {} -func (*PublicKey_AnyPubkey) isPublicKey_Sum() {} +func (*PublicKey_Secp256K1) isPublicKey_Sum() {} +func (*PublicKey_Ed25519) isPublicKey_Sum() {} +func (*PublicKey_Sr25519) isPublicKey_Sum() {} +func (*PublicKey_Multisig) isPublicKey_Sum() {} +func (*PublicKey_Secp256R1) isPublicKey_Sum() {} +func (*PublicKey_AminoMultisig) isPublicKey_Sum() {} +func (*PublicKey_AnyPubkey) isPublicKey_Sum() {} func (m *PublicKey) GetSum() isPublicKey_Sum { if m != nil { @@ -145,6 +135,13 @@ func (m *PublicKey) GetSecp256R1() []byte { return nil } +func (m *PublicKey) GetAminoMultisig() *LegacyAminoPubKeyMultisigThreshold { + if x, ok := m.GetSum().(*PublicKey_AminoMultisig); ok { + return x.AminoMultisig + } + return nil +} + func (m *PublicKey) GetAnyPubkey() *types.Any { if x, ok := m.GetSum().(*PublicKey_AnyPubkey); ok { return x.AnyPubkey @@ -160,6 +157,7 @@ func (*PublicKey) XXX_OneofWrappers() []interface{} { (*PublicKey_Sr25519)(nil), (*PublicKey_Multisig)(nil), (*PublicKey_Secp256R1)(nil), + (*PublicKey_AminoMultisig)(nil), (*PublicKey_AnyPubkey)(nil), } } @@ -168,7 +166,7 @@ func (*PublicKey) XXX_OneofWrappers() []interface{} { // keys and a threshold type PubKeyMultisigThreshold struct { K uint32 `protobuf:"varint,1,opt,name=threshold,proto3" json:"threshold,omitempty" yaml:"threshold"` - PubKeys []*PublicKey `protobuf:"bytes,2,rep,name=pubkeys,proto3" json:"pubkeys,omitempty" yaml:"pubkeys"` + PubKeys []*PublicKey `protobuf:"bytes,2,rep,name=public_keys,json=publicKeys,proto3" json:"public_keys,omitempty" yaml:"pubkeys"` } func (m *PubKeyMultisigThreshold) Reset() { *m = PubKeyMultisigThreshold{} } @@ -222,7 +220,8 @@ func (m *PubKeyMultisigThreshold) GetPubKeys() []*PublicKey { // See cosmos_sdk.tx.v1.ModeInfo.Multi for how to specify which signers signed // and with which modes type MultiSignature struct { - Sigs [][]byte `protobuf:"bytes,1,rep,name=sigs,proto3" json:"sigs,omitempty"` + Signatures [][]byte `protobuf:"bytes,1,rep,name=signatures,proto3" json:"signatures,omitempty"` + XXX_unrecognized []byte `json:"-"` } func (m *MultiSignature) Reset() { *m = MultiSignature{} } @@ -258,9 +257,9 @@ func (m *MultiSignature) XXX_DiscardUnknown() { var xxx_messageInfo_MultiSignature proto.InternalMessageInfo -func (m *MultiSignature) GetSigs() [][]byte { +func (m *MultiSignature) GetSignatures() [][]byte { if m != nil { - return m.Sigs + return m.Signatures } return nil } @@ -320,49 +319,110 @@ func (m *CompactBitArray) GetElems() []byte { return nil } +// LegacyAminoPubKeyMultisigThreshold specifies a PubKeyMultisigThreshold that +// uses a legacy amino address which is passed along with the key. This type of +// key can only be used with existing accounts in state as the address is hard-coded +type LegacyAminoPubKeyMultisigThreshold struct { + Key *PubKeyMultisigThreshold `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Address []byte `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` +} + +func (m *LegacyAminoPubKeyMultisigThreshold) Reset() { *m = LegacyAminoPubKeyMultisigThreshold{} } +func (m *LegacyAminoPubKeyMultisigThreshold) String() string { return proto.CompactTextString(m) } +func (*LegacyAminoPubKeyMultisigThreshold) ProtoMessage() {} +func (*LegacyAminoPubKeyMultisigThreshold) Descriptor() ([]byte, []int) { + return fileDescriptor_2165b2a1badb1b0c, []int{4} +} +func (m *LegacyAminoPubKeyMultisigThreshold) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *LegacyAminoPubKeyMultisigThreshold) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_LegacyAminoPubKeyMultisigThreshold.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 *LegacyAminoPubKeyMultisigThreshold) XXX_Merge(src proto.Message) { + xxx_messageInfo_LegacyAminoPubKeyMultisigThreshold.Merge(m, src) +} +func (m *LegacyAminoPubKeyMultisigThreshold) XXX_Size() int { + return m.Size() +} +func (m *LegacyAminoPubKeyMultisigThreshold) XXX_DiscardUnknown() { + xxx_messageInfo_LegacyAminoPubKeyMultisigThreshold.DiscardUnknown(m) +} + +var xxx_messageInfo_LegacyAminoPubKeyMultisigThreshold proto.InternalMessageInfo + +func (m *LegacyAminoPubKeyMultisigThreshold) GetKey() *PubKeyMultisigThreshold { + if m != nil { + return m.Key + } + return nil +} + +func (m *LegacyAminoPubKeyMultisigThreshold) GetAddress() []byte { + if m != nil { + return m.Address + } + return nil +} + func init() { proto.RegisterType((*PublicKey)(nil), "cosmos_sdk.crypto.v1.PublicKey") proto.RegisterType((*PubKeyMultisigThreshold)(nil), "cosmos_sdk.crypto.v1.PubKeyMultisigThreshold") proto.RegisterType((*MultiSignature)(nil), "cosmos_sdk.crypto.v1.MultiSignature") proto.RegisterType((*CompactBitArray)(nil), "cosmos_sdk.crypto.v1.CompactBitArray") + proto.RegisterType((*LegacyAminoPubKeyMultisigThreshold)(nil), "cosmos_sdk.crypto.v1.LegacyAminoPubKeyMultisigThreshold") } func init() { proto.RegisterFile("crypto/types/types.proto", fileDescriptor_2165b2a1badb1b0c) } var fileDescriptor_2165b2a1badb1b0c = []byte{ - // 501 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x52, 0xcd, 0x6a, 0xdb, 0x40, - 0x18, 0x94, 0xec, 0xb8, 0x8e, 0x37, 0x69, 0xdc, 0x2e, 0x86, 0x2a, 0x86, 0x4a, 0x46, 0x94, 0xe2, - 0x16, 0x22, 0x61, 0x17, 0xb7, 0x34, 0xb7, 0x28, 0x97, 0x80, 0x29, 0x18, 0xa5, 0x87, 0x52, 0x28, - 0x42, 0x3f, 0x5b, 0x79, 0xb1, 0xa4, 0x15, 0xbb, 0xab, 0xd2, 0x7d, 0x89, 0xd2, 0x63, 0x8f, 0xe9, - 0xbd, 0x0f, 0xd2, 0x63, 0x8e, 0x3d, 0x99, 0x22, 0xbf, 0x41, 0x9e, 0xa0, 0x44, 0x2b, 0xc5, 0xa1, - 0x24, 0x17, 0x69, 0xf7, 0x9b, 0xf9, 0x46, 0x33, 0xdf, 0x27, 0xa0, 0x85, 0x54, 0xe4, 0x9c, 0xd8, - 0x5c, 0xe4, 0x88, 0xc9, 0xa7, 0x95, 0x53, 0xc2, 0x09, 0x1c, 0x84, 0x84, 0xa5, 0x84, 0x79, 0x2c, - 0x5a, 0x59, 0x92, 0x64, 0x7d, 0x99, 0x0c, 0x9f, 0xf3, 0x25, 0xa6, 0x91, 0x97, 0xfb, 0x94, 0x0b, - 0xbb, 0x22, 0xda, 0x31, 0x89, 0xc9, 0xf6, 0x24, 0xbb, 0x87, 0x87, 0x31, 0x21, 0x71, 0x82, 0x24, - 0x25, 0x28, 0x3e, 0xdb, 0x7e, 0x26, 0x24, 0x64, 0x7e, 0x6b, 0x81, 0xde, 0xa2, 0x08, 0x12, 0x1c, - 0xce, 0x91, 0x80, 0x3a, 0xe8, 0x31, 0x14, 0xe6, 0xd3, 0xd9, 0xeb, 0xd5, 0x44, 0x53, 0x47, 0xea, - 0x78, 0xff, 0x4c, 0x71, 0xb7, 0x25, 0x38, 0x04, 0x5d, 0x14, 0x4d, 0x67, 0xb3, 0xc9, 0x5b, 0xad, - 0x55, 0xa3, 0x4d, 0xe1, 0x1a, 0x63, 0x54, 0x62, 0xed, 0x06, 0xab, 0x0b, 0x70, 0x0e, 0x76, 0xd3, - 0x22, 0xe1, 0x98, 0xe1, 0x58, 0xdb, 0x19, 0xa9, 0xe3, 0xbd, 0xe9, 0x91, 0x75, 0x57, 0x22, 0x6b, - 0x51, 0x04, 0x73, 0x24, 0xde, 0xd5, 0xdc, 0xf7, 0x4b, 0x8a, 0xd8, 0x92, 0x24, 0xd1, 0x99, 0xe2, - 0xde, 0x08, 0xdc, 0x32, 0x49, 0x27, 0x5a, 0xe7, 0x3f, 0x93, 0x74, 0x02, 0x67, 0x00, 0xf8, 0x99, - 0xf0, 0xf2, 0x22, 0x58, 0x21, 0xa1, 0xf5, 0xab, 0xcf, 0x0d, 0x2c, 0x39, 0x02, 0xab, 0x19, 0x81, - 0x75, 0x92, 0x89, 0xeb, 0x36, 0x3f, 0x13, 0x8b, 0x8a, 0xe8, 0x74, 0x40, 0x9b, 0x15, 0xa9, 0xf9, - 0x4b, 0x05, 0x4f, 0xee, 0x71, 0x01, 0xdf, 0x80, 0x1e, 0x6f, 0x2e, 0xd5, 0x78, 0x1e, 0x3a, 0x87, - 0xe5, 0xda, 0x50, 0xe7, 0x57, 0x6b, 0xe3, 0x91, 0xf0, 0xd3, 0xe4, 0xd8, 0xbc, 0xc1, 0x4d, 0x77, - 0xcb, 0x85, 0x1f, 0x40, 0x57, 0xda, 0x61, 0x5a, 0x6b, 0xd4, 0x1e, 0xef, 0x4d, 0x8d, 0x7b, 0xe3, - 0xcb, 0x4d, 0x38, 0x4f, 0xcb, 0xb5, 0xd1, 0x95, 0x3e, 0xd8, 0xd5, 0xda, 0x38, 0x90, 0xea, 0xb5, - 0x88, 0xe9, 0x36, 0x72, 0xe6, 0x33, 0x70, 0x50, 0xf9, 0x3c, 0xc7, 0x71, 0xe6, 0xf3, 0x82, 0x22, - 0x08, 0xc1, 0x0e, 0xc3, 0x31, 0xd3, 0xd4, 0x51, 0x7b, 0xbc, 0xef, 0x56, 0x67, 0xf3, 0x13, 0xe8, - 0x9f, 0x92, 0x34, 0xf7, 0x43, 0xee, 0x60, 0x7e, 0x42, 0xa9, 0x2f, 0xe0, 0x4b, 0xf0, 0x18, 0x7d, - 0xe5, 0xd4, 0xf7, 0x02, 0xcc, 0x99, 0xc7, 0x38, 0xa1, 0xa8, 0xce, 0xe4, 0xf6, 0x2b, 0xc0, 0xc1, - 0x9c, 0x9d, 0x57, 0x65, 0x38, 0x00, 0x1d, 0x94, 0xa0, 0x94, 0xc9, 0xa5, 0xbb, 0xf2, 0x72, 0xbc, - 0xfb, 0xe3, 0xc2, 0x50, 0x2e, 0x7e, 0x1a, 0x8a, 0x73, 0xfa, 0xbb, 0xd4, 0xd5, 0xcb, 0x52, 0x57, - 0xff, 0x96, 0xba, 0xfa, 0x7d, 0xa3, 0x2b, 0x97, 0x1b, 0x5d, 0xf9, 0xb3, 0xd1, 0x95, 0x8f, 0x2f, - 0x62, 0xcc, 0x97, 0x45, 0x60, 0x85, 0x24, 0xb5, 0x65, 0xe2, 0xfa, 0x75, 0xc4, 0xa2, 0x95, 0x7d, - 0xfb, 0x77, 0x0f, 0x1e, 0x54, 0xab, 0x79, 0xf5, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x1e, 0xd7, 0x43, - 0xb2, 0x05, 0x03, 0x00, 0x00, + // 582 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x53, 0x4d, 0x8b, 0xd3, 0x4e, + 0x1c, 0x4e, 0xb6, 0xfb, 0x3a, 0xfb, 0xf6, 0xff, 0x0f, 0x0b, 0x66, 0x17, 0x4c, 0x4a, 0x0e, 0x52, + 0x85, 0x4d, 0x68, 0xa5, 0xab, 0xf6, 0x22, 0x9b, 0xbd, 0x2c, 0x54, 0xa1, 0x64, 0x3d, 0x09, 0x12, + 0x26, 0xc9, 0x98, 0x86, 0x26, 0x99, 0x30, 0x33, 0x11, 0xe7, 0xe4, 0x57, 0xf0, 0xe8, 0x71, 0xfb, + 0x19, 0xfc, 0x12, 0x1e, 0x7b, 0xf4, 0x54, 0xa4, 0xfd, 0x02, 0xb2, 0x17, 0xaf, 0xd2, 0x4c, 0xd3, + 0x16, 0xd9, 0x22, 0x78, 0x49, 0xf2, 0xfb, 0x3d, 0xcf, 0xcc, 0xf3, 0xfc, 0x5e, 0x02, 0xb4, 0x80, + 0x8a, 0x9c, 0x13, 0x9b, 0x8b, 0x1c, 0x33, 0xf9, 0xb4, 0x72, 0x4a, 0x38, 0x81, 0x27, 0x01, 0x61, + 0x29, 0x61, 0x1e, 0x0b, 0x07, 0x96, 0x24, 0x59, 0x1f, 0x9a, 0x67, 0x8f, 0x78, 0x3f, 0xa6, 0xa1, + 0x97, 0x23, 0xca, 0x85, 0x5d, 0x12, 0xed, 0x88, 0x44, 0x64, 0xf9, 0x25, 0x4f, 0x9f, 0x9d, 0x46, + 0x84, 0x44, 0x09, 0x96, 0x14, 0xbf, 0x78, 0x6f, 0xa3, 0x4c, 0x48, 0xc8, 0xfc, 0xb5, 0x01, 0xf6, + 0x7a, 0x85, 0x9f, 0xc4, 0x41, 0x17, 0x0b, 0xa8, 0x83, 0x3d, 0x86, 0x83, 0xbc, 0xd5, 0xbe, 0x18, + 0x34, 0x35, 0xb5, 0xae, 0x36, 0x0e, 0xae, 0x15, 0x77, 0x99, 0x82, 0x67, 0x60, 0x07, 0x87, 0xad, + 0x76, 0xbb, 0xf9, 0x42, 0xdb, 0x98, 0xa3, 0x55, 0x62, 0x86, 0x31, 0x2a, 0xb1, 0x5a, 0x85, 0xcd, + 0x13, 0xb0, 0x0b, 0x76, 0xd3, 0x22, 0xe1, 0x31, 0x8b, 0x23, 0x6d, 0xb3, 0xae, 0x36, 0xf6, 0x5b, + 0xe7, 0xd6, 0x7d, 0x15, 0x59, 0xbd, 0xc2, 0xef, 0x62, 0xf1, 0x7a, 0xce, 0x7d, 0xd3, 0xa7, 0x98, + 0xf5, 0x49, 0x12, 0x5e, 0x2b, 0xee, 0xe2, 0x82, 0x15, 0x93, 0xb4, 0xa9, 0x6d, 0xfd, 0x61, 0x92, + 0x36, 0x21, 0x02, 0x47, 0x28, 0x8d, 0x33, 0xe2, 0x2d, 0x24, 0xb7, 0x4b, 0xc9, 0xe7, 0xf7, 0x4b, + 0xbe, 0xc2, 0x11, 0x0a, 0xc4, 0xe5, 0xec, 0xc4, 0x7a, 0xf5, 0xc3, 0xf2, 0xc6, 0x0a, 0x81, 0x6d, + 0x00, 0x50, 0x26, 0xbc, 0xbc, 0xf0, 0x07, 0x58, 0x68, 0xc7, 0xe5, 0xf5, 0x27, 0x96, 0xec, 0xb2, + 0x55, 0x75, 0xd9, 0xba, 0xcc, 0xc4, 0xcc, 0x19, 0xca, 0x44, 0xaf, 0x24, 0x76, 0x36, 0x7f, 0x0e, + 0x0d, 0xc5, 0xd9, 0x02, 0x35, 0x56, 0xa4, 0xe6, 0x57, 0x15, 0x3c, 0x58, 0x23, 0x08, 0x9f, 0x81, + 0x3d, 0x5e, 0x05, 0xe5, 0x1c, 0x0e, 0x9d, 0xd3, 0xc9, 0xd8, 0x50, 0xbb, 0x77, 0x63, 0xe3, 0x3f, + 0x81, 0xd2, 0xa4, 0x63, 0x2e, 0x70, 0xd3, 0x5d, 0x72, 0xa1, 0x07, 0xf6, 0xf3, 0x72, 0x9a, 0xde, + 0x00, 0x0b, 0xa6, 0x6d, 0xd4, 0x6b, 0x8d, 0xfd, 0x96, 0xb1, 0xb6, 0xd7, 0x72, 0xec, 0xce, 0xc3, + 0xc9, 0xd8, 0xd8, 0x91, 0x5e, 0xd8, 0xdd, 0xd8, 0x38, 0x92, 0x0a, 0xb2, 0x3a, 0x66, 0xba, 0x20, + 0xaf, 0x98, 0xcc, 0xbc, 0x00, 0x47, 0xa5, 0xdd, 0x9b, 0x38, 0xca, 0x10, 0x2f, 0x28, 0x86, 0x3a, + 0x00, 0xac, 0x0a, 0x98, 0xa6, 0xd6, 0x6b, 0x8d, 0x03, 0x77, 0x25, 0xd3, 0xd9, 0x1c, 0x0d, 0x0d, + 0xd5, 0x7c, 0x07, 0x8e, 0xaf, 0x48, 0x9a, 0xa3, 0x80, 0x3b, 0x31, 0xbf, 0xa4, 0x14, 0x09, 0xf8, + 0x04, 0xfc, 0x8f, 0x3f, 0x72, 0x8a, 0x3c, 0x3f, 0xe6, 0xcc, 0x63, 0x9c, 0x50, 0x3c, 0x2f, 0xd6, + 0x3d, 0x2e, 0x01, 0x27, 0xe6, 0xec, 0xa6, 0x4c, 0xc3, 0x13, 0xb0, 0x85, 0x13, 0x9c, 0x32, 0xb9, + 0x76, 0xae, 0x0c, 0x3a, 0xbb, 0x5f, 0x6e, 0x0d, 0xe5, 0x76, 0x68, 0x28, 0xe6, 0x27, 0x60, 0xfe, + 0x7d, 0x8e, 0xf0, 0x25, 0xa8, 0xcd, 0xe6, 0xa5, 0xfe, 0xc3, 0x06, 0xba, 0xb3, 0x93, 0x50, 0x03, + 0x3b, 0x28, 0x0c, 0x29, 0x66, 0x95, 0x91, 0x2a, 0x74, 0xae, 0xbe, 0x4d, 0x74, 0x75, 0x34, 0xd1, + 0xd5, 0x1f, 0x13, 0x5d, 0xfd, 0x3c, 0xd5, 0x95, 0xd1, 0x54, 0x57, 0xbe, 0x4f, 0x75, 0xe5, 0xed, + 0xe3, 0x28, 0xe6, 0xfd, 0xc2, 0xb7, 0x02, 0x92, 0xda, 0x52, 0x71, 0xfe, 0x3a, 0x67, 0xe1, 0xc0, + 0x5e, 0xfd, 0xe3, 0xfd, 0xed, 0x72, 0x75, 0x9e, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x3b, 0x56, + 0xa0, 0xa2, 0x08, 0x04, 0x00, 0x00, } func (m *PublicKey) Marshal() (dAtA []byte, err error) { @@ -482,6 +542,27 @@ func (m *PublicKey_Secp256R1) MarshalToSizedBuffer(dAtA []byte) (int, error) { } return len(dAtA) - i, nil } +func (m *PublicKey_AminoMultisig) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PublicKey_AminoMultisig) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + if m.AminoMultisig != nil { + { + size, err := m.AminoMultisig.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + return len(dAtA) - i, nil +} func (m *PublicKey_AnyPubkey) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) @@ -565,11 +646,15 @@ func (m *MultiSignature) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.Sigs) > 0 { - for iNdEx := len(m.Sigs) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Sigs[iNdEx]) - copy(dAtA[i:], m.Sigs[iNdEx]) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Sigs[iNdEx]))) + if m.XXX_unrecognized != nil { + i -= len(m.XXX_unrecognized) + copy(dAtA[i:], m.XXX_unrecognized) + } + if len(m.Signatures) > 0 { + for iNdEx := len(m.Signatures) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Signatures[iNdEx]) + copy(dAtA[i:], m.Signatures[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Signatures[iNdEx]))) i-- dAtA[i] = 0xa } @@ -612,6 +697,48 @@ func (m *CompactBitArray) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *LegacyAminoPubKeyMultisigThreshold) 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 *LegacyAminoPubKeyMultisigThreshold) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *LegacyAminoPubKeyMultisigThreshold) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0x12 + } + if m.Key != nil { + { + size, err := m.Key.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { offset -= sovTypes(v) base := offset @@ -695,6 +822,18 @@ func (m *PublicKey_Secp256R1) Size() (n int) { } return n } +func (m *PublicKey_AminoMultisig) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.AminoMultisig != nil { + l = m.AminoMultisig.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} func (m *PublicKey_AnyPubkey) Size() (n int) { if m == nil { return 0 @@ -731,12 +870,32 @@ func (m *MultiSignature) Size() (n int) { } var l int _ = l - if len(m.Sigs) > 0 { - for _, b := range m.Sigs { + if len(m.Signatures) > 0 { + for _, b := range m.Signatures { l = len(b) n += 1 + l + sovTypes(uint64(l)) } } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func (m *LegacyAminoPubKeyMultisigThreshold) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Key != nil { + l = m.Key.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } return n } @@ -942,6 +1101,41 @@ func (m *PublicKey) Unmarshal(dAtA []byte) error { copy(v, dAtA[iNdEx:postIndex]) m.Sum = &PublicKey_Secp256R1{v} iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AminoMultisig", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + v := &LegacyAminoPubKeyMultisigThreshold{} + if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + m.Sum = &PublicKey_AminoMultisig{v} + iNdEx = postIndex case 15: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field AnyPubkey", wireType) @@ -1138,7 +1332,7 @@ func (m *MultiSignature) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sigs", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -1165,8 +1359,8 @@ func (m *MultiSignature) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Sigs = append(m.Sigs, make([]byte, postIndex-iNdEx)) - copy(m.Sigs[len(m.Sigs)-1], dAtA[iNdEx:postIndex]) + m.Signatures = append(m.Signatures, make([]byte, postIndex-iNdEx)) + copy(m.Signatures[len(m.Signatures)-1], dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -1183,6 +1377,7 @@ func (m *MultiSignature) Unmarshal(dAtA []byte) error { if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } @@ -1298,6 +1493,129 @@ func (m *CompactBitArray) Unmarshal(dAtA []byte) error { } return nil } +func (m *LegacyAminoPubKeyMultisigThreshold) 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 ErrIntOverflowTypes + } + 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: LegacyAminoPubKeyMultisigThreshold: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: LegacyAminoPubKeyMultisigThreshold: 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 msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Key == nil { + m.Key = &PubKeyMultisigThreshold{} + } + if err := m.Key.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipTypes(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/crypto/types/types.proto b/crypto/types/types.proto index 2496ad8e30d6..104d7e52941b 100644 --- a/crypto/types/types.proto +++ b/crypto/types/types.proto @@ -10,30 +10,34 @@ option go_package = "github.com/cosmos/cosmos-sdk/crypto/types"; message PublicKey { // sum specifies which type of public key is wrapped oneof sum { - bytes secp256k1 = 1; - bytes ed25519 = 2; - bytes sr25519 = 3; - PubKeyMultisigThreshold multisig = 4; - bytes secp256r1 = 5; + bytes secp256k1 = 1; + bytes ed25519 = 2; + bytes sr25519 = 3; + PubKeyMultisigThreshold multisig = 4; + bytes secp256r1 = 5; + LegacyAminoPubKeyMultisigThreshold amino_multisig = 6; // any_pubkey can be used for any pubkey that an app may use which is // not explicitly defined in the oneof google.protobuf.Any any_pubkey = 15; // 15 is largest field that occupies one byte } + + option (gogoproto.typedecl) = false; } // PubKeyMultisigThreshold specifies a public key type which nests multiple public // keys and a threshold message PubKeyMultisigThreshold { uint32 threshold = 1 [(gogoproto.customname) = "K", (gogoproto.moretags) = "yaml:\"threshold\""]; - repeated PublicKey pubkeys = 2 [(gogoproto.customname) = "PubKeys", (gogoproto.moretags) = "yaml:\"pubkeys\""]; + repeated PublicKey public_keys = 2 [(gogoproto.customname) = "PubKeys", (gogoproto.moretags) = "yaml:\"pubkeys\""]; } // MultiSignature wraps the signatures from a PubKeyMultisigThreshold. // See cosmos_sdk.tx.v1.ModeInfo.Multi for how to specify which signers signed // and with which modes message MultiSignature { - repeated bytes sigs = 1; + option (gogoproto.goproto_unrecognized) = true; + repeated bytes signatures = 1; } // CompactBitArray is an implementation of a space efficient bit array. @@ -47,3 +51,11 @@ message CompactBitArray { uint32 extra_bits_stored = 1; bytes elems = 2; } + +// LegacyAminoPubKeyMultisigThreshold specifies a PubKeyMultisigThreshold that +// uses a legacy amino address which is passed along with the key. This type of +// key can only be used with existing accounts in state as the address is hard-coded +message LegacyAminoPubKeyMultisigThreshold { + PubKeyMultisigThreshold key = 1; + bytes address = 2; +} diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 443645cdba03..1f3039f52239 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -4,6 +4,7 @@ package server import ( "fmt" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/spf13/cobra" "github.com/spf13/viper" diff --git a/simapp/amino.go b/simapp/amino.go new file mode 100644 index 000000000000..f0b905ba62bf --- /dev/null +++ b/simapp/amino.go @@ -0,0 +1,30 @@ +// +build test_amino + +package simapp + +import ( + "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/ibc" +) + +func AminoJSONTxDecoder(cfg params.EncodingConfig) types.TxDecoder { + return func(txBytes []byte) (types.Tx, error) { + var tx authtypes.StdTx + err := cfg.Marshaler.UnmarshalJSON(txBytes, &tx) + if err != nil { + return nil, err + } + return tx, nil + } +} + +func NewAnteHandler(ak auth.AccountKeeper, bk bank.Keeper, ibcK ibc.Keeper) types.AnteHandler { + return ante.NewAnteHandler( + ak, bk, ibcK, ante.DefaultSigVerificationGasConsumer, + ) +} diff --git a/simapp/app.go b/simapp/app.go index 7835fa284368..3259380b443b 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -4,6 +4,8 @@ import ( "io" "os" + params2 "github.com/cosmos/cosmos-sdk/simapp/params" + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tmos "github.com/tendermint/tendermint/libs/os" @@ -18,7 +20,6 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/capability" "github.com/cosmos/cosmos-sdk/x/crisis" @@ -96,8 +97,9 @@ var _ App = (*SimApp)(nil) // capabilities aren't needed for testing. type SimApp struct { *baseapp.BaseApp - cdc *codec.Codec - appCodec *std.Codec + amino *codec.Codec + marshaler codec.Marshaler + encodingConfig params2.EncodingConfig invCheckPeriod uint @@ -142,10 +144,11 @@ func NewSimApp( homePath string, invCheckPeriod uint, baseAppOptions ...func(*baseapp.BaseApp), ) *SimApp { - // TODO: Remove cdc in favor of appCodec once all modules are migrated. - appCodec, cdc := MakeCodecs() + // TODO: Remove amino in favor of marshaler once all modules are migrated. + encodingConfig := MakeEncodingConfig() + marshaler := encodingConfig.Marshaler - bApp := baseapp.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) + bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxGenerator.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetAppVersion(version.Version) @@ -160,8 +163,9 @@ func NewSimApp( app := &SimApp{ BaseApp: bApp, - cdc: cdc, - appCodec: appCodec, + amino: encodingConfig.Amino, + marshaler: encodingConfig.Marshaler, + encodingConfig: encodingConfig, invCheckPeriod: invCheckPeriod, keys: keys, tkeys: tkeys, @@ -170,7 +174,7 @@ func NewSimApp( } // init params keeper and subspaces - app.ParamsKeeper = params.NewKeeper(appCodec, keys[params.StoreKey], tkeys[params.TStoreKey]) + app.ParamsKeeper = params.NewKeeper(marshaler, keys[params.StoreKey], tkeys[params.TStoreKey]) app.subspaces[auth.ModuleName] = app.ParamsKeeper.Subspace(auth.DefaultParamspace) app.subspaces[bank.ModuleName] = app.ParamsKeeper.Subspace(bank.DefaultParamspace) app.subspaces[staking.ModuleName] = app.ParamsKeeper.Subspace(staking.DefaultParamspace) @@ -184,35 +188,35 @@ func NewSimApp( bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(std.ConsensusParamsKeyTable())) // add capability keeper and ScopeToModule for ibc module - app.CapabilityKeeper = capability.NewKeeper(appCodec, keys[capability.StoreKey], memKeys[capability.MemStoreKey]) + app.CapabilityKeeper = capability.NewKeeper(marshaler, keys[capability.StoreKey], memKeys[capability.MemStoreKey]) scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibc.ModuleName) scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(transfer.ModuleName) // add keepers app.AccountKeeper = auth.NewAccountKeeper( - appCodec, keys[auth.StoreKey], app.subspaces[auth.ModuleName], auth.ProtoBaseAccount, maccPerms, + marshaler, keys[auth.StoreKey], app.subspaces[auth.ModuleName], auth.ProtoBaseAccount, maccPerms, ) app.BankKeeper = bank.NewBaseKeeper( - appCodec, keys[bank.StoreKey], app.AccountKeeper, app.subspaces[bank.ModuleName], app.BlacklistedAccAddrs(), + marshaler, keys[bank.StoreKey], app.AccountKeeper, app.subspaces[bank.ModuleName], app.BlacklistedAccAddrs(), ) stakingKeeper := staking.NewKeeper( - appCodec, keys[staking.StoreKey], app.AccountKeeper, app.BankKeeper, app.subspaces[staking.ModuleName], + marshaler, keys[staking.StoreKey], app.AccountKeeper, app.BankKeeper, app.subspaces[staking.ModuleName], ) app.MintKeeper = mint.NewKeeper( - appCodec, keys[mint.StoreKey], app.subspaces[mint.ModuleName], &stakingKeeper, + marshaler, keys[mint.StoreKey], app.subspaces[mint.ModuleName], &stakingKeeper, app.AccountKeeper, app.BankKeeper, auth.FeeCollectorName, ) app.DistrKeeper = distr.NewKeeper( - appCodec, keys[distr.StoreKey], app.subspaces[distr.ModuleName], app.AccountKeeper, app.BankKeeper, + marshaler, keys[distr.StoreKey], app.subspaces[distr.ModuleName], app.AccountKeeper, app.BankKeeper, &stakingKeeper, auth.FeeCollectorName, app.ModuleAccountAddrs(), ) app.SlashingKeeper = slashing.NewKeeper( - appCodec, keys[slashing.StoreKey], &stakingKeeper, app.subspaces[slashing.ModuleName], + marshaler, keys[slashing.StoreKey], &stakingKeeper, app.subspaces[slashing.ModuleName], ) app.CrisisKeeper = crisis.NewKeeper( app.subspaces[crisis.ModuleName], invCheckPeriod, app.BankKeeper, auth.FeeCollectorName, ) - app.UpgradeKeeper = upgrade.NewKeeper(skipUpgradeHeights, keys[upgrade.StoreKey], appCodec, homePath) + app.UpgradeKeeper = upgrade.NewKeeper(skipUpgradeHeights, keys[upgrade.StoreKey], marshaler, homePath) // register the proposal types govRouter := gov.NewRouter() @@ -221,7 +225,7 @@ func NewSimApp( AddRoute(distr.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)). AddRoute(upgrade.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)) app.GovKeeper = gov.NewKeeper( - appCodec, keys[gov.StoreKey], app.subspaces[gov.ModuleName], app.AccountKeeper, app.BankKeeper, + marshaler, keys[gov.StoreKey], app.subspaces[gov.ModuleName], app.AccountKeeper, app.BankKeeper, &stakingKeeper, govRouter, ) @@ -235,12 +239,12 @@ func NewSimApp( // TODO: remove amino codec dependency once Tendermint version is upgraded with // protobuf changes app.IBCKeeper = ibc.NewKeeper( - app.cdc, appCodec, keys[ibc.StoreKey], app.StakingKeeper, scopedIBCKeeper, + app.amino, marshaler, keys[ibc.StoreKey], app.StakingKeeper, scopedIBCKeeper, ) // Create Transfer Keepers app.TransferKeeper = transfer.NewKeeper( - appCodec, keys[transfer.StoreKey], + marshaler, keys[transfer.StoreKey], app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, scopedTransferKeeper, ) @@ -253,7 +257,7 @@ func NewSimApp( // create evidence keeper with router evidenceKeeper := evidence.NewKeeper( - appCodec, keys[evidence.StoreKey], &app.StakingKeeper, app.SlashingKeeper, + marshaler, keys[evidence.StoreKey], &app.StakingKeeper, app.SlashingKeeper, ) evidenceRouter := evidence.NewRouter(). AddRoute(ibcclient.RouterKey, ibcclient.HandlerClientMisbehaviour(app.IBCKeeper.ClientKeeper)) @@ -264,16 +268,18 @@ func NewSimApp( // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. app.mm = module.NewManager( - genutil.NewAppModule(app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx), - auth.NewAppModule(appCodec, app.AccountKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), + genutil.NewAppModule( + app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx, + AminoJSONTxDecoder(encodingConfig), encodingConfig.TxGenerator.TxEncoder()), + auth.NewAppModule(marshaler, app.AccountKeeper), + bank.NewAppModule(marshaler, app.BankKeeper, app.AccountKeeper), + capability.NewAppModule(marshaler, *app.CapabilityKeeper), crisis.NewAppModule(&app.CrisisKeeper), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), + gov.NewAppModule(marshaler, app.GovKeeper, app.AccountKeeper, app.BankKeeper), + mint.NewAppModule(marshaler, app.MintKeeper, app.AccountKeeper), + slashing.NewAppModule(marshaler, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + distr.NewAppModule(marshaler, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + staking.NewAppModule(marshaler, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), upgrade.NewAppModule(app.UpgradeKeeper), evidence.NewAppModule(app.EvidenceKeeper), ibc.NewAppModule(app.IBCKeeper), @@ -314,14 +320,14 @@ func NewSimApp( // NOTE: this is not required apps that don't use the simulator for fuzz testing // transactions app.sm = module.NewSimulationManager( - auth.NewAppModule(appCodec, app.AccountKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + auth.NewAppModule(marshaler, app.AccountKeeper), + bank.NewAppModule(marshaler, app.BankKeeper, app.AccountKeeper), + capability.NewAppModule(marshaler, *app.CapabilityKeeper), + gov.NewAppModule(marshaler, app.GovKeeper, app.AccountKeeper, app.BankKeeper), + mint.NewAppModule(marshaler, app.MintKeeper, app.AccountKeeper), + staking.NewAppModule(marshaler, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), + distr.NewAppModule(marshaler, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), + slashing.NewAppModule(marshaler, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), params.NewAppModule(app.ParamsKeeper), evidence.NewAppModule(app.EvidenceKeeper), ibc.NewAppModule(app.IBCKeeper), @@ -339,9 +345,7 @@ func NewSimApp( app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetAnteHandler( - ante.NewAnteHandler( - app.AccountKeeper, app.BankKeeper, *app.IBCKeeper, ante.DefaultSigVerificationGasConsumer, - ), + NewAnteHandler(app.AccountKeeper, app.BankKeeper, *app.IBCKeeper), ) app.SetEndBlocker(app.EndBlocker) @@ -365,18 +369,6 @@ func NewSimApp( return app } -// MakeCodecs constructs the *std.Codec and *codec.Codec instances used by -// simapp. It is useful for tests and clients who do not want to construct the -// full simapp -func MakeCodecs() (*std.Codec, *codec.Codec) { - cdc := std.MakeCodec(ModuleBasics) - interfaceRegistry := types.NewInterfaceRegistry() - std.RegisterInterfaces(interfaceRegistry) - ModuleBasics.RegisterInterfaceModules(interfaceRegistry) - appCodec := std.NewAppCodec(cdc, interfaceRegistry) - return appCodec, cdc -} - // Name returns the name of the App func (app *SimApp) Name() string { return app.BaseApp.Name() } @@ -393,8 +385,8 @@ func (app *SimApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.Re // InitChainer application update at chain initialization func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { var genesisState GenesisState - app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) - return app.mm.InitGenesis(ctx, app.cdc, genesisState) + app.amino.MustUnmarshalJSON(req.AppStateBytes, &genesisState) + return app.mm.InitGenesis(ctx, app.amino, genesisState) } // LoadHeight loads a particular height @@ -427,15 +419,23 @@ func (app *SimApp) BlacklistedAccAddrs() map[string]bool { // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. func (app *SimApp) Codec() *codec.Codec { - return app.cdc + return app.amino } // AppCodec returns SimApp's app codec. // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. -func (app *SimApp) AppCodec() *std.Codec { - return app.appCodec +func (app *SimApp) AppCodec() codec.Marshaler { + return app.marshaler +} + +// GetEncodingConfig returns SimApp's EncodingConfig +// +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *SimApp) GetEncodingConfig() params2.EncodingConfig { + return app.encodingConfig } // GetKey returns the KVStoreKey for the provided store key. diff --git a/simapp/cmd/simcli/amino.go b/simapp/cmd/simcli/amino.go new file mode 100644 index 000000000000..c04ac9e1d985 --- /dev/null +++ b/simapp/cmd/simcli/amino.go @@ -0,0 +1,19 @@ +// +build test_amino + +package main + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func MakeTxCLIContext() client.Context { + cliCtx := client.Context{} + aminoCdc := codec.NewAminoCodec(encodingConfig.Amino) + return cliCtx. + WithJSONMarshaler(aminoCdc). + WithTxGenerator(encodingConfig.TxGenerator). + WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)). + WithCodec(encodingConfig.Amino) +} diff --git a/simapp/cmd/simcli/main.go b/simapp/cmd/simcli/main.go index ee849b9189f3..27ded513c2c3 100644 --- a/simapp/cmd/simcli/main.go +++ b/simapp/cmd/simcli/main.go @@ -20,16 +20,15 @@ import ( authclient "github.com/cosmos/cosmos-sdk/x/auth/client" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - "github.com/cosmos/cosmos-sdk/x/auth/types" bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" ) var ( - appCodec, cdc = simapp.MakeCodecs() + encodingConfig = simapp.MakeEncodingConfig() ) func init() { - authclient.Codec = appCodec + authclient.Codec = encodingConfig.Marshaler } func main() { @@ -62,10 +61,10 @@ func main() { rootCmd.AddCommand( rpc.StatusCommand(), client.ConfigCmd(simapp.DefaultCLIHome), - queryCmd(cdc), - txCmd(cdc), + queryCmd(encodingConfig.Amino), + txCmd(), flags.LineBreak, - lcd.ServeCommand(cdc, registerRoutes), + lcd.ServeCommand(encodingConfig.Amino, registerRoutes), flags.LineBreak, keys.Commands(), flags.LineBreak, @@ -112,7 +111,7 @@ func queryCmd(cdc *codec.Codec) *cobra.Command { return queryCmd } -func txCmd(cdc *codec.Codec) *cobra.Command { +func txCmd() *cobra.Command { txCmd := &cobra.Command{ Use: "tx", Short: "Transactions subcommands", @@ -121,24 +120,19 @@ func txCmd(cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } - clientCtx := client.Context{} - clientCtx = clientCtx. - WithJSONMarshaler(appCodec). - WithTxGenerator(types.StdTxGenerator{Cdc: cdc}). - WithAccountRetriever(types.NewAccountRetriever(appCodec)). - WithCodec(cdc) + clientCtx := MakeTxCLIContext() txCmd.AddCommand( bankcmd.NewSendTxCmd(clientCtx), flags.LineBreak, - authcmd.GetSignCommand(cdc), + authcmd.GetSignCommand(clientCtx), authcmd.GetSignBatchCommand(cdc), - authcmd.GetMultiSignCommand(cdc), - authcmd.GetValidateSignaturesCommand(cdc), + authcmd.GetMultiSignCommand(clientCtx), + authcmd.GetValidateSignaturesCommand(clientCtx), flags.LineBreak, - authcmd.GetBroadcastCommand(cdc), - authcmd.GetEncodeCommand(cdc), - authcmd.GetDecodeCommand(cdc), + authcmd.GetBroadcastCommand(clientCtx), + authcmd.GetEncodeCommand(clientCtx), + authcmd.GetDecodeCommand(clientCtx), flags.LineBreak, ) diff --git a/simapp/cmd/simcli/proto.go b/simapp/cmd/simcli/proto.go new file mode 100644 index 000000000000..6754542a28c7 --- /dev/null +++ b/simapp/cmd/simcli/proto.go @@ -0,0 +1,19 @@ +// +build !test_amino + +package main + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func MakeTxCLIContext() client.Context { + cliCtx := client.Context{} + protoCdc := codec.NewProtoCodec(encodingConfig.InterfaceRegistry) + return cliCtx. + WithJSONMarshaler(protoCdc). + WithTxGenerator(encodingConfig.TxGenerator). + WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)). + WithCodec(encodingConfig.Amino) +} diff --git a/simapp/cmd/simd/genaccounts.go b/simapp/cmd/simd/genaccounts.go index 0268b5405420..7e6d395abaac 100644 --- a/simapp/cmd/simd/genaccounts.go +++ b/simapp/cmd/simd/genaccounts.go @@ -7,8 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/std" - "github.com/spf13/cobra" "github.com/spf13/viper" @@ -34,7 +32,7 @@ const ( // AddGenesisAccountCmd returns add-genesis-account cobra Command. func AddGenesisAccountCmd( - ctx *server.Context, depCdc *codec.Codec, cdc *std.Codec, defaultNodeHome, defaultClientHome string, + ctx *server.Context, depCdc *codec.Codec, cdc codec.Marshaler, defaultNodeHome, defaultClientHome string, ) *cobra.Command { cmd := &cobra.Command{ diff --git a/simapp/cmd/simd/main.go b/simapp/cmd/simd/main.go index 7078a453885b..5e0787070988 100644 --- a/simapp/cmd/simd/main.go +++ b/simapp/cmd/simd/main.go @@ -29,7 +29,7 @@ const flagInvCheckPeriod = "inv-check-period" var invCheckPeriod uint func main() { - appCodec, cdc := simapp.MakeCodecs() + appCodec, _, cdc := simapp.MakeCodecs() config := sdk.GetConfig() config.SetBech32PrefixForAccount(sdk.Bech32PrefixAccAddr, sdk.Bech32PrefixAccPub) diff --git a/simapp/encoding.go b/simapp/encoding.go new file mode 100644 index 000000000000..916272813036 --- /dev/null +++ b/simapp/encoding.go @@ -0,0 +1,22 @@ +package simapp + +import ( + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/std" +) + +func MakeCodecs() (codec.Marshaler, codectypes.InterfaceRegistry, *codec.Codec) { + cfg := MakeEncodingConfig() + return cfg.Marshaler, cfg.InterfaceRegistry, cfg.Amino +} + +func MakeEncodingConfig() params.EncodingConfig { + encodingConfig := params.MakeEncodingConfig() + std.RegisterCodec(encodingConfig.Amino) + std.RegisterInterfaces(encodingConfig.InterfaceRegistry) + ModuleBasics.RegisterCodec(encodingConfig.Amino) + ModuleBasics.RegisterInterfaceModules(encodingConfig.InterfaceRegistry) + return encodingConfig +} diff --git a/simapp/export.go b/simapp/export.go index 84e442fafa2b..1c145d804455 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -27,8 +27,8 @@ func (app *SimApp) ExportAppStateAndValidators( app.prepForZeroHeightGenesis(ctx, jailWhiteList) } - genState := app.mm.ExportGenesis(ctx, app.cdc) - appState, err = codec.MarshalJSONIndent(app.cdc, genState) + genState := app.mm.ExportGenesis(ctx, app.amino) + appState, err = codec.MarshalJSONIndent(app.amino, genState) if err != nil { return nil, nil, nil, err } diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index ff807ff29ece..11d558352c07 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -4,11 +4,14 @@ import ( "math/rand" "time" + "github.com/cosmos/cosmos-sdk/client" + + types "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth" ) // SimAppChainID hardcoded chainID for simulation @@ -18,31 +21,62 @@ const ( ) // GenTx generates a signed mock transaction. -func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { - fee := auth.StdFee{ - Amount: feeAmt, - Gas: gas, - } - - sigs := make([]auth.StdSignature, len(priv)) +func GenTx(gen client.TxGenerator, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) sdk.Tx { + sigs := make([]client.SignatureBuilder, len(priv)) // create a random length memo r := rand.New(rand.NewSource(time.Now().UnixNano())) memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) + signMode := gen.SignModeHandler().DefaultMode() + + for i, p := range priv { + sigs[i] = client.SignatureBuilder{ + PubKey: p.PubKey(), + Data: &types.SingleSignatureData{ + SignMode: signMode, + }, + } + } + + tx := gen.NewTxBuilder() + err := tx.SetMsgs(msgs...) + if err != nil { + panic(err) + } + err = tx.SetSignatures(sigs...) + if err != nil { + panic(err) + } + tx.SetMemo(memo) + tx.SetFee(feeAmt) + tx.SetGasLimit(gas) + for i, p := range priv { // use a empty chainID for ease of testing - sig, err := p.Sign(auth.StdSignBytes(chainID, accnums[i], seq[i], fee, msgs, memo)) + signBytes, err := gen.SignModeHandler().GetSignBytes(signMode, types.SigningData{ + PublicKey: nil, + ChainID: chainID, + AccountNumber: accnums[i], + AccountSequence: seq[i], + }, tx.GetTx()) + if err != nil { panic(err) } - - sigs[i] = auth.StdSignature{ - PubKey: p.PubKey().Bytes(), - Signature: sig, + sig, err := p.Sign(signBytes) + if err != nil { + panic(err) } + + sigs[i].Data.(*types.SingleSignatureData).Signature = sig + } + + err = tx.SetSignatures(sigs...) + if err != nil { + panic(err) } - return auth.NewStdTx(msgs, fee, sigs, memo) + return tx.GetTx() } diff --git a/simapp/params/amino.go b/simapp/params/amino.go new file mode 100644 index 000000000000..10c91b1ac769 --- /dev/null +++ b/simapp/params/amino.go @@ -0,0 +1,22 @@ +// +build test_amino + +package params + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func MakeEncodingConfig() EncodingConfig { + cdc := codec.New() + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewHybridCodec(cdc, interfaceRegistry) + + return EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Marshaler: marshaler, + TxGenerator: authtypes.StdTxGenerator{Cdc: cdc}, + Amino: cdc, + } +} diff --git a/simapp/params/encoding.go b/simapp/params/encoding.go new file mode 100644 index 000000000000..040e06ddb247 --- /dev/null +++ b/simapp/params/encoding.go @@ -0,0 +1,14 @@ +package params + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" +) + +type EncodingConfig struct { + InterfaceRegistry types.InterfaceRegistry + Marshaler codec.Marshaler + TxGenerator client.TxGenerator + Amino *codec.Codec +} diff --git a/simapp/params/proto.go b/simapp/params/proto.go new file mode 100644 index 000000000000..d02c9a1e38ee --- /dev/null +++ b/simapp/params/proto.go @@ -0,0 +1,25 @@ +// +build !test_amino + +package params + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/types/tx/signing" +) + +func MakeEncodingConfig() EncodingConfig { + cdc := codec.New() + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewHybridCodec(cdc, interfaceRegistry) + pubKeyCodec := cryptocodec.DefaultPublicKeyCodec{} + txGen := signing.NewTxGenerator(marshaler, pubKeyCodec, signing.DefaultSignModeHandler()) + + return EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Marshaler: marshaler, + TxGenerator: txGen, + Amino: cdc, + } +} diff --git a/simapp/proto.go b/simapp/proto.go new file mode 100644 index 000000000000..6a68416a9193 --- /dev/null +++ b/simapp/proto.go @@ -0,0 +1,23 @@ +// +build !test_amino + +package simapp + +import ( + "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/ibc" +) + +func AminoJSONTxDecoder(enc params.EncodingConfig) types.TxDecoder { + return signing.AminoJSONTxDecoder(enc.Marshaler, enc.TxGenerator) +} + +func NewAnteHandler(ak auth.AccountKeeper, bk bank.Keeper, ibcK ibc.Keeper) types.AnteHandler { + return ante.NewProtoAnteHandler( + ak, bk, ibcK, ante.DefaultSigVerificationGasConsumer, + ) +} diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 7b17fe743044..841efac11e32 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -7,6 +7,8 @@ import ( "strconv" "testing" + "github.com/cosmos/cosmos-sdk/client" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" @@ -239,11 +241,11 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.C // the parameter 'expPass' against the result. A corresponding result is // returned. func SignCheckDeliver( - t *testing.T, cdc *codec.Codec, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg, + t *testing.T, txGen client.TxGenerator, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg, accNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { - tx := helpers.GenTx( + txGen, msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, helpers.DefaultGenTxGas, @@ -253,11 +255,11 @@ func SignCheckDeliver( priv..., ) - txBytes, err := cdc.MarshalBinaryBare(tx) + txBytes, err := txGen.TxEncoder()(tx) require.Nil(t, err) // Must simulate now as CheckTx doesn't run Msgs anymore - _, res, err := app.Simulate(txBytes, tx) + _, res, tx, err := app.Simulate(txBytes) if expSimPass { require.NoError(t, err) @@ -288,18 +290,10 @@ func SignCheckDeliver( // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. -func GenSequenceOfTxs(msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) []auth.StdTx { - txs := make([]auth.StdTx, numToGenerate) +func GenSequenceOfTxs(txGen client.TxGenerator, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) []sdk.Tx { + txs := make([]sdk.Tx, numToGenerate) for i := 0; i < numToGenerate; i++ { - txs[i] = helpers.GenTx( - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.DefaultGenTxGas, - "", - accNums, - initSeqNums, - priv..., - ) + txs[i] = helpers.GenTx(txGen, msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, helpers.DefaultGenTxGas, "", accNums, initSeqNums, priv...) incrementAllSequenceNumbers(initSeqNums) } diff --git a/std/codec.go b/std/codec.go index ce9ded25a9c0..606a9c96130b 100644 --- a/std/codec.go +++ b/std/codec.go @@ -9,22 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/vesting" ) -// Codec defines the application-level codec. This codec contains all the -// required module-specific codecs that are to be provided upon initialization. -type Codec struct { - codec.Marshaler - - // Keep reference to the amino codec to allow backwards compatibility along - // with type, and interface registration. - amino *codec.Codec - - anyUnpacker types.AnyUnpacker -} - -func NewAppCodec(amino *codec.Codec, anyUnpacker types.AnyUnpacker) *Codec { - return &Codec{Marshaler: codec.NewHybridCodec(amino, anyUnpacker), amino: amino, anyUnpacker: anyUnpacker} -} - // ---------------------------------------------------------------------------- // necessary types and interfaces registered. This codec is provided to all the // modules the application depends on. @@ -35,13 +19,17 @@ func MakeCodec(bm module.BasicManager) *codec.Codec { cdc := codec.New() bm.RegisterCodec(cdc) - vesting.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - cryptocodec.RegisterCrypto(cdc) + RegisterCodec(cdc) return cdc } +func RegisterCodec(cdc *codec.Codec) { + sdk.RegisterCodec(cdc) + cryptocodec.RegisterCrypto(cdc) + vesting.RegisterCodec(cdc) +} + // RegisterInterfaces registers Interfaces from sdk/types and vesting func RegisterInterfaces(interfaceRegistry types.InterfaceRegistry) { sdk.RegisterInterfaces(interfaceRegistry) diff --git a/tests/cli/fixtures.go b/tests/cli/fixtures.go index 564514ddc114..bcec1516afbc 100644 --- a/tests/cli/fixtures.go +++ b/tests/cli/fixtures.go @@ -9,31 +9,30 @@ import ( "github.com/stretchr/testify/require" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/std" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/simapp" -) - -var ( - cdc = std.MakeCodec(simapp.ModuleBasics) + "github.com/cosmos/cosmos-sdk/simapp/params" ) // Fixtures is used to setup the testing environment type Fixtures struct { - BuildDir string - RootDir string - SimdBinary string - SimcliBinary string - ChainID string - RPCAddr string - Port string - SimdHome string - SimcliHome string - P2PAddr string - Cdc *codec.Codec - T *testing.T + BuildDir string + RootDir string + SimdBinary string + SimcliBinary string + ChainID string + RPCAddr string + Port string + SimdHome string + SimcliHome string + P2PAddr string + JSONMarshaler codec.JSONMarshaler + Amino *codec.Codec + InterfaceRegistry types.InterfaceRegistry + EncodingConfig params.EncodingConfig + T *testing.T } // NewFixtures creates a new instance of Fixtures with many vars set @@ -52,18 +51,23 @@ func NewFixtures(t *testing.T) *Fixtures { t.Skip("builddir is empty, skipping") } + encodingConfig := simapp.MakeEncodingConfig() + return &Fixtures{ - T: t, - BuildDir: buildDir, - RootDir: tmpDir, - SimdBinary: filepath.Join(buildDir, "simd"), - SimcliBinary: filepath.Join(buildDir, "simcli"), - SimdHome: filepath.Join(tmpDir, ".simd"), - SimcliHome: filepath.Join(tmpDir, ".simcli"), - RPCAddr: servAddr, - P2PAddr: p2pAddr, - Cdc: cdc, - Port: port, + T: t, + BuildDir: buildDir, + RootDir: tmpDir, + SimdBinary: filepath.Join(buildDir, "simd"), + SimcliBinary: filepath.Join(buildDir, "simcli"), + SimdHome: filepath.Join(tmpDir, ".simd"), + SimcliHome: filepath.Join(tmpDir, ".simcli"), + RPCAddr: servAddr, + P2PAddr: p2pAddr, + JSONMarshaler: encodingConfig.Marshaler, + InterfaceRegistry: encodingConfig.InterfaceRegistry, + Amino: encodingConfig.Amino, + EncodingConfig: encodingConfig, + Port: port, } } @@ -78,6 +82,6 @@ func (f Fixtures) GenesisState() simapp.GenesisState { require.NoError(f.T, err) var appState simapp.GenesisState - require.NoError(f.T, f.Cdc.UnmarshalJSON(genDoc.AppState, &appState)) + require.NoError(f.T, f.JSONMarshaler.UnmarshalJSON(genDoc.AppState, &appState)) return appState } diff --git a/tests/cli/helpers.go b/tests/cli/helpers.go index 35c5d31b4bc6..87bd2537f395 100644 --- a/tests/cli/helpers.go +++ b/tests/cli/helpers.go @@ -10,11 +10,10 @@ import ( "github.com/stretchr/testify/require" clientkeys "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" ) var ( @@ -168,7 +167,7 @@ func (f *Fixtures) QueryTxs(page, limit int, events ...string) *sdk.SearchTxsRes out, _ := tests.ExecuteT(f.T, cmd, "") var result sdk.SearchTxsResult - err := f.Cdc.UnmarshalJSON([]byte(out), &result) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &result) require.NoError(f.T, err, "out %v\n, err %v", out, err) return &result } @@ -191,18 +190,29 @@ func AddFlags(cmd string, flags []string) string { return strings.TrimSpace(cmd) } -func UnmarshalStdTx(t require.TestingT, c *codec.Codec, s string) (stdTx auth.StdTx) { - require.Nil(t, c.UnmarshalJSON([]byte(s), &stdTx)) - return +type CLITx interface { + txtypes.SigTx + txtypes.FeeTx + txtypes.TxWithMemo + + SetMemo(string) +} + +func (f Fixtures) UnmarshalTxJSON(s string) CLITx { + tx, err := f.EncodingConfig.TxGenerator.TxJSONDecoder()([]byte(s)) + require.Nil(f.T, err) + sigTx, ok := tx.(CLITx) + require.True(f.T, ok, "couldn't decode tx") + return sigTx } func buildEventsQueryString(events []string) string { return strings.Join(events, "&") } -func MarshalStdTx(t require.TestingT, c *codec.Codec, stdTx auth.StdTx) []byte { - bz, err := c.MarshalBinaryBare(stdTx) - require.NoError(t, err) +func (f Fixtures) MarshalTx(tx sdk.Tx) []byte { + bz, err := f.EncodingConfig.TxGenerator.TxEncoder()(tx) + require.NoError(f.T, err) return bz } diff --git a/tests/cli/simd_test.go b/tests/cli/simd_test.go index 2be36dc8e93a..8b5aeab74082 100644 --- a/tests/cli/simd_test.go +++ b/tests/cli/simd_test.go @@ -11,8 +11,6 @@ import ( "github.com/stretchr/testify/require" tmtypes "github.com/tendermint/tendermint/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/tests/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" @@ -99,11 +97,8 @@ func TestCLISimdAddGenesisAccount(t *testing.T) { genesisState := f.GenesisState() - interfaceRegistry := codectypes.NewInterfaceRegistry() - appCodec := std.NewAppCodec(f.Cdc, interfaceRegistry) - - accounts := auth.GetGenesisStateFromAppState(appCodec, genesisState).Accounts - balances := bank.GetGenesisStateFromAppState(f.Cdc, genesisState).Balances + accounts := auth.GetGenesisStateFromAppState(f.JSONMarshaler, genesisState).Accounts + balances := bank.GetGenesisStateFromAppState(f.JSONMarshaler, genesisState).Balances balancesSet := make(map[string]sdk.Coins) for _, b := range balances { diff --git a/types/decimal_test.go b/types/decimal_test.go index c58777783764..39a24703e261 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -9,8 +9,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" yaml "gopkg.in/yaml.v2" - - "github.com/cosmos/cosmos-sdk/codec" ) // create a decimal from a decimal string (ex. "1234.5678") @@ -270,8 +268,6 @@ func TestTruncate(t *testing.T) { } } -var cdc = codec.New() - func TestDecMarshalJSON(t *testing.T) { decimal := func(i int64) Dec { d := NewDec(0) diff --git a/types/events.go b/types/events.go index 10723931e9cd..30fe1ee39de2 100644 --- a/types/events.go +++ b/types/events.go @@ -48,13 +48,6 @@ type ( // Event is a type alias for an ABCI Event Event abci.Event - // Attribute defines an attribute wrapper where the key and value are - // strings instead of raw bytes. - Attribute struct { - Key string `json:"key"` - Value string `json:"value,omitempty"` - } - // Events defines a slice of Event objects Events []Event ) @@ -141,13 +134,6 @@ var ( ) type ( - // StringAttribute defines en Event object wrapper where all the attributes - // contain key/value pairs that are strings instead of raw bytes. - StringEvent struct { - Type string `json:"type,omitempty"` - Attributes []Attribute `json:"attributes,omitempty"` - } - // StringAttributes defines a slice of StringEvents objects. StringEvents []StringEvent ) diff --git a/types/rest/rest.go b/types/rest/rest.go index bee3bbbeaa55..ff633ce354eb 100644 --- a/types/rest/rest.go +++ b/types/rest/rest.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "io/ioutil" "net/http" "net/url" diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index e428d8e49a61..aff5f00d64ac 100644 --- a/types/rest/rest_test.go +++ b/types/rest/rest_test.go @@ -2,6 +2,7 @@ package rest_test import ( "errors" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "io" "io/ioutil" "net/http" diff --git a/types/result.go b/types/result.go index 156cd340c0f8..d973f3c66a77 100644 --- a/types/result.go +++ b/types/result.go @@ -4,17 +4,22 @@ import ( "encoding/hex" "encoding/json" "fmt" + "github.com/cosmos/cosmos-sdk/codec" "math" "strings" yaml "gopkg.in/yaml.v2" + "github.com/cosmos/cosmos-sdk/codec/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" ) +var cdc = codec.New() + func (gi GasInfo) String() string { bz, _ := yaml.Marshal(gi) return string(bz) @@ -37,19 +42,9 @@ func (r Result) GetEvents() Events { // ABCIMessageLogs represents a slice of ABCIMessageLog. type ABCIMessageLogs []ABCIMessageLog -// ABCIMessageLog defines a structure containing an indexed tx ABCI message log. -type ABCIMessageLog struct { - MsgIndex uint16 `json:"msg_index"` - Log string `json:"log"` - - // Events contains a slice of Event objects that were emitted during some - // execution. - Events StringEvents `json:"events"` -} - func NewABCIMessageLog(i uint16, log string, events Events) ABCIMessageLog { return ABCIMessageLog{ - MsgIndex: i, + MsgIndex: uint32(i), Log: log, Events: StringifyEvents(events.ToABCIEvents()), } @@ -58,7 +53,7 @@ func NewABCIMessageLog(i uint16, log string, events Events) ABCIMessageLog { // String implements the fmt.Stringer interface for the ABCIMessageLogs type. func (logs ABCIMessageLogs) String() (str string) { if logs != nil { - raw, err := legacy.Cdc.MarshalJSON(logs) + raw, err := cdc.MarshalJSON(logs) if err == nil { str = string(raw) } @@ -67,32 +62,15 @@ func (logs ABCIMessageLogs) String() (str string) { return str } -// TxResponse defines a structure containing relevant tx data and metadata. The -// tags are stringified and the log is JSON decoded. -type TxResponse struct { - Height int64 `json:"height"` - TxHash string `json:"txhash"` - Codespace string `json:"codespace,omitempty"` - Code uint32 `json:"code,omitempty"` - Data string `json:"data,omitempty"` - RawLog string `json:"raw_log,omitempty"` - Logs ABCIMessageLogs `json:"logs,omitempty"` - Info string `json:"info,omitempty"` - GasWanted int64 `json:"gas_wanted,omitempty"` - GasUsed int64 `json:"gas_used,omitempty"` - Tx Tx `json:"tx,omitempty"` - Timestamp string `json:"timestamp,omitempty"` -} - // NewResponseResultTx returns a TxResponse given a ResultTx from tendermint -func NewResponseResultTx(res *ctypes.ResultTx, tx Tx, timestamp string) TxResponse { +func NewResponseResultTx(res *ctypes.ResultTx, tx Tx, timestamp string) *TxResponse { if res == nil { - return TxResponse{} + return &TxResponse{} } parsedLogs, _ := ParseABCILogs(res.TxResult.Log) - return TxResponse{ + return &TxResponse{ TxHash: res.Hash.String(), Height: res.Height, Codespace: res.TxResult.Codespace, @@ -103,16 +81,16 @@ func NewResponseResultTx(res *ctypes.ResultTx, tx Tx, timestamp string) TxRespon Info: res.TxResult.Info, GasWanted: res.TxResult.GasWanted, GasUsed: res.TxResult.GasUsed, - Tx: tx, + Tx: types.UnsafePackAny(tx), Timestamp: timestamp, } } // NewResponseFormatBroadcastTxCommit returns a TxResponse given a // ResultBroadcastTxCommit from tendermint. -func NewResponseFormatBroadcastTxCommit(res *ctypes.ResultBroadcastTxCommit) TxResponse { +func NewResponseFormatBroadcastTxCommit(res *ctypes.ResultBroadcastTxCommit) *TxResponse { if res == nil { - return TxResponse{} + return &TxResponse{} } if !res.CheckTx.IsOK() { @@ -122,9 +100,9 @@ func NewResponseFormatBroadcastTxCommit(res *ctypes.ResultBroadcastTxCommit) TxR return newTxResponseDeliverTx(res) } -func newTxResponseCheckTx(res *ctypes.ResultBroadcastTxCommit) TxResponse { +func newTxResponseCheckTx(res *ctypes.ResultBroadcastTxCommit) *TxResponse { if res == nil { - return TxResponse{} + return nil } var txHash string @@ -134,7 +112,7 @@ func newTxResponseCheckTx(res *ctypes.ResultBroadcastTxCommit) TxResponse { parsedLogs, _ := ParseABCILogs(res.CheckTx.Log) - return TxResponse{ + return &TxResponse{ Height: res.Height, TxHash: txHash, Codespace: res.CheckTx.Codespace, @@ -148,9 +126,9 @@ func newTxResponseCheckTx(res *ctypes.ResultBroadcastTxCommit) TxResponse { } } -func newTxResponseDeliverTx(res *ctypes.ResultBroadcastTxCommit) TxResponse { +func newTxResponseDeliverTx(res *ctypes.ResultBroadcastTxCommit) *TxResponse { if res == nil { - return TxResponse{} + return nil } var txHash string @@ -160,7 +138,7 @@ func newTxResponseDeliverTx(res *ctypes.ResultBroadcastTxCommit) TxResponse { parsedLogs, _ := ParseABCILogs(res.DeliverTx.Log) - return TxResponse{ + return &TxResponse{ Height: res.Height, TxHash: txHash, Codespace: res.DeliverTx.Codespace, @@ -175,14 +153,14 @@ func newTxResponseDeliverTx(res *ctypes.ResultBroadcastTxCommit) TxResponse { } // NewResponseFormatBroadcastTx returns a TxResponse given a ResultBroadcastTx from tendermint -func NewResponseFormatBroadcastTx(res *ctypes.ResultBroadcastTx) TxResponse { +func NewResponseFormatBroadcastTx(res *ctypes.ResultBroadcastTx) *TxResponse { if res == nil { - return TxResponse{} + return &TxResponse{} } parsedLogs, _ := ParseABCILogs(res.Log) - return TxResponse{ + return &TxResponse{ Code: res.Code, Codespace: res.Codespace, Data: res.Data.String(), @@ -240,15 +218,15 @@ func (r TxResponse) Empty() bool { // SearchTxsResult defines a structure for querying txs pageable type SearchTxsResult struct { - TotalCount int `json:"total_count"` // Count of all txs - Count int `json:"count"` // Count of txs in current page - PageNumber int `json:"page_number"` // Index of current page, start from 1 - PageTotal int `json:"page_total"` // Count of total pages - Limit int `json:"limit"` // Max count txs per page - Txs []TxResponse `json:"txs"` // List of txs in current page + TotalCount int `json:"total_count"` // Count of all txs + Count int `json:"count"` // Count of txs in current page + PageNumber int `json:"page_number"` // Index of current page, start from 1 + PageTotal int `json:"page_total"` // Count of total pages + Limit int `json:"limit"` // Max count txs per page + Txs []*TxResponse `json:"txs"` // List of txs in current page } -func NewSearchTxsResult(totalCount, count, page, limit int, txs []TxResponse) SearchTxsResult { +func NewSearchTxsResult(totalCount, count, page, limit int, txs []*TxResponse) SearchTxsResult { return SearchTxsResult{ TotalCount: totalCount, Count: count, @@ -284,5 +262,13 @@ func (s SearchTxsResult) UnpackInterfaces(unpacker types.AnyUnpacker) error { // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (r TxResponse) UnpackInterfaces(unpacker types.AnyUnpacker) error { - return types.UnpackInterfaces(r.Tx, unpacker) + var tx Tx + return unpacker.UnpackAny(r.Tx, &tx) +} + +func (r TxResponse) GetTx() Tx { + if tx, ok := r.Tx.GetCachedValue().(Tx); ok { + return tx + } + return nil } diff --git a/types/result_test.go b/types/result_test.go index 98e8ddca10a4..c5be8d15a5ba 100644 --- a/types/result_test.go +++ b/types/result_test.go @@ -5,12 +5,15 @@ import ( "strings" "testing" + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/bytes" ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -22,30 +25,31 @@ func TestParseABCILog(t *testing.T) { require.NoError(t, err) require.Len(t, res, 1) require.Equal(t, res[0].Log, "") - require.Equal(t, res[0].MsgIndex, uint16(1)) + require.Equal(t, res[0].MsgIndex, uint32(1)) } func TestABCIMessageLog(t *testing.T) { t.Parallel() + cdc := codec.New() events := sdk.Events{sdk.NewEvent("transfer", sdk.NewAttribute("sender", "foo"))} msgLog := sdk.NewABCIMessageLog(0, "", events) msgLogs := sdk.ABCIMessageLogs{msgLog} - bz, err := legacy.Cdc.MarshalJSON(msgLogs) + bz, err := cdc.MarshalJSON(msgLogs) require.NoError(t, err) require.Equal(t, string(bz), msgLogs.String()) } func TestNewSearchTxsResult(t *testing.T) { t.Parallel() - got := sdk.NewSearchTxsResult(150, 20, 2, 20, []sdk.TxResponse{}) + got := sdk.NewSearchTxsResult(150, 20, 2, 20, []*sdk.TxResponse{}) require.Equal(t, sdk.SearchTxsResult{ TotalCount: 150, Count: 20, PageNumber: 2, PageTotal: 8, Limit: 20, - Txs: []sdk.TxResponse{}, + Txs: []*sdk.TxResponse{}, }, got) } @@ -80,7 +84,7 @@ func TestResponseResultTx(t *testing.T) { } logs, err := sdk.ParseABCILogs(`[]`) require.NoError(t, err) - want := sdk.TxResponse{ + want := &sdk.TxResponse{ TxHash: "74657374", Height: 10, Codespace: "codespace", @@ -91,12 +95,12 @@ func TestResponseResultTx(t *testing.T) { Info: "info", GasWanted: 100, GasUsed: 90, - Tx: sdk.Tx(nil), + Tx: &types.Any{}, Timestamp: "timestamp", } require.Equal(t, want, sdk.NewResponseResultTx(resultTx, sdk.Tx(nil), "timestamp")) - require.Equal(t, sdk.TxResponse{}, sdk.NewResponseResultTx(nil, sdk.Tx(nil), "timestamp")) + require.Equal(t, &sdk.TxResponse{}, sdk.NewResponseResultTx(nil, sdk.Tx(nil), "timestamp")) require.Equal(t, `Response: Height: 10 TxHash: 74657374 @@ -119,7 +123,7 @@ func TestResponseResultTx(t *testing.T) { Log: `[]`, Hash: bytes.HexBytes([]byte("test")), } - require.Equal(t, sdk.TxResponse{ + require.Equal(t, &sdk.TxResponse{ Code: 1, Codespace: "codespace", Data: "64617461", @@ -127,12 +131,12 @@ func TestResponseResultTx(t *testing.T) { Logs: logs, TxHash: "74657374", }, sdk.NewResponseFormatBroadcastTx(resultBroadcastTx)) - require.Equal(t, sdk.TxResponse{}, sdk.NewResponseFormatBroadcastTx(nil)) + require.Equal(t, &sdk.TxResponse{}, sdk.NewResponseFormatBroadcastTx(nil)) } func TestResponseFormatBroadcastTxCommit(t *testing.T) { // test nil - require.Equal(t, sdk.TxResponse{}, sdk.NewResponseFormatBroadcastTxCommit(nil)) + require.Equal(t, &sdk.TxResponse{}, sdk.NewResponseFormatBroadcastTxCommit(nil)) logs, err := sdk.ParseABCILogs(`[]`) require.NoError(t, err) @@ -165,7 +169,7 @@ func TestResponseFormatBroadcastTxCommit(t *testing.T) { }, } - want := sdk.TxResponse{ + want := &sdk.TxResponse{ Height: 10, TxHash: "74657374", Codespace: "codespace", diff --git a/types/tx/fee.go b/types/tx/fee.go new file mode 100644 index 000000000000..6c165c7e8846 --- /dev/null +++ b/types/tx/fee.go @@ -0,0 +1,18 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// MaxGasWanted defines the max gas allowed. +const MaxGasWanted = uint64((1 << 63) - 1) + +func (m *Fee) GetGas() uint64 { + return m.GasLimit +} + +func (m *Fee) SetGas(u uint64) { + m.GasLimit = u +} + +func (m *Fee) SetAmount(coins sdk.Coins) { + m.Amount = coins +} diff --git a/types/tx/mode_handler.go b/types/tx/mode_handler.go new file mode 100644 index 000000000000..bfe9223b638e --- /dev/null +++ b/types/tx/mode_handler.go @@ -0,0 +1,21 @@ +package types + +import ( + "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type SigningData struct { + Mode SignMode + PublicKey crypto.PubKey + ChainID string + AccountNumber uint64 + AccountSequence uint64 +} + +type SignModeHandler interface { + DefaultMode() SignMode + Modes() []SignMode + GetSignBytes(mode SignMode, data SigningData, tx sdk.Tx) ([]byte, error) +} diff --git a/types/tx/signature.go b/types/tx/signature.go new file mode 100644 index 000000000000..7b45c6c72265 --- /dev/null +++ b/types/tx/signature.go @@ -0,0 +1,58 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/crypto/types" +) + +type SignatureData interface { + isSignatureData() +} + +type SingleSignatureData struct { + SignMode SignMode + Signature []byte +} + +type MultiSignatureData struct { + BitArray *types.CompactBitArray + Signatures []SignatureData +} + +var _, _ SignatureData = &SingleSignatureData{}, &MultiSignatureData{} + +func (m *SingleSignatureData) isSignatureData() {} +func (m *MultiSignatureData) isSignatureData() {} + +func ModeInfoToSignatureData(modeInfo *ModeInfo, sig []byte) (SignatureData, error) { + switch modeInfo := modeInfo.Sum.(type) { + case *ModeInfo_Single_: + return &SingleSignatureData{ + SignMode: modeInfo.Single.Mode, + Signature: sig, + }, nil + + case *ModeInfo_Multi_: + multi := modeInfo.Multi + + sigs, err := types.DecodeMultisignatures(sig) + if err != nil { + return nil, err + } + + sigv2s := make([]SignatureData, len(sigs)) + for i, mi := range multi.ModeInfos { + sigv2s[i], err = ModeInfoToSignatureData(mi, sigs[i]) + if err != nil { + return nil, err + } + } + + return &MultiSignatureData{ + BitArray: multi.Bitarray, + Signatures: sigv2s, + }, nil + + default: + panic("unexpected case") + } +} diff --git a/types/tx/signing/amino.go b/types/tx/signing/amino.go new file mode 100644 index 000000000000..92d017867464 --- /dev/null +++ b/types/tx/signing/amino.go @@ -0,0 +1,92 @@ +package signing + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" + multisig2 "github.com/cosmos/cosmos-sdk/crypto/multisig" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" + auth "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func AminoJSONTxDecoder(aminoJsonMarshaler codec.JSONMarshaler, txGen client.TxGenerator) sdk.TxDecoder { + return func(txBytes []byte) (sdk.Tx, error) { + var aminoTx auth.StdTx + err := aminoJsonMarshaler.UnmarshalJSON(txBytes, &aminoTx) + if err != nil { + return nil, err + } + + txBuilder := txGen.NewTxBuilder() + + // set msgs + err = txBuilder.SetMsgs(aminoTx.Msgs...) + if err != nil { + return nil, err + } + + txBuilder.SetMemo(aminoTx.Memo) + txBuilder.SetFee(aminoTx.Fee.Amount) + txBuilder.SetGasLimit(aminoTx.Fee.Gas) + + n := len(aminoTx.Signatures) + clientSigs := make([]client.SignatureBuilder, n) + sigs := aminoTx.Signatures + + for i := 0; i < n; i++ { + data, err := stdSignatureToSignatureData(sigs[i]) + if err != nil { + return nil, err + } + clientSigs[i] = client.SignatureBuilder{ + PubKey: sigs[i].GetPubKey(), + Data: data, + } + } + + err = txBuilder.SetSignatures(clientSigs...) + if err != nil { + return nil, err + } + + return txBuilder.GetTx(), nil + } +} + +func stdSignatureToSignatureData(signature auth.StdSignature) (types.SignatureData, error) { + pk := signature.GetPubKey() + if multisigPk, ok := pk.(multisig2.MultisigPubKey); ok { + pubKeys := multisigPk.GetPubKeys() + var sig multisig2.AminoMultisignature + err := legacy_global.Cdc.UnmarshalBinaryBare(signature.Signature, &sig) + if err != nil { + return nil, err + } + n := sig.BitArray.Size() + datas := make([]types.SignatureData, n) + sigIndex := 0 + for i := 0; i < n; i++ { + if sig.BitArray.GetIndex(i) { + datas[sigIndex], err = stdSignatureToSignatureData(auth.StdSignature{ + PubKey: pubKeys[i].Bytes(), + Signature: sig.Sigs[sigIndex], + }) + if err != nil { + return nil, err + } + sigIndex++ + } + } + return &types.MultiSignatureData{ + BitArray: sig.BitArray, + Signatures: datas[:sigIndex], + }, nil + } else { + return &types.SingleSignatureData{ + SignMode: types.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, + Signature: signature.Signature, + }, nil + } +} diff --git a/types/tx/signing/decoded_tx.go b/types/tx/signing/decoded_tx.go new file mode 100644 index 000000000000..a12c39615ba9 --- /dev/null +++ b/types/tx/signing/decoded_tx.go @@ -0,0 +1,64 @@ +package signing + +import ( + "github.com/tendermint/tendermint/crypto" + + "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +type DecodedTx struct { + *types.Tx + Raw *TxRaw + PubKeys []crypto.PubKey +} + +var _ types.ProtoTx = DecodedTx{} + +func DefaultTxDecoder(cdc codec.Marshaler, keyCodec cryptotypes.PublicKeyCodec) sdk.TxDecoder { + keyCodec = cryptotypes.CacheWrapCodec(keyCodec) + + return func(txBytes []byte) (sdk.Tx, error) { + var raw TxRaw + err := cdc.UnmarshalBinaryBare(txBytes, &raw) + if err != nil { + return nil, err + } + + var tx types.Tx + err = cdc.UnmarshalBinaryBare(txBytes, &tx) + if err != nil { + return nil, err + } + + 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 DecodedTx{ + Tx: &tx, + Raw: &raw, + PubKeys: pks, + }, nil + } +} + +func (m DecodedTx) GetBodyBytes() []byte { + return m.Raw.BodyBytes +} + +func (m DecodedTx) GetAuthInfoBytes() []byte { + return m.Raw.AuthInfoBytes +} + +func (m DecodedTx) GetPubKeys() []crypto.PubKey { + return m.PubKeys +} diff --git a/types/tx/signing/default.go b/types/tx/signing/default.go new file mode 100644 index 000000000000..a898cbd83d15 --- /dev/null +++ b/types/tx/signing/default.go @@ -0,0 +1,13 @@ +package signing + +import ( + types "github.com/cosmos/cosmos-sdk/types/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func DefaultSignModeHandler() types.SignModeHandler { + return NewHandlerMap(types.SignMode_SIGN_MODE_DIRECT, []types.SignModeHandler{ + DirectModeHandler{}, + authtypes.LegacyAminoJSONHandler{}, + }) +} diff --git a/types/tx/signing/direct.go b/types/tx/signing/direct.go new file mode 100644 index 000000000000..9db445cc4208 --- /dev/null +++ b/types/tx/signing/direct.go @@ -0,0 +1,41 @@ +package signing + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +type DirectModeHandler struct{} + +func (h DirectModeHandler) DefaultMode() types.SignMode { + return types.SignMode_SIGN_MODE_DIRECT +} + +var _ types.SignModeHandler = DirectModeHandler{} + +func (DirectModeHandler) Modes() []types.SignMode { + return []types.SignMode{types.SignMode_SIGN_MODE_DIRECT} +} + +func (DirectModeHandler) GetSignBytes(mode types.SignMode, data types.SigningData, tx sdk.Tx) ([]byte, error) { + protoTx, ok := tx.(types.ProtoTx) + if !ok { + return nil, fmt.Errorf("can only get direct sign bytes for a ProtoTx, got %T", tx) + } + bodyBz := protoTx.GetBodyBytes() + authInfoBz := protoTx.GetAuthInfoBytes() + return DirectSignBytes(bodyBz, authInfoBz, data.ChainID, data.AccountNumber, data.AccountSequence) +} + +func DirectSignBytes(bodyBz, authInfoBz []byte, chainID string, accnum, sequence uint64) ([]byte, error) { + signDoc := SignDocRaw{ + BodyBytes: bodyBz, + AuthInfoBytes: authInfoBz, + ChainId: chainID, + AccountNumber: accnum, + AccountSequence: sequence, + } + return signDoc.Marshal() +} diff --git a/types/tx/signing/handler_map.go b/types/tx/signing/handler_map.go new file mode 100644 index 000000000000..043486271a4c --- /dev/null +++ b/types/tx/signing/handler_map.go @@ -0,0 +1,53 @@ +package signing + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +type HandlerMap struct { + defaultMode types.SignMode + modes []types.SignMode + signModeHandlers map[types.SignMode]types.SignModeHandler +} + +var _ types.SignModeHandler = HandlerMap{} + +func NewHandlerMap(defaultMode types.SignMode, handlers []types.SignModeHandler) *HandlerMap { + handlerMap := make(map[types.SignMode]types.SignModeHandler) + var modes []types.SignMode + + for _, h := range handlers { + for _, m := range h.Modes() { + if _, have := handlerMap[m]; have { + panic(fmt.Errorf("duplicate sign mode handler for mode %s", m)) + } + handlerMap[m] = h + modes = append(modes, m) + } + } + + return &HandlerMap{ + defaultMode: defaultMode, + modes: modes, + signModeHandlers: handlerMap, + } +} + +func (h HandlerMap) DefaultMode() types.SignMode { + return h.defaultMode +} + +func (h HandlerMap) Modes() []types.SignMode { + return h.modes +} + +func (h HandlerMap) GetSignBytes(mode types.SignMode, data types.SigningData, tx sdk.Tx) ([]byte, error) { + handler, found := h.signModeHandlers[mode] + if !found { + return nil, fmt.Errorf("can't verify sign mode %s", data.Mode.String()) + } + return handler.GetSignBytes(mode, data, tx) +} diff --git a/types/tx/signing/json.go b/types/tx/signing/json.go new file mode 100644 index 000000000000..a6df0f311f7a --- /dev/null +++ b/types/tx/signing/json.go @@ -0,0 +1,33 @@ +package signing + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +func DefaultJSONTxDecoder(cdc codec.Marshaler, keyCodec cryptotypes.PublicKeyCodec) sdk.TxDecoder { + keyCodec = cryptotypes.CacheWrapCodec(keyCodec) + + return func(txBytes []byte) (sdk.Tx, error) { + var tx types.Tx + err := cdc.UnmarshalJSON(txBytes, &tx) + if err != nil { + return nil, err + } + + // this decodes pubkeys and makes sure they are cached + if tx.AuthInfo != nil { + signerInfos := tx.AuthInfo.SignerInfos + for _, si := range signerInfos { + _, err := keyCodec.Decode(si.PublicKey) + if err != nil { + return nil, err + } + } + } + + return &tx, nil + } +} diff --git a/types/tx/signing/tx_builder.go b/types/tx/signing/tx_builder.go new file mode 100644 index 000000000000..3a431533e955 --- /dev/null +++ b/types/tx/signing/tx_builder.go @@ -0,0 +1,131 @@ +package signing + +import ( + "fmt" + + "github.com/gogo/protobuf/proto" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +type TxBuilder struct { + *types.Tx + Marshaler codec.Marshaler + PubKeyCodec cryptotypes.PublicKeyCodec +} + +var _ client.TxBuilder = TxBuilder{} + +func (t TxBuilder) GetTx() types.SigTx { + return t.Tx +} + +func (t TxBuilder) SetMsgs(msgs ...sdk.Msg) error { + anys := make([]*codectypes.Any, len(msgs)) + for i, msg := range msgs { + pmsg, ok := msg.(proto.Message) + if !ok { + return fmt.Errorf("cannot proto marshal %T", msg) + } + any, err := codectypes.NewAnyWithValue(pmsg) + if err != nil { + return err + } + anys[i] = any + } + t.Body.Messages = anys + return nil +} + +func SignatureDataToSignerInfoSig(data types.SignatureData) (*types.ModeInfo, []byte) { + if data == nil { + return nil, nil + } + + switch data := data.(type) { + case *types.SingleSignatureData: + return &types.ModeInfo{ + Sum: &types.ModeInfo_Single_{ + Single: &types.ModeInfo_Single{Mode: data.SignMode}, + }, + }, data.Signature + case *types.MultiSignatureData: + n := len(data.Signatures) + modeInfos := make([]*types.ModeInfo, n) + sigs := make([][]byte, n) + + for i, d := range data.Signatures { + modeInfos[i], sigs[i] = SignatureDataToSignerInfoSig(d) + } + + multisig := cryptotypes.MultiSignature{ + Signatures: sigs, + } + sig, err := multisig.Marshal() + if err != nil { + panic(err) + } + + return &types.ModeInfo{ + Sum: &types.ModeInfo_Multi_{ + Multi: &types.ModeInfo_Multi{ + Bitarray: data.BitArray, + ModeInfos: modeInfos, + }, + }, + }, sig + default: + panic("unexpected case") + } +} + +func (t TxBuilder) SetSignatures(signatures ...client.SignatureBuilder) error { + n := len(signatures) + signerInfos := make([]*types.SignerInfo, n) + rawSigs := make([][]byte, n) + for i, sig := range signatures { + var modeInfo *types.ModeInfo + modeInfo, rawSigs[i] = SignatureDataToSignerInfoSig(sig.Data) + pk, err := t.PubKeyCodec.Encode(sig.PubKey) + if err != nil { + return err + } + signerInfos[i] = &types.SignerInfo{ + PublicKey: pk, + ModeInfo: modeInfo, + } + } + t.Tx.AuthInfo.SignerInfos = signerInfos + t.Tx.Signatures = rawSigs + return nil +} + +func (t TxBuilder) SetFee(amount sdk.Coins) { + t.Tx.AuthInfo.Fee.Amount = amount +} + +func (t TxBuilder) SetGasLimit(limit uint64) { + t.Tx.AuthInfo.Fee.GasLimit = limit +} + +func (t TxBuilder) SetMemo(s string) { + t.Tx.Body.Memo = s +} + +func (t TxBuilder) CanonicalSignBytes(cid string, num, seq uint64) ([]byte, error) { + bodyBz, err := t.Marshaler.MarshalBinaryBare(t.Body) + if err != nil { + return nil, err + } + aiBz, err := t.Marshaler.MarshalBinaryBare(t.AuthInfo) + if err != nil { + + return nil, err + } + return DirectSignBytes(bodyBz, aiBz, cid, num, seq) +} diff --git a/types/tx/signing/tx_generator.go b/types/tx/signing/tx_generator.go new file mode 100644 index 000000000000..ae467ba18472 --- /dev/null +++ b/types/tx/signing/tx_generator.go @@ -0,0 +1,73 @@ +package signing + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client" + + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +type TxGenerator struct { + Marshaler codec.Marshaler + PubKeyCodec cryptotypes.PublicKeyCodec + ModeHandler types.SignModeHandler +} + +func NewTxGenerator(marshaler codec.Marshaler, pubKeyCodec cryptotypes.PublicKeyCodec, handler types.SignModeHandler) *TxGenerator { + return &TxGenerator{Marshaler: marshaler, PubKeyCodec: cryptotypes.CacheWrapCodec(pubKeyCodec), ModeHandler: handler} +} + +var _ client.TxGenerator = TxGenerator{} + +func (t TxGenerator) NewTxBuilder() client.TxBuilder { + return TxBuilder{ + Tx: types.NewTx(), + Marshaler: t.Marshaler, + PubKeyCodec: t.PubKeyCodec, + } +} + +func (t TxGenerator) WrapTxBuilder(tx sdk.Tx) (client.TxBuilder, error) { + stdTx, ok := tx.(*types.Tx) + if !ok { + return nil, fmt.Errorf("expected %T, got %T", &types.Tx{}, tx) + } + return TxBuilder{ + Tx: stdTx, + Marshaler: t.Marshaler, + PubKeyCodec: t.PubKeyCodec, + }, nil +} + +func (t TxGenerator) TxEncoder() sdk.TxEncoder { + return func(tx sdk.Tx) ([]byte, error) { + ptx, ok := tx.(*types.Tx) + if !ok { + return nil, fmt.Errorf("expected protobuf Tx, got %T", tx) + } + return t.Marshaler.MarshalBinaryBare(ptx) + } +} + +func (t TxGenerator) TxDecoder() sdk.TxDecoder { + return DefaultTxDecoder(t.Marshaler, t.PubKeyCodec) +} + +func (t TxGenerator) TxJSONEncoder() sdk.TxEncoder { + return func(tx sdk.Tx) ([]byte, error) { + return t.Marshaler.MarshalJSON(tx) + } +} + +func (t TxGenerator) TxJSONDecoder() sdk.TxDecoder { + return DefaultJSONTxDecoder(t.Marshaler, t.PubKeyCodec) +} + +func (t TxGenerator) SignModeHandler() types.SignModeHandler { + return t.ModeHandler +} diff --git a/types/tx/signing/types.pb.go b/types/tx/signing/types.pb.go new file mode 100644 index 000000000000..257b474c95c1 --- /dev/null +++ b/types/tx/signing/types.pb.go @@ -0,0 +1,787 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: types/tx/signing/types.proto + +package signing + +import ( + fmt "fmt" + 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 + +// TxRaw is using for transaction decoding and verification +type TxRaw struct { + BodyBytes []byte `protobuf:"bytes,1,opt,name=body_bytes,json=bodyBytes,proto3" json:"body_bytes,omitempty"` + AuthInfoBytes []byte `protobuf:"bytes,2,opt,name=auth_info_bytes,json=authInfoBytes,proto3" json:"auth_info_bytes,omitempty"` + Signatures [][]byte `protobuf:"bytes,3,rep,name=signatures,proto3" json:"signatures,omitempty"` +} + +func (m *TxRaw) Reset() { *m = TxRaw{} } +func (m *TxRaw) String() string { return proto.CompactTextString(m) } +func (*TxRaw) ProtoMessage() {} +func (*TxRaw) Descriptor() ([]byte, []int) { + return fileDescriptor_52d5d5e2efced9ba, []int{0} +} +func (m *TxRaw) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TxRaw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TxRaw.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 *TxRaw) XXX_Merge(src proto.Message) { + xxx_messageInfo_TxRaw.Merge(m, src) +} +func (m *TxRaw) XXX_Size() int { + return m.Size() +} +func (m *TxRaw) XXX_DiscardUnknown() { + xxx_messageInfo_TxRaw.DiscardUnknown(m) +} + +var xxx_messageInfo_TxRaw proto.InternalMessageInfo + +func (m *TxRaw) GetBodyBytes() []byte { + if m != nil { + return m.BodyBytes + } + return nil +} + +func (m *TxRaw) GetAuthInfoBytes() []byte { + if m != nil { + return m.AuthInfoBytes + } + return nil +} + +func (m *TxRaw) GetSignatures() [][]byte { + if m != nil { + return m.Signatures + } + return nil +} + +// SignDocRaw is used for verifying signatures with SIGN_MODE_DIRECT +type SignDocRaw struct { + BodyBytes []byte `protobuf:"bytes,1,opt,name=body_bytes,json=bodyBytes,proto3" json:"body_bytes,omitempty"` + AuthInfoBytes []byte `protobuf:"bytes,2,opt,name=auth_info_bytes,json=authInfoBytes,proto3" json:"auth_info_bytes,omitempty"` + ChainId string `protobuf:"bytes,3,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + AccountNumber uint64 `protobuf:"varint,4,opt,name=account_number,json=accountNumber,proto3" json:"account_number,omitempty"` + AccountSequence uint64 `protobuf:"varint,5,opt,name=account_sequence,json=accountSequence,proto3" json:"account_sequence,omitempty"` +} + +func (m *SignDocRaw) Reset() { *m = SignDocRaw{} } +func (m *SignDocRaw) String() string { return proto.CompactTextString(m) } +func (*SignDocRaw) ProtoMessage() {} +func (*SignDocRaw) Descriptor() ([]byte, []int) { + return fileDescriptor_52d5d5e2efced9ba, []int{1} +} +func (m *SignDocRaw) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SignDocRaw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SignDocRaw.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 *SignDocRaw) XXX_Merge(src proto.Message) { + xxx_messageInfo_SignDocRaw.Merge(m, src) +} +func (m *SignDocRaw) XXX_Size() int { + return m.Size() +} +func (m *SignDocRaw) XXX_DiscardUnknown() { + xxx_messageInfo_SignDocRaw.DiscardUnknown(m) +} + +var xxx_messageInfo_SignDocRaw proto.InternalMessageInfo + +func (m *SignDocRaw) GetBodyBytes() []byte { + if m != nil { + return m.BodyBytes + } + return nil +} + +func (m *SignDocRaw) GetAuthInfoBytes() []byte { + if m != nil { + return m.AuthInfoBytes + } + return nil +} + +func (m *SignDocRaw) GetChainId() string { + if m != nil { + return m.ChainId + } + return "" +} + +func (m *SignDocRaw) GetAccountNumber() uint64 { + if m != nil { + return m.AccountNumber + } + return 0 +} + +func (m *SignDocRaw) GetAccountSequence() uint64 { + if m != nil { + return m.AccountSequence + } + return 0 +} + +func init() { + proto.RegisterType((*TxRaw)(nil), "cosmos_sdk.tx.signing.v1.TxRaw") + proto.RegisterType((*SignDocRaw)(nil), "cosmos_sdk.tx.signing.v1.SignDocRaw") +} + +func init() { proto.RegisterFile("types/tx/signing/types.proto", fileDescriptor_52d5d5e2efced9ba) } + +var fileDescriptor_52d5d5e2efced9ba = []byte{ + // 297 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0xd1, 0xc1, 0x4a, 0xc3, 0x30, + 0x18, 0xc0, 0xf1, 0xc5, 0x6d, 0xea, 0x3e, 0x36, 0x27, 0x3d, 0x45, 0xd0, 0x50, 0x06, 0x4a, 0x3d, + 0xac, 0x45, 0x7c, 0x83, 0x21, 0xc8, 0x2e, 0x1e, 0x3a, 0x4f, 0x5e, 0x4a, 0x9b, 0x66, 0x5d, 0x18, + 0x4b, 0xe6, 0x92, 0xe8, 0xfa, 0x16, 0x3e, 0x92, 0x47, 0x8f, 0x3b, 0x7a, 0x94, 0xf6, 0x45, 0xa4, + 0x59, 0x04, 0xf1, 0xec, 0x29, 0xe4, 0xc7, 0x9f, 0x04, 0xbe, 0x0f, 0xce, 0x75, 0xb9, 0x66, 0x2a, + 0xd2, 0xdb, 0x48, 0xf1, 0x42, 0x70, 0x51, 0x44, 0x16, 0xc2, 0xf5, 0x46, 0x6a, 0xe9, 0x61, 0x2a, + 0xd5, 0x4a, 0xaa, 0x44, 0xe5, 0xcb, 0x50, 0x6f, 0x43, 0x97, 0x84, 0x2f, 0x37, 0x23, 0x01, 0xdd, + 0xc7, 0x6d, 0x9c, 0xbe, 0x7a, 0x17, 0x00, 0x99, 0xcc, 0xcb, 0x24, 0x2b, 0x35, 0x53, 0x18, 0xf9, + 0x28, 0xe8, 0xc7, 0xbd, 0x46, 0x26, 0x0d, 0x78, 0x57, 0x30, 0x4c, 0x8d, 0x5e, 0x24, 0x5c, 0xcc, + 0xa5, 0x6b, 0x0e, 0x6c, 0x33, 0x68, 0x78, 0x2a, 0xe6, 0x72, 0xdf, 0x11, 0x80, 0xe6, 0xf5, 0x54, + 0x9b, 0x0d, 0x53, 0xb8, 0xed, 0xb7, 0x83, 0x7e, 0xfc, 0x4b, 0x46, 0xef, 0x08, 0x60, 0xc6, 0x0b, + 0x71, 0x27, 0xe9, 0x3f, 0xfe, 0x7a, 0x06, 0xc7, 0x74, 0x91, 0x72, 0x91, 0xf0, 0x1c, 0xb7, 0x7d, + 0x14, 0xf4, 0xe2, 0x23, 0x7b, 0x9f, 0xe6, 0xde, 0x25, 0x9c, 0xa4, 0x94, 0x4a, 0x23, 0x74, 0x22, + 0xcc, 0x2a, 0x63, 0x1b, 0xdc, 0xf1, 0x51, 0xd0, 0x89, 0x07, 0x4e, 0x1f, 0x2c, 0x7a, 0xd7, 0x70, + 0xfa, 0x93, 0x29, 0xf6, 0x6c, 0x98, 0xa0, 0x0c, 0x77, 0x6d, 0x38, 0x74, 0x3e, 0x73, 0x3c, 0xb9, + 0xff, 0xa8, 0x08, 0xda, 0x55, 0x04, 0x7d, 0x55, 0x04, 0xbd, 0xd5, 0xa4, 0xb5, 0xab, 0x49, 0xeb, + 0xb3, 0x26, 0xad, 0xa7, 0x71, 0xc1, 0xf5, 0xc2, 0x64, 0x21, 0x95, 0xab, 0x68, 0x3f, 0x71, 0x77, + 0x8c, 0x55, 0xbe, 0x8c, 0xfe, 0x6e, 0x28, 0x3b, 0xb4, 0xcb, 0xb9, 0xfd, 0x0e, 0x00, 0x00, 0xff, + 0xff, 0x34, 0x9a, 0xbd, 0x5a, 0xbc, 0x01, 0x00, 0x00, +} + +func (m *TxRaw) 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 *TxRaw) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TxRaw) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signatures) > 0 { + for iNdEx := len(m.Signatures) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Signatures[iNdEx]) + copy(dAtA[i:], m.Signatures[iNdEx]) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Signatures[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + if len(m.AuthInfoBytes) > 0 { + i -= len(m.AuthInfoBytes) + copy(dAtA[i:], m.AuthInfoBytes) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AuthInfoBytes))) + i-- + dAtA[i] = 0x12 + } + if len(m.BodyBytes) > 0 { + i -= len(m.BodyBytes) + copy(dAtA[i:], m.BodyBytes) + i = encodeVarintTypes(dAtA, i, uint64(len(m.BodyBytes))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *SignDocRaw) 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 *SignDocRaw) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SignDocRaw) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.AccountSequence != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.AccountSequence)) + i-- + dAtA[i] = 0x28 + } + if m.AccountNumber != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.AccountNumber)) + i-- + dAtA[i] = 0x20 + } + if len(m.ChainId) > 0 { + i -= len(m.ChainId) + copy(dAtA[i:], m.ChainId) + i = encodeVarintTypes(dAtA, i, uint64(len(m.ChainId))) + i-- + dAtA[i] = 0x1a + } + if len(m.AuthInfoBytes) > 0 { + i -= len(m.AuthInfoBytes) + copy(dAtA[i:], m.AuthInfoBytes) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AuthInfoBytes))) + i-- + dAtA[i] = 0x12 + } + if len(m.BodyBytes) > 0 { + i -= len(m.BodyBytes) + copy(dAtA[i:], m.BodyBytes) + i = encodeVarintTypes(dAtA, i, uint64(len(m.BodyBytes))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *TxRaw) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.BodyBytes) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.AuthInfoBytes) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Signatures) > 0 { + for _, b := range m.Signatures { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *SignDocRaw) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.BodyBytes) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.AuthInfoBytes) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.ChainId) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.AccountNumber != 0 { + n += 1 + sovTypes(uint64(m.AccountNumber)) + } + if m.AccountSequence != 0 { + n += 1 + sovTypes(uint64(m.AccountSequence)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *TxRaw) 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 ErrIntOverflowTypes + } + 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: TxRaw: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TxRaw: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BodyBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BodyBytes = append(m.BodyBytes[:0], dAtA[iNdEx:postIndex]...) + if m.BodyBytes == nil { + m.BodyBytes = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AuthInfoBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AuthInfoBytes = append(m.AuthInfoBytes[:0], dAtA[iNdEx:postIndex]...) + if m.AuthInfoBytes == nil { + m.AuthInfoBytes = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signatures = append(m.Signatures, make([]byte, postIndex-iNdEx)) + copy(m.Signatures[len(m.Signatures)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SignDocRaw) 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 ErrIntOverflowTypes + } + 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: SignDocRaw: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SignDocRaw: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BodyBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BodyBytes = append(m.BodyBytes[:0], dAtA[iNdEx:postIndex]...) + if m.BodyBytes == nil { + m.BodyBytes = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AuthInfoBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AuthInfoBytes = append(m.AuthInfoBytes[:0], dAtA[iNdEx:postIndex]...) + if m.AuthInfoBytes == nil { + m.AuthInfoBytes = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ChainId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountNumber", wireType) + } + m.AccountNumber = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.AccountNumber |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AccountSequence", wireType) + } + m.AccountSequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.AccountSequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(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, ErrIntOverflowTypes + } + 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, ErrIntOverflowTypes + } + 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, ErrIntOverflowTypes + } + 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, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/types/tx/signing/types.proto b/types/tx/signing/types.proto new file mode 100644 index 000000000000..541cd68ba63e --- /dev/null +++ b/types/tx/signing/types.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package cosmos_sdk.tx.signing.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/types/tx/signing"; + +// TxRaw is using for transaction decoding and verification +message TxRaw { + bytes body_bytes = 1; + + bytes auth_info_bytes = 2; + + repeated bytes signatures = 3; +} + +// SignDocRaw is used for verifying signatures with SIGN_MODE_DIRECT +message SignDocRaw { + bytes body_bytes = 1; + + bytes auth_info_bytes = 2; + + string chain_id = 3; + + uint64 account_number = 4; + + uint64 account_sequence = 5; +} diff --git a/types/tx/signing/verify.go b/types/tx/signing/verify.go new file mode 100644 index 000000000000..97566353c940 --- /dev/null +++ b/types/tx/signing/verify.go @@ -0,0 +1,27 @@ +package signing + +import ( + "github.com/cosmos/cosmos-sdk/crypto/multisig" + sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" +) + +func VerifySignature(signingData types.SigningData, sigData types.SignatureData, tx sdk.Tx, handler types.SignModeHandler) bool { + switch data := sigData.(type) { + case *types.SingleSignatureData: + signBytes, err := handler.GetSignBytes(data.SignMode, signingData, tx) + if err != nil { + return false + } + return signingData.PublicKey.VerifyBytes(signBytes, data.Signature) + case *types.MultiSignatureData: + multiPK, ok := signingData.PublicKey.(multisig.MultisigPubKey) + if !ok { + return false + } + return multiPK.VerifyMultisignature(func(mode types.SignMode) ([]byte, error) { + return handler.GetSignBytes(mode, signingData, tx) + }, data) + } + return false +} diff --git a/types/tx/tx.go b/types/tx/tx.go new file mode 100644 index 000000000000..f0c5cba0ea9f --- /dev/null +++ b/types/tx/tx.go @@ -0,0 +1,202 @@ +package types + +import ( + "github.com/tendermint/tendermint/crypto" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +type ProtoTx interface { + sdk.Tx + FeeTx + TxWithMemo + SigTx + + GetBody() *TxBody + GetAuthInfo() *AuthInfo + GetSignatures() [][]byte + + GetBodyBytes() []byte + GetAuthInfoBytes() []byte +} + +var _ ProtoTx = &Tx{} + +func NewTx() *Tx { + return &Tx{ + Body: &TxBody{}, + AuthInfo: &AuthInfo{ + SignerInfos: nil, + Fee: &Fee{}, + }, + Signatures: nil, + } +} + +func (tx *Tx) GetMsgs() []sdk.Msg { + anys := tx.Body.Messages + res := make([]sdk.Msg, len(anys)) + for i, any := range anys { + msg := any.GetCachedValue().(sdk.Msg) + res[i] = msg + } + return res +} + +func (tx *Tx) ValidateBasic() error { + sigs := tx.GetSignatures() + + if tx.GetGas() > MaxGasWanted { + return sdkerrors.Wrapf( + sdkerrors.ErrInvalidRequest, + "invalid gas supplied; %d > %d", tx.GetGas(), MaxGasWanted, + ) + } + if tx.GetFee().IsAnyNegative() { + return sdkerrors.Wrapf( + sdkerrors.ErrInsufficientFee, + "invalid fee provided: %s", tx.GetFee(), + ) + } + if len(sigs) == 0 { + return sdkerrors.ErrNoSignatures + } + if len(sigs) != len(tx.GetSigners()) { + return sdkerrors.Wrapf( + sdkerrors.ErrUnauthorized, + "wrong number of signers; expected %d, got %d", tx.GetSigners(), len(sigs), + ) + } + + return nil +} + +func (m *Tx) GetGas() uint64 { + return m.AuthInfo.Fee.GasLimit +} + +func (m *Tx) GetFee() sdk.Coins { + return m.AuthInfo.Fee.Amount +} + +func (m *Tx) FeePayer() sdk.AccAddress { + signers := m.GetSigners() + if signers != nil { + return signers[0] + } + return sdk.AccAddress{} +} + +func (m *Tx) GetMemo() string { + if m.Body == nil { + return "" + } + return m.Body.Memo +} + +func (m *Tx) GetSigners() []sdk.AccAddress { + var signers []sdk.AccAddress + seen := map[string]bool{} + + for _, msg := range m.GetMsgs() { + for _, addr := range msg.GetSigners() { + if !seen[addr.String()] { + signers = append(signers, addr) + seen[addr.String()] = true + } + } + } + return signers +} + +func (m *Tx) GetPubKeys() []crypto.PubKey { + signerInfos := m.AuthInfo.SignerInfos + res := make([]crypto.PubKey, len(signerInfos)) + for i, si := range signerInfos { + res[i] = si.PublicKey.GetCachedPubKey() + } + return res +} + +func (m *Tx) GetBodyBytes() []byte { + bz, err := m.Body.Marshal() + if err != nil { + panic(err) + } + return bz +} + +func (m *Tx) GetAuthInfoBytes() []byte { + bz, err := m.AuthInfo.Marshal() + if err != nil { + panic(err) + } + return bz +} + +var _ codectypes.UnpackInterfacesMessage = &Tx{} +var _ codectypes.UnpackInterfacesMessage = &TxBody{} +var _ codectypes.UnpackInterfacesMessage = &SignDoc{} + +func (m *Tx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { + if m.Body != nil { + return m.Body.UnpackInterfaces(unpacker) + } + return nil +} + +func (m *SignDoc) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { + return m.Body.UnpackInterfaces(unpacker) +} + +func (m *TxBody) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { + for _, any := range m.Messages { + var msg sdk.Msg + err := unpacker.UnpackAny(any, &msg) + if err != nil { + return err + } + } + return nil +} + +// FeeTx defines the interface to be implemented by Tx to use the FeeDecorators +type FeeTx interface { + sdk.Tx + GetGas() uint64 + GetFee() sdk.Coins + FeePayer() sdk.AccAddress +} + +// Tx must have GetMemo() method to use ValidateMemoDecorator +type TxWithMemo interface { + sdk.Tx + GetMemo() string +} + +type SigTx interface { + sdk.Tx + GetSignatures() [][]byte + GetSigners() []sdk.AccAddress + GetPubKeys() []crypto.PubKey // If signer already has pubkey in context, this list will have nil in its place + GetSignatureData() ([]SignatureData, error) +} + +func (m *Tx) GetSignatureData() ([]SignatureData, error) { + signerInfos := m.AuthInfo.SignerInfos + sigs := m.Signatures + n := len(signerInfos) + res := make([]SignatureData, n) + + for i, si := range signerInfos { + var err error + res[i], err = ModeInfoToSignatureData(si.ModeInfo, sigs[i]) + if err != nil { + return nil, err + } + } + + return res, nil +} diff --git a/types/tx/types.pb.go b/types/tx/types.pb.go index 16e2ac453b56..e46ce5a7ff0d 100644 --- a/types/tx/types.pb.go +++ b/types/tx/types.pb.go @@ -365,7 +365,7 @@ func (m *AuthInfo) GetFee() *Fee { type SignerInfo struct { // public_key is the public key of the signer. It is optional for accounts // that already exist in state - PublicKey *types.Any `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` + PublicKey *types1.PublicKey `protobuf:"bytes,1,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"` // mode_info describes the signing mode of the signer and is a nested // structure to support nested multisig pubkey's ModeInfo *ModeInfo `protobuf:"bytes,2,opt,name=mode_info,json=modeInfo,proto3" json:"mode_info,omitempty"` @@ -404,7 +404,7 @@ func (m *SignerInfo) XXX_DiscardUnknown() { var xxx_messageInfo_SignerInfo proto.InternalMessageInfo -func (m *SignerInfo) GetPublicKey() *types.Any { +func (m *SignerInfo) GetPublicKey() *types1.PublicKey { if m != nil { return m.PublicKey } @@ -684,60 +684,61 @@ func init() { func init() { proto.RegisterFile("types/tx/types.proto", fileDescriptor_1c6ac8fa65877134) } var fileDescriptor_1c6ac8fa65877134 = []byte{ - // 842 bytes of a gzipped FileDescriptorProto + // 849 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0x4d, 0x6f, 0xe3, 0x44, 0x18, 0x8e, 0x93, 0x34, 0x4d, 0xde, 0xee, 0x47, 0x3a, 0xb4, 0x92, 0x9b, 0xa2, 0x34, 0x44, 0x2a, - 0x04, 0x04, 0xce, 0xb2, 0x7b, 0x60, 0x11, 0x87, 0x55, 0x92, 0xa6, 0xdb, 0x40, 0x9b, 0xa2, 0x49, - 0x56, 0x82, 0x95, 0x90, 0xe5, 0xd8, 0x53, 0x67, 0xd4, 0x78, 0x26, 0x78, 0xc6, 0x28, 0xe1, 0x82, - 0x38, 0x70, 0xe2, 0xc2, 0x85, 0x3f, 0xc1, 0x2f, 0x59, 0x71, 0xda, 0x23, 0x17, 0x3e, 0xd4, 0xfe, - 0x10, 0x90, 0xc7, 0xe3, 0xa4, 0x6a, 0x4a, 0xb8, 0x71, 0xca, 0xeb, 0xc7, 0xcf, 0xf3, 0xcc, 0xfb, - 0x95, 0x31, 0xec, 0xc8, 0xf9, 0x94, 0x88, 0xa6, 0x9c, 0x35, 0x55, 0x60, 0x4d, 0x43, 0x2e, 0x39, - 0x2a, 0xbb, 0x5c, 0x04, 0x5c, 0xd8, 0xc2, 0xbb, 0xb4, 0xe4, 0xcc, 0xfa, 0xe6, 0xc3, 0xca, 0xdb, - 0x72, 0x4c, 0x43, 0xcf, 0x9e, 0x3a, 0xa1, 0x9c, 0x37, 0x15, 0xa9, 0xe9, 0x73, 0x9f, 0x2f, 0xa3, - 0x44, 0x59, 0x31, 0xdd, 0x70, 0x3e, 0x95, 0xbc, 0xa9, 0x6d, 0x97, 0x9e, 0x95, 0xed, 0x55, 0x68, - 0xcf, 0xe7, 0xdc, 0x9f, 0x90, 0xc4, 0x6f, 0x14, 0x5d, 0x34, 0x1d, 0x36, 0x4f, 0x5e, 0xd5, 0x7f, - 0x34, 0x20, 0x3b, 0x9c, 0xa1, 0xf7, 0x21, 0x3f, 0xe2, 0xde, 0xdc, 0x34, 0x6a, 0x46, 0x63, 0xeb, - 0xb1, 0x69, 0xdd, 0xce, 0xcb, 0x1a, 0xce, 0xda, 0xdc, 0x9b, 0x63, 0xc5, 0x42, 0x1f, 0x41, 0xc9, - 0x89, 0xe4, 0xd8, 0xa6, 0xec, 0x82, 0x9b, 0x59, 0x25, 0xa9, 0xac, 0x4a, 0x5a, 0x91, 0x1c, 0xf7, - 0xd8, 0x05, 0xc7, 0x45, 0x47, 0x47, 0xa8, 0x0a, 0x20, 0xa8, 0xcf, 0x1c, 0x19, 0x85, 0x44, 0x98, - 0xb9, 0x5a, 0xae, 0x71, 0x0f, 0xdf, 0x40, 0xea, 0xbf, 0x1b, 0xb0, 0x39, 0xa0, 0x3e, 0x3b, 0xe2, - 0xee, 0xff, 0x95, 0xd2, 0x1e, 0x14, 0xdd, 0xb1, 0x43, 0x99, 0x4d, 0x3d, 0x33, 0x57, 0x33, 0x1a, - 0x25, 0xbc, 0xa9, 0x9e, 0x7b, 0x1e, 0x3a, 0x84, 0x07, 0x8e, 0xeb, 0xf2, 0x88, 0x49, 0x9b, 0x45, - 0xc1, 0x88, 0x84, 0x66, 0xbe, 0x66, 0x34, 0xf2, 0xf8, 0xbe, 0x46, 0xfb, 0x0a, 0x44, 0xef, 0x42, - 0x39, 0xa5, 0x09, 0xf2, 0x75, 0x44, 0x98, 0x4b, 0xcc, 0x0d, 0x45, 0x7c, 0xa8, 0xf1, 0x81, 0x86, - 0xeb, 0x3f, 0x67, 0xa1, 0x90, 0xa4, 0x8d, 0x1e, 0x41, 0x31, 0x20, 0x42, 0x38, 0x3e, 0x11, 0xa6, - 0x51, 0xcb, 0x35, 0xb6, 0x1e, 0xef, 0x58, 0xc9, 0x98, 0xac, 0x74, 0x4c, 0x56, 0x8b, 0xcd, 0xf1, - 0x82, 0x85, 0x10, 0xe4, 0x03, 0x12, 0x24, 0xd5, 0x95, 0xb0, 0x8a, 0xe3, 0x14, 0x25, 0x0d, 0x08, - 0x8f, 0xa4, 0x3d, 0x26, 0xd4, 0x1f, 0x4b, 0x55, 0x43, 0x0e, 0xdf, 0xd7, 0xe8, 0x89, 0x02, 0x51, - 0x1b, 0xb6, 0xc9, 0x4c, 0x12, 0x26, 0x28, 0x67, 0x36, 0x9f, 0x4a, 0xca, 0x99, 0x30, 0xff, 0xde, - 0x5c, 0x73, 0x6c, 0x79, 0xc1, 0x3f, 0x4f, 0xe8, 0xe8, 0x25, 0x54, 0x19, 0x67, 0xb6, 0x1b, 0x52, - 0x49, 0x5d, 0x67, 0x62, 0xdf, 0x61, 0xf8, 0x70, 0x8d, 0xe1, 0x3e, 0xe3, 0xac, 0xa3, 0xb5, 0xdd, - 0x5b, 0xde, 0x75, 0x09, 0xc5, 0x74, 0x34, 0xe8, 0x19, 0xdc, 0x8b, 0x37, 0x82, 0x84, 0x6a, 0x96, - 0x69, 0x73, 0xde, 0x5c, 0x1d, 0xe6, 0x40, 0xb1, 0xd4, 0x38, 0xb7, 0xc4, 0x22, 0x16, 0xe8, 0x1d, - 0xc8, 0x5d, 0x10, 0xa2, 0x97, 0x60, 0x77, 0x55, 0x77, 0x4c, 0x08, 0x8e, 0x19, 0xf5, 0x6f, 0x01, - 0x96, 0x1e, 0xe8, 0x09, 0xc0, 0x34, 0x1a, 0x4d, 0xa8, 0x6b, 0x5f, 0x92, 0x74, 0xeb, 0xee, 0x2e, - 0xa5, 0x94, 0xf0, 0x3e, 0x23, 0x6a, 0xed, 0x02, 0xee, 0x91, 0xff, 0x58, 0xbb, 0x33, 0xee, 0x91, - 0x64, 0xed, 0x02, 0x1d, 0xd5, 0x7f, 0xcd, 0x42, 0x31, 0x85, 0xd1, 0x27, 0x50, 0x10, 0x94, 0xf9, - 0x13, 0xa2, 0x8f, 0x7d, 0xeb, 0xdf, 0x2d, 0xac, 0x81, 0x22, 0x9e, 0x64, 0xb0, 0x96, 0xa0, 0xa7, - 0xb0, 0x11, 0x44, 0x13, 0x49, 0xf5, 0xf1, 0xb5, 0x35, 0xda, 0xb3, 0x98, 0x77, 0x92, 0xc1, 0x89, - 0xa0, 0xf2, 0x14, 0x0a, 0x89, 0x1b, 0xb2, 0x20, 0x1f, 0x67, 0xa6, 0x8e, 0x7f, 0x70, 0x57, 0x05, - 0x71, 0x9f, 0x62, 0x1b, 0xac, 0x78, 0x95, 0x1f, 0x0c, 0xd8, 0x50, 0x66, 0xa8, 0x05, 0xc5, 0x11, - 0x95, 0x4e, 0x18, 0x3a, 0x69, 0xcf, 0x0e, 0x6f, 0xaa, 0x93, 0x5b, 0x2a, 0x76, 0xe8, 0xf0, 0x60, - 0xea, 0xb8, 0xb2, 0x4d, 0x65, 0x2b, 0x26, 0xe3, 0x85, 0x0c, 0x7d, 0x0c, 0xb0, 0xe8, 0xa1, 0x30, - 0xb3, 0x6a, 0xdc, 0xeb, 0x9a, 0x58, 0x4a, 0x9b, 0x28, 0xda, 0x1b, 0x90, 0x13, 0x51, 0x50, 0xff, - 0xde, 0x80, 0xdc, 0x31, 0x21, 0xe8, 0x2b, 0x28, 0x38, 0x41, 0xfc, 0x87, 0xd3, 0x4b, 0xf3, 0xc6, - 0x4d, 0x17, 0x95, 0x03, 0x65, 0xed, 0x47, 0xaf, 0xfe, 0x38, 0xc8, 0xfc, 0xf2, 0xe7, 0x41, 0xc3, - 0xa7, 0x72, 0x1c, 0x8d, 0x2c, 0x97, 0x07, 0xcd, 0x84, 0xa6, 0x7f, 0x3e, 0x10, 0xde, 0xa5, 0xbe, - 0x3e, 0x63, 0x81, 0xc0, 0xda, 0x14, 0xed, 0x43, 0xc9, 0x77, 0x84, 0x3d, 0xa1, 0x01, 0x95, 0xaa, - 0xdb, 0x79, 0x5c, 0xf4, 0x1d, 0x71, 0x1a, 0x3f, 0xbf, 0x27, 0xa0, 0x98, 0x36, 0x09, 0xed, 0xc1, - 0xee, 0xa0, 0xf7, 0xbc, 0x6f, 0x9f, 0x9d, 0x1f, 0x75, 0xed, 0x17, 0xfd, 0xc1, 0xe7, 0xdd, 0x4e, - 0xef, 0xb8, 0xd7, 0x3d, 0x2a, 0x67, 0xd0, 0x0e, 0x94, 0x97, 0xaf, 0x8e, 0x7a, 0xb8, 0xdb, 0x19, - 0x96, 0x0d, 0xb4, 0x0b, 0xdb, 0x4b, 0x74, 0xd8, 0xfd, 0x62, 0xf8, 0xa2, 0x75, 0x5a, 0xce, 0xa2, - 0x03, 0xd8, 0x5f, 0xc2, 0xa7, 0xdd, 0xe7, 0xad, 0xce, 0x97, 0x76, 0xeb, 0xac, 0xd7, 0x3f, 0xb7, - 0x3f, 0x1d, 0x9c, 0xf7, 0xcb, 0xdf, 0xb5, 0x9f, 0xbd, 0xba, 0xaa, 0x1a, 0xaf, 0xaf, 0xaa, 0xc6, - 0x5f, 0x57, 0x55, 0xe3, 0xa7, 0xeb, 0x6a, 0xe6, 0xf5, 0x75, 0x35, 0xf3, 0xdb, 0x75, 0x35, 0xf3, - 0xf2, 0x70, 0x7d, 0x75, 0xfa, 0x33, 0x34, 0x2a, 0xa8, 0xc5, 0x7e, 0xf2, 0x4f, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x28, 0x03, 0x76, 0x89, 0x9f, 0x06, 0x00, 0x00, + 0x04, 0x04, 0xce, 0xb2, 0x1c, 0x58, 0x84, 0xc4, 0x2a, 0x49, 0xd3, 0x6d, 0xa0, 0x4d, 0x57, 0x93, + 0xac, 0x04, 0x2b, 0x21, 0xcb, 0xb1, 0xa7, 0xce, 0xa8, 0xf1, 0x4c, 0xf0, 0x8c, 0x51, 0x72, 0x42, + 0x1c, 0xf6, 0xc4, 0x85, 0x0b, 0x7f, 0x82, 0x5f, 0xb2, 0xe2, 0xb4, 0x47, 0x2e, 0x7c, 0xa8, 0xfd, + 0x21, 0x20, 0x8f, 0xc7, 0x49, 0xb5, 0x29, 0xe1, 0xb6, 0xa7, 0xbc, 0x7e, 0xfc, 0x3c, 0xcf, 0xbc, + 0x5f, 0x13, 0xc3, 0x8e, 0x9c, 0x4f, 0x89, 0x68, 0xca, 0x59, 0x53, 0x05, 0xd6, 0x34, 0xe4, 0x92, + 0xa3, 0xb2, 0xcb, 0x45, 0xc0, 0x85, 0x2d, 0xbc, 0x4b, 0x4b, 0xce, 0xac, 0xef, 0x3f, 0xae, 0xbc, + 0x2b, 0xc7, 0x34, 0xf4, 0xec, 0xa9, 0x13, 0xca, 0x79, 0x53, 0x91, 0x9a, 0x3e, 0xf7, 0xf9, 0x32, + 0x4a, 0x94, 0x15, 0xd3, 0x0d, 0xe7, 0x53, 0xc9, 0x9b, 0xda, 0x76, 0xe9, 0x59, 0xd9, 0x5e, 0x85, + 0xf6, 0x7c, 0xce, 0xfd, 0x09, 0x49, 0xfc, 0x46, 0xd1, 0x45, 0xd3, 0x61, 0xf3, 0xe4, 0x55, 0xfd, + 0x27, 0x03, 0xb2, 0xc3, 0x19, 0xfa, 0x10, 0xf2, 0x23, 0xee, 0xcd, 0x4d, 0xa3, 0x66, 0x34, 0xb6, + 0x1e, 0x9a, 0xd6, 0xeb, 0x79, 0x59, 0xc3, 0x59, 0x9b, 0x7b, 0x73, 0xac, 0x58, 0xe8, 0x53, 0x28, + 0x39, 0x91, 0x1c, 0xdb, 0x94, 0x5d, 0x70, 0x33, 0xab, 0x24, 0x95, 0x55, 0x49, 0x2b, 0x92, 0xe3, + 0x1e, 0xbb, 0xe0, 0xb8, 0xe8, 0xe8, 0x08, 0x55, 0x01, 0x04, 0xf5, 0x99, 0x23, 0xa3, 0x90, 0x08, + 0x33, 0x57, 0xcb, 0x35, 0xee, 0xe0, 0x1b, 0x48, 0xfd, 0x0f, 0x03, 0x36, 0x07, 0xd4, 0x67, 0x47, + 0xdc, 0x7d, 0x53, 0x29, 0xed, 0x41, 0xd1, 0x1d, 0x3b, 0x94, 0xd9, 0xd4, 0x33, 0x73, 0x35, 0xa3, + 0x51, 0xc2, 0x9b, 0xea, 0xb9, 0xe7, 0xa1, 0x43, 0xb8, 0xe7, 0xb8, 0x2e, 0x8f, 0x98, 0xb4, 0x59, + 0x14, 0x8c, 0x48, 0x68, 0xe6, 0x6b, 0x46, 0x23, 0x8f, 0xef, 0x6a, 0xb4, 0xaf, 0x40, 0xf4, 0x3e, + 0x94, 0x53, 0x9a, 0x20, 0xdf, 0x45, 0x84, 0xb9, 0xc4, 0xdc, 0x50, 0xc4, 0xfb, 0x1a, 0x1f, 0x68, + 0xb8, 0xfe, 0x4b, 0x16, 0x0a, 0x49, 0xda, 0xe8, 0x01, 0x14, 0x03, 0x22, 0x84, 0xe3, 0x13, 0x61, + 0x1a, 0xb5, 0x5c, 0x63, 0xeb, 0xe1, 0x8e, 0x95, 0x8c, 0xc9, 0x4a, 0xc7, 0x64, 0xb5, 0xd8, 0x1c, + 0x2f, 0x58, 0x08, 0x41, 0x3e, 0x20, 0x41, 0x52, 0x5d, 0x09, 0xab, 0x38, 0x4e, 0x51, 0xd2, 0x80, + 0xf0, 0x48, 0xda, 0x63, 0x42, 0xfd, 0xb1, 0x54, 0x35, 0xe4, 0xf0, 0x5d, 0x8d, 0x9e, 0x28, 0x10, + 0xb5, 0x61, 0x9b, 0xcc, 0x24, 0x61, 0x82, 0x72, 0x66, 0xf3, 0xa9, 0xa4, 0x9c, 0x09, 0xf3, 0x9f, + 0xcd, 0x35, 0xc7, 0x96, 0x17, 0xfc, 0xf3, 0x84, 0x8e, 0x9e, 0x43, 0x95, 0x71, 0x66, 0xbb, 0x21, + 0x95, 0xd4, 0x75, 0x26, 0xf6, 0x2d, 0x86, 0xf7, 0xd7, 0x18, 0xee, 0x33, 0xce, 0x3a, 0x5a, 0xdb, + 0x7d, 0xcd, 0xbb, 0x2e, 0xa1, 0x98, 0x8e, 0x06, 0x3d, 0x86, 0x3b, 0xf1, 0x46, 0x90, 0x50, 0xcd, + 0x32, 0x6d, 0xce, 0xdb, 0xab, 0xc3, 0x1c, 0x28, 0x96, 0x1a, 0xe7, 0x96, 0x58, 0xc4, 0x02, 0xbd, + 0x07, 0xb9, 0x0b, 0x42, 0xf4, 0x12, 0xec, 0xae, 0xea, 0x8e, 0x09, 0xc1, 0x31, 0xa3, 0xfe, 0xc2, + 0x00, 0x58, 0x9a, 0xa0, 0x2f, 0x00, 0xa6, 0xd1, 0x68, 0x42, 0x5d, 0xfb, 0x92, 0xa4, 0x6b, 0x77, + 0x70, 0x53, 0x9e, 0x5c, 0xb9, 0xd8, 0xe2, 0xa9, 0xe2, 0x7d, 0x45, 0xe6, 0xb8, 0x34, 0x4d, 0xc3, + 0x78, 0x05, 0x03, 0xee, 0x91, 0xff, 0x59, 0xc1, 0x33, 0xee, 0x91, 0x64, 0x05, 0x03, 0x1d, 0xd5, + 0x7f, 0xcb, 0x42, 0x31, 0x85, 0xd1, 0xe7, 0x50, 0x10, 0x94, 0xf9, 0x13, 0xa2, 0x33, 0x78, 0xe7, + 0xbf, 0x2d, 0xac, 0x81, 0x22, 0x9e, 0x64, 0xb0, 0x96, 0xa0, 0x47, 0xb0, 0x11, 0x44, 0x13, 0x49, + 0xf5, 0xf1, 0xb5, 0x35, 0xda, 0xb3, 0x98, 0x77, 0x92, 0xc1, 0x89, 0xa0, 0xf2, 0x08, 0x0a, 0x89, + 0x1b, 0xb2, 0x20, 0x1f, 0x67, 0xa6, 0x8e, 0xbf, 0x77, 0x5b, 0x05, 0x71, 0xcb, 0x62, 0x1b, 0xac, + 0x78, 0x95, 0x17, 0x06, 0x6c, 0x28, 0x33, 0xd4, 0x82, 0xe2, 0x88, 0x4a, 0x27, 0x0c, 0x9d, 0xb4, + 0x7d, 0x87, 0xb7, 0xb7, 0xaf, 0xc3, 0x83, 0xa9, 0xe3, 0xca, 0x36, 0x95, 0xad, 0x98, 0x8c, 0x17, + 0x32, 0xf4, 0x19, 0xc0, 0xa2, 0x87, 0xc2, 0xcc, 0xaa, 0xd1, 0xaf, 0x6b, 0x62, 0x29, 0x6d, 0xa2, + 0x68, 0x6f, 0x40, 0x4e, 0x44, 0x41, 0xfd, 0x47, 0x03, 0x72, 0xc7, 0x84, 0xa0, 0x6f, 0xa1, 0xe0, + 0x04, 0xf1, 0xe5, 0xd3, 0x0b, 0xf4, 0xd6, 0x4d, 0x17, 0x95, 0x03, 0x65, 0xed, 0x07, 0x2f, 0xff, + 0x3c, 0xc8, 0xfc, 0xfa, 0xd7, 0x41, 0xc3, 0xa7, 0x72, 0x1c, 0x8d, 0x2c, 0x97, 0x07, 0xcd, 0x84, + 0xa6, 0x7f, 0x3e, 0x12, 0xde, 0xa5, 0xfe, 0x2b, 0x8d, 0x05, 0x02, 0x6b, 0x53, 0xb4, 0x0f, 0x25, + 0xdf, 0x11, 0xf6, 0x84, 0x06, 0x54, 0xaa, 0x6e, 0xe7, 0x71, 0xd1, 0x77, 0xc4, 0x69, 0xfc, 0xfc, + 0x81, 0x80, 0x62, 0xda, 0x24, 0xb4, 0x07, 0xbb, 0x83, 0xde, 0x93, 0xbe, 0x7d, 0x76, 0x7e, 0xd4, + 0xb5, 0x9f, 0xf5, 0x07, 0x4f, 0xbb, 0x9d, 0xde, 0x71, 0xaf, 0x7b, 0x54, 0xce, 0xa0, 0x1d, 0x28, + 0x2f, 0x5f, 0x1d, 0xf5, 0x70, 0xb7, 0x33, 0x2c, 0x1b, 0x68, 0x17, 0xb6, 0x97, 0xe8, 0xb0, 0xfb, + 0xf5, 0xf0, 0x59, 0xeb, 0xb4, 0x9c, 0x45, 0x07, 0xb0, 0xbf, 0x84, 0x4f, 0xbb, 0x4f, 0x5a, 0x9d, + 0x6f, 0xec, 0xd6, 0x59, 0xaf, 0x7f, 0x6e, 0x7f, 0x39, 0x38, 0xef, 0x97, 0x7f, 0x68, 0x3f, 0x7e, + 0x79, 0x55, 0x35, 0x5e, 0x5d, 0x55, 0x8d, 0xbf, 0xaf, 0xaa, 0xc6, 0xcf, 0xd7, 0xd5, 0xcc, 0xab, + 0xeb, 0x6a, 0xe6, 0xf7, 0xeb, 0x6a, 0xe6, 0xf9, 0xe1, 0xfa, 0xea, 0xf4, 0x27, 0x69, 0x54, 0x50, + 0xf7, 0xf5, 0x93, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x86, 0x44, 0xd6, 0x71, 0xab, 0x06, 0x00, + 0x00, } func (m *Tx) Marshal() (dAtA []byte, err error) { @@ -2192,7 +2193,7 @@ func (m *SignerInfo) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } if m.PublicKey == nil { - m.PublicKey = &types.Any{} + m.PublicKey = &types1.PublicKey{} } if err := m.PublicKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err diff --git a/types/tx/types.proto b/types/tx/types.proto index 51ec4da84390..f6b4c8569d1a 100644 --- a/types/tx/types.proto +++ b/types/tx/types.proto @@ -81,7 +81,7 @@ message AuthInfo { message SignerInfo { // public_key is the public key of the signer. It is optional for accounts // that already exist in state - google.protobuf.Any public_key = 1; + cosmos_sdk.crypto.v1.PublicKey public_key = 1; // mode_info describes the signing mode of the signer and is a nested // structure to support nested multisig pubkey's @@ -105,6 +105,8 @@ message ModeInfo { message Single { // mode is the signing mode of the single signer SignMode mode = 1; + + bytes signature = 2; } // Multi is the mode info for a multisig public key @@ -148,3 +150,4 @@ message Fee { // before an out of gas error occurs uint64 gas_limit = 2; } + diff --git a/types/types.pb.go b/types/types.pb.go index 6b4d9813ab5f..39564330ee4c 100644 --- a/types/types.pb.go +++ b/types/types.pb.go @@ -5,6 +5,7 @@ package types import ( fmt "fmt" + types1 "github.com/cosmos/cosmos-sdk/codec/types" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" types "github.com/tendermint/tendermint/abci/types" @@ -384,6 +385,223 @@ func (m *SimulationResponse) GetResult() *Result { return nil } +// TxResponse defines a structure containing relevant tx data and metadata. The +// tags are stringified and the log is JSON decoded. +type TxResponse struct { + Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` + TxHash string `protobuf:"bytes,2,opt,name=txhash,proto3" json:"txhash,omitempty"` + Codespace string `protobuf:"bytes,3,opt,name=codespace,proto3" json:"codespace,omitempty"` + Code uint32 `protobuf:"varint,4,opt,name=code,proto3" json:"code,omitempty"` + Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"` + RawLog string `protobuf:"bytes,6,opt,name=raw_log,json=rawLog,proto3" json:"raw_log,omitempty"` + Logs ABCIMessageLogs `protobuf:"bytes,7,rep,name=logs,proto3,castrepeated=ABCIMessageLogs" json:"logs"` + Info string `protobuf:"bytes,8,opt,name=info,proto3" json:"info,omitempty"` + GasWanted int64 `protobuf:"varint,9,opt,name=gas_wanted,json=gasWanted,proto3" json:"gas_wanted,omitempty"` + GasUsed int64 `protobuf:"varint,10,opt,name=gas_used,json=gasUsed,proto3" json:"gas_used,omitempty"` + Tx *types1.Any `protobuf:"bytes,11,opt,name=tx,proto3" json:"tx,omitempty"` + Timestamp string `protobuf:"bytes,12,opt,name=timestamp,proto3" json:"timestamp,omitempty"` +} + +func (m *TxResponse) Reset() { *m = TxResponse{} } +func (*TxResponse) ProtoMessage() {} +func (*TxResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_2c0f90c600ad7e2e, []int{8} +} +func (m *TxResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *TxResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_TxResponse.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 *TxResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_TxResponse.Merge(m, src) +} +func (m *TxResponse) XXX_Size() int { + return m.Size() +} +func (m *TxResponse) XXX_DiscardUnknown() { + xxx_messageInfo_TxResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_TxResponse proto.InternalMessageInfo + +// ABCIMessageLog defines a structure containing an indexed tx ABCI message log. +type ABCIMessageLog struct { + MsgIndex uint32 `protobuf:"varint,1,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty"` + Log string `protobuf:"bytes,2,opt,name=log,proto3" json:"log,omitempty"` + // Events contains a slice of Event objects that were emitted during some + // execution. + Events StringEvents `protobuf:"bytes,3,rep,name=events,proto3,castrepeated=StringEvents" json:"events"` +} + +func (m *ABCIMessageLog) Reset() { *m = ABCIMessageLog{} } +func (*ABCIMessageLog) ProtoMessage() {} +func (*ABCIMessageLog) Descriptor() ([]byte, []int) { + return fileDescriptor_2c0f90c600ad7e2e, []int{9} +} +func (m *ABCIMessageLog) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ABCIMessageLog) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ABCIMessageLog.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 *ABCIMessageLog) XXX_Merge(src proto.Message) { + xxx_messageInfo_ABCIMessageLog.Merge(m, src) +} +func (m *ABCIMessageLog) XXX_Size() int { + return m.Size() +} +func (m *ABCIMessageLog) XXX_DiscardUnknown() { + xxx_messageInfo_ABCIMessageLog.DiscardUnknown(m) +} + +var xxx_messageInfo_ABCIMessageLog proto.InternalMessageInfo + +func (m *ABCIMessageLog) GetMsgIndex() uint32 { + if m != nil { + return m.MsgIndex + } + return 0 +} + +func (m *ABCIMessageLog) GetLog() string { + if m != nil { + return m.Log + } + return "" +} + +func (m *ABCIMessageLog) GetEvents() StringEvents { + if m != nil { + return m.Events + } + return nil +} + +// StringAttribute defines en Event object wrapper where all the attributes +// contain key/value pairs that are strings instead of raw bytes. +type StringEvent struct { + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + Attributes []Attribute `protobuf:"bytes,2,rep,name=attributes,proto3" json:"attributes"` +} + +func (m *StringEvent) Reset() { *m = StringEvent{} } +func (*StringEvent) ProtoMessage() {} +func (*StringEvent) Descriptor() ([]byte, []int) { + return fileDescriptor_2c0f90c600ad7e2e, []int{10} +} +func (m *StringEvent) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StringEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StringEvent.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 *StringEvent) XXX_Merge(src proto.Message) { + xxx_messageInfo_StringEvent.Merge(m, src) +} +func (m *StringEvent) XXX_Size() int { + return m.Size() +} +func (m *StringEvent) XXX_DiscardUnknown() { + xxx_messageInfo_StringEvent.DiscardUnknown(m) +} + +var xxx_messageInfo_StringEvent proto.InternalMessageInfo + +func (m *StringEvent) GetType() string { + if m != nil { + return m.Type + } + return "" +} + +func (m *StringEvent) GetAttributes() []Attribute { + if m != nil { + return m.Attributes + } + return nil +} + +// Attribute defines an attribute wrapper where the key and value are +// strings instead of raw bytes. +type Attribute struct { + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *Attribute) Reset() { *m = Attribute{} } +func (*Attribute) ProtoMessage() {} +func (*Attribute) Descriptor() ([]byte, []int) { + return fileDescriptor_2c0f90c600ad7e2e, []int{11} +} +func (m *Attribute) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Attribute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Attribute.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 *Attribute) XXX_Merge(src proto.Message) { + xxx_messageInfo_Attribute.Merge(m, src) +} +func (m *Attribute) XXX_Size() int { + return m.Size() +} +func (m *Attribute) XXX_DiscardUnknown() { + xxx_messageInfo_Attribute.DiscardUnknown(m) +} + +var xxx_messageInfo_Attribute proto.InternalMessageInfo + +func (m *Attribute) GetKey() string { + if m != nil { + return m.Key + } + return "" +} + +func (m *Attribute) GetValue() string { + if m != nil { + return m.Value + } + return "" +} + func init() { proto.RegisterType((*Coin)(nil), "cosmos_sdk.v1.Coin") proto.RegisterType((*DecCoin)(nil), "cosmos_sdk.v1.DecCoin") @@ -393,46 +611,70 @@ func init() { proto.RegisterType((*GasInfo)(nil), "cosmos_sdk.v1.GasInfo") proto.RegisterType((*Result)(nil), "cosmos_sdk.v1.Result") proto.RegisterType((*SimulationResponse)(nil), "cosmos_sdk.v1.SimulationResponse") + proto.RegisterType((*TxResponse)(nil), "cosmos_sdk.v1.TxResponse") + proto.RegisterType((*ABCIMessageLog)(nil), "cosmos_sdk.v1.ABCIMessageLog") + proto.RegisterType((*StringEvent)(nil), "cosmos_sdk.v1.StringEvent") + proto.RegisterType((*Attribute)(nil), "cosmos_sdk.v1.Attribute") } func init() { proto.RegisterFile("types/types.proto", fileDescriptor_2c0f90c600ad7e2e) } var fileDescriptor_2c0f90c600ad7e2e = []byte{ - // 534 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x52, 0x4f, 0x6f, 0xd3, 0x4e, - 0x10, 0xb5, 0x7f, 0xf6, 0x2f, 0x7f, 0x36, 0xe1, 0x4f, 0x17, 0x8a, 0xa2, 0x0a, 0xec, 0xc8, 0x48, - 0x28, 0x48, 0xd4, 0x16, 0x29, 0xa7, 0x70, 0xc2, 0x04, 0x55, 0xe1, 0x84, 0x16, 0x01, 0x12, 0x97, - 0x68, 0xe3, 0xdd, 0xba, 0x56, 0xe3, 0xdd, 0xc8, 0xbb, 0x29, 0xca, 0x2d, 0x47, 0x8e, 0x7c, 0x84, - 0x7e, 0x9c, 0x1e, 0x73, 0xac, 0x10, 0xb2, 0x20, 0xb9, 0x70, 0xee, 0x91, 0x13, 0xda, 0xb5, 0xc1, - 0x6a, 0x7a, 0xe3, 0x92, 0xcc, 0xce, 0xbc, 0x79, 0x33, 0xf3, 0xfc, 0xc0, 0x8e, 0x5c, 0xcc, 0xa8, - 0x08, 0xf4, 0xaf, 0x3f, 0xcb, 0xb8, 0xe4, 0xf0, 0x46, 0xc4, 0x45, 0xca, 0xc5, 0x58, 0x90, 0x13, - 0xff, 0xf4, 0xe9, 0xde, 0x23, 0x79, 0x9c, 0x64, 0x64, 0x3c, 0xc3, 0x99, 0x5c, 0x04, 0x1a, 0x11, - 0xc4, 0x3c, 0xe6, 0x55, 0x54, 0xb4, 0xed, 0x1d, 0x5c, 0xc7, 0x49, 0xca, 0x08, 0xcd, 0xd2, 0x84, - 0xc9, 0x00, 0x4f, 0xa2, 0x24, 0xb8, 0x36, 0xcb, 0x3b, 0x04, 0xf6, 0x4b, 0x9e, 0x30, 0x78, 0x17, - 0xfc, 0x4f, 0x28, 0xe3, 0x69, 0xc7, 0xec, 0x9a, 0xbd, 0x26, 0x2a, 0x1e, 0xf0, 0x21, 0xa8, 0xe1, - 0x94, 0xcf, 0x99, 0xec, 0xfc, 0xa7, 0xd2, 0x61, 0xeb, 0x3c, 0x77, 0x8d, 0xaf, 0xb9, 0x6b, 0x8d, - 0x98, 0x44, 0x65, 0x69, 0x60, 0xff, 0x3c, 0x73, 0x4d, 0xef, 0x35, 0xa8, 0x0f, 0x69, 0xf4, 0x2f, - 0x5c, 0x43, 0x1a, 0x6d, 0x71, 0x3d, 0x06, 0x8d, 0x11, 0x93, 0x6f, 0xb4, 0x18, 0x0f, 0x80, 0x95, - 0x30, 0x59, 0x50, 0x5d, 0x9d, 0xaf, 0xf2, 0x0a, 0x3a, 0xa4, 0xd1, 0x5f, 0x28, 0xa1, 0xd1, 0x36, - 0x54, 0xd1, 0xab, 0xbc, 0x17, 0x82, 0xf6, 0x7b, 0x3c, 0x7d, 0x41, 0x48, 0x46, 0x85, 0xa0, 0x02, - 0x3e, 0x01, 0x4d, 0xfc, 0xe7, 0xd1, 0x31, 0xbb, 0x56, 0xaf, 0x1d, 0xde, 0xfc, 0x95, 0xbb, 0xa0, - 0x02, 0xa1, 0x0a, 0x30, 0xb0, 0x97, 0xdf, 0xba, 0xa6, 0xc7, 0x41, 0xfd, 0x10, 0x8b, 0x11, 0x3b, - 0xe2, 0xf0, 0x19, 0x00, 0x31, 0x16, 0xe3, 0x4f, 0x98, 0x49, 0x4a, 0xf4, 0x50, 0x3b, 0xdc, 0xbd, - 0xcc, 0xdd, 0x9d, 0x05, 0x4e, 0xa7, 0x03, 0xaf, 0xaa, 0x79, 0xa8, 0x19, 0x63, 0xf1, 0x41, 0xc7, - 0xd0, 0x07, 0x0d, 0x55, 0x99, 0x0b, 0x4a, 0xb4, 0x0e, 0x76, 0x78, 0xe7, 0x32, 0x77, 0x6f, 0x55, - 0x3d, 0xaa, 0xe2, 0xa1, 0x7a, 0x8c, 0xc5, 0x3b, 0x15, 0xcd, 0x40, 0x0d, 0x51, 0x31, 0x9f, 0x4a, - 0x08, 0x81, 0x4d, 0xb0, 0xc4, 0x7a, 0x52, 0x1b, 0xe9, 0x18, 0xde, 0x06, 0xd6, 0x94, 0xc7, 0x85, - 0xa0, 0x48, 0x85, 0x70, 0x00, 0x6a, 0xf4, 0x94, 0x32, 0x29, 0x3a, 0x56, 0xd7, 0xea, 0xb5, 0xfa, - 0xf7, 0xfd, 0xca, 0x03, 0xbe, 0xf2, 0x80, 0x5f, 0x7c, 0xfd, 0x57, 0x0a, 0x14, 0xda, 0x4a, 0x24, - 0x54, 0x76, 0x0c, 0xec, 0xcf, 0x67, 0xae, 0xe1, 0x2d, 0x4d, 0x00, 0xdf, 0x26, 0xe9, 0x7c, 0x8a, - 0x65, 0xc2, 0x19, 0xa2, 0x62, 0xc6, 0x99, 0xa0, 0xf0, 0x79, 0xb1, 0x78, 0xc2, 0x8e, 0xb8, 0x5e, - 0xa1, 0xd5, 0xbf, 0xe7, 0x5f, 0xf1, 0xa9, 0x5f, 0x0a, 0x13, 0x36, 0x14, 0xe9, 0x2a, 0x77, 0x4d, - 0x7d, 0x85, 0xd6, 0x6a, 0x1f, 0xd4, 0x32, 0x7d, 0x85, 0x5e, 0xb5, 0xd5, 0xdf, 0xdd, 0x6a, 0x2d, - 0x4e, 0x44, 0x25, 0x28, 0x1c, 0x5e, 0xfc, 0x70, 0x8c, 0xe5, 0xda, 0x31, 0xce, 0xd7, 0x8e, 0xb9, - 0x5a, 0x3b, 0xe6, 0xf7, 0xb5, 0x63, 0x7e, 0xd9, 0x38, 0xc6, 0x6a, 0xe3, 0x18, 0x17, 0x1b, 0xc7, - 0xf8, 0xe8, 0xc5, 0x89, 0x3c, 0x9e, 0x4f, 0xfc, 0x88, 0xa7, 0x41, 0x41, 0x55, 0xfe, 0xed, 0x0b, - 0x72, 0x52, 0x18, 0x7c, 0x52, 0xd3, 0x0e, 0x3f, 0xf8, 0x1d, 0x00, 0x00, 0xff, 0xff, 0x0e, 0xe8, - 0xc3, 0x0c, 0x62, 0x03, 0x00, 0x00, + // 862 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0xcf, 0x6f, 0x1b, 0x45, + 0x14, 0xf6, 0xc6, 0xdb, 0xb5, 0xfd, 0xec, 0xb4, 0x74, 0x48, 0xdb, 0x6d, 0x68, 0xbc, 0xd6, 0x82, + 0x50, 0x90, 0xe8, 0x5a, 0x24, 0x9c, 0x8c, 0x84, 0x94, 0x6d, 0x50, 0xeb, 0xaa, 0x48, 0x68, 0x5b, + 0x40, 0xe2, 0x62, 0x8d, 0x77, 0x27, 0xe3, 0x55, 0xbc, 0x33, 0xd6, 0xce, 0x38, 0xb1, 0x6f, 0x39, + 0x22, 0x71, 0x80, 0x3f, 0xa1, 0x67, 0xfe, 0x92, 0x1e, 0x73, 0xac, 0x10, 0x32, 0xe0, 0x5c, 0x38, + 0xf7, 0xc8, 0x09, 0xcd, 0xcc, 0xc6, 0xbf, 0xc2, 0x89, 0x8b, 0xfd, 0x7e, 0x7c, 0xf3, 0xde, 0xbc, + 0x6f, 0xbe, 0x7d, 0x70, 0x57, 0x4e, 0x47, 0x44, 0xb4, 0xf5, 0x6f, 0x30, 0xca, 0xb9, 0xe4, 0x68, + 0x3b, 0xe6, 0x22, 0xe3, 0xa2, 0x27, 0x92, 0xd3, 0xe0, 0xec, 0xb3, 0xdd, 0x8f, 0xe5, 0x20, 0xcd, + 0x93, 0xde, 0x08, 0xe7, 0x72, 0xda, 0xd6, 0x88, 0x36, 0xe5, 0x94, 0x2f, 0x2d, 0x73, 0x6c, 0xf7, + 0xf0, 0x26, 0x4e, 0x12, 0x96, 0x90, 0x3c, 0x4b, 0x99, 0x6c, 0xe3, 0x7e, 0x9c, 0xb6, 0x6f, 0xf4, + 0xda, 0x7d, 0x48, 0x39, 0xa7, 0x43, 0x62, 0xf0, 0xfd, 0xf1, 0x49, 0x1b, 0xb3, 0xa9, 0x49, 0xf9, + 0x4f, 0xc1, 0x7e, 0xc2, 0x53, 0x86, 0x76, 0xe0, 0x56, 0x42, 0x18, 0xcf, 0x5c, 0xab, 0x65, 0xed, + 0xd7, 0x22, 0xe3, 0xa0, 0x0f, 0xc1, 0xc1, 0x19, 0x1f, 0x33, 0xe9, 0x6e, 0xa9, 0x70, 0x58, 0x7f, + 0x33, 0xf3, 0x4a, 0xbf, 0xcd, 0xbc, 0x72, 0x97, 0xc9, 0xa8, 0x48, 0x75, 0xec, 0xbf, 0x5f, 0x7b, + 0x96, 0xff, 0x1c, 0x2a, 0xc7, 0x24, 0xfe, 0x3f, 0xb5, 0x8e, 0x49, 0xbc, 0x51, 0xeb, 0x13, 0xa8, + 0x76, 0x99, 0xfc, 0x46, 0xf3, 0xb4, 0x07, 0xe5, 0x94, 0x49, 0x53, 0x6a, 0xbd, 0xbf, 0x8a, 0x2b, + 0xe8, 0x31, 0x89, 0x17, 0xd0, 0x84, 0xc4, 0x9b, 0x50, 0x55, 0x5e, 0xc5, 0xfd, 0x10, 0x1a, 0xdf, + 0xe1, 0xe1, 0x51, 0x92, 0xe4, 0x44, 0x08, 0x22, 0xd0, 0xa7, 0x50, 0xc3, 0xd7, 0x8e, 0x6b, 0xb5, + 0xca, 0xfb, 0x8d, 0xf0, 0xf6, 0x3f, 0x33, 0x0f, 0x96, 0xa0, 0x68, 0x09, 0xe8, 0xd8, 0x17, 0xbf, + 0xb7, 0x2c, 0x9f, 0x43, 0xe5, 0x29, 0x16, 0x5d, 0x76, 0xc2, 0xd1, 0xe7, 0x00, 0x14, 0x8b, 0xde, + 0x39, 0x66, 0x92, 0x24, 0xba, 0xa9, 0x1d, 0xde, 0x7b, 0x37, 0xf3, 0xee, 0x4e, 0x71, 0x36, 0xec, + 0xf8, 0xcb, 0x9c, 0x1f, 0xd5, 0x28, 0x16, 0xdf, 0x6b, 0x1b, 0x05, 0x50, 0x55, 0x99, 0xb1, 0x20, + 0x89, 0xe6, 0xc1, 0x0e, 0xdf, 0x7f, 0x37, 0xf3, 0xee, 0x2c, 0xcf, 0xa8, 0x8c, 0x1f, 0x55, 0x28, + 0x16, 0xdf, 0x2a, 0x6b, 0x04, 0x4e, 0x44, 0xc4, 0x78, 0x28, 0x11, 0x02, 0x3b, 0xc1, 0x12, 0xeb, + 0x4e, 0x8d, 0x48, 0xdb, 0xe8, 0x3d, 0x28, 0x0f, 0x39, 0x35, 0x84, 0x46, 0xca, 0x44, 0x1d, 0x70, + 0xc8, 0x19, 0x61, 0x52, 0xb8, 0xe5, 0x56, 0x79, 0xbf, 0x7e, 0xf0, 0x28, 0x58, 0xca, 0x23, 0x50, + 0xf2, 0x08, 0x8c, 0x30, 0xbe, 0x52, 0xa0, 0xd0, 0x56, 0x24, 0x45, 0xc5, 0x89, 0x8e, 0xfd, 0xe3, + 0x6b, 0xaf, 0xe4, 0x5f, 0x58, 0x80, 0x5e, 0xa6, 0xd9, 0x78, 0x88, 0x65, 0xca, 0x59, 0x44, 0xc4, + 0x88, 0x33, 0x41, 0xd0, 0x17, 0xe6, 0xe2, 0x29, 0x3b, 0xe1, 0xfa, 0x0a, 0xf5, 0x83, 0xfb, 0xc1, + 0x9a, 0x84, 0x83, 0x82, 0x98, 0xb0, 0xaa, 0x8a, 0x5e, 0xce, 0x3c, 0x4b, 0x4f, 0xa1, 0xb9, 0x7a, + 0x0c, 0x4e, 0xae, 0xa7, 0xd0, 0x57, 0xad, 0x1f, 0xdc, 0xdb, 0x38, 0x6a, 0x46, 0x8c, 0x0a, 0x90, + 0xff, 0x53, 0x19, 0xe0, 0xd5, 0x64, 0xd1, 0xfa, 0x3e, 0x38, 0x03, 0x92, 0xd2, 0x81, 0x51, 0x41, + 0x39, 0x2a, 0x3c, 0xe4, 0x83, 0x23, 0x27, 0x03, 0x2c, 0x06, 0x85, 0xa2, 0x60, 0x3e, 0xf3, 0x9c, + 0x57, 0x93, 0x67, 0x58, 0x0c, 0xa2, 0x22, 0x83, 0x1e, 0x41, 0x2d, 0xe6, 0x09, 0x11, 0x23, 0x1c, + 0x13, 0xb7, 0xac, 0x79, 0x5a, 0x06, 0x14, 0xa7, 0xca, 0x71, 0xed, 0x96, 0xb5, 0xbf, 0x1d, 0x69, + 0x7b, 0xc1, 0xf3, 0x2d, 0x0d, 0x36, 0x3c, 0x3f, 0x80, 0x4a, 0x8e, 0xcf, 0x7b, 0x8a, 0x6b, 0x47, + 0x87, 0x9d, 0x1c, 0x9f, 0xbf, 0xe0, 0x14, 0x3d, 0x07, 0x7b, 0xc8, 0xa9, 0x70, 0x2b, 0x9a, 0xec, + 0xbd, 0x8d, 0xb1, 0x8e, 0xc2, 0x27, 0xdd, 0xaf, 0x89, 0x10, 0x98, 0x92, 0x17, 0x9c, 0x86, 0x0f, + 0x14, 0x31, 0xbf, 0xfe, 0xe1, 0xdd, 0x59, 0x8f, 0x8b, 0x48, 0xd7, 0x50, 0x8d, 0x35, 0xbb, 0x55, + 0xd3, 0x58, 0xd9, 0x68, 0x6f, 0x4d, 0x64, 0x35, 0x3d, 0xfe, 0x8a, 0x9a, 0x1e, 0xae, 0xa8, 0x09, + 0x74, 0xf2, 0x5a, 0x38, 0xe8, 0x23, 0xd8, 0x92, 0x13, 0xb7, 0xae, 0xe9, 0xde, 0x09, 0xcc, 0x02, + 0x08, 0xae, 0x17, 0x40, 0x70, 0xc4, 0xa6, 0xd1, 0x96, 0x9c, 0x28, 0x7a, 0x64, 0x9a, 0x11, 0x21, + 0x71, 0x36, 0x72, 0x1b, 0x86, 0x9e, 0x45, 0xa0, 0x10, 0xc4, 0xcf, 0x16, 0xdc, 0x5e, 0xbf, 0x31, + 0xfa, 0x00, 0x6a, 0x99, 0xa0, 0xbd, 0x94, 0x25, 0x64, 0xa2, 0x1f, 0x65, 0x3b, 0xaa, 0x66, 0x82, + 0x76, 0x95, 0xff, 0x1f, 0xa2, 0x7c, 0xb6, 0x21, 0xca, 0xdd, 0x0d, 0x9e, 0x5e, 0xca, 0x3c, 0x65, + 0xd4, 0x48, 0x72, 0xa7, 0x20, 0xa9, 0xb1, 0x12, 0x14, 0x4b, 0x89, 0xea, 0xaf, 0x90, 0x42, 0x7d, + 0x25, 0xab, 0x88, 0x53, 0xa2, 0x2e, 0xd6, 0x8d, 0xb6, 0xd1, 0x97, 0x00, 0x58, 0xca, 0x3c, 0xed, + 0x8f, 0x25, 0x11, 0xee, 0x96, 0x6e, 0xeb, 0x6e, 0x3e, 0xcf, 0x35, 0xa0, 0xf8, 0x0e, 0x56, 0x4e, + 0x14, 0x8d, 0x0e, 0xa1, 0xb6, 0x00, 0xa9, 0xb9, 0x4e, 0xc9, 0xb4, 0xe8, 0xa2, 0x4c, 0xb5, 0xe8, + 0xce, 0xf0, 0x70, 0x4c, 0x8a, 0x59, 0x8d, 0x13, 0x1e, 0xbf, 0xfd, 0xab, 0x59, 0xba, 0x98, 0x37, + 0x4b, 0x6f, 0xe6, 0x4d, 0xeb, 0x72, 0xde, 0xb4, 0xfe, 0x9c, 0x37, 0xad, 0x5f, 0xae, 0x9a, 0xa5, + 0xcb, 0xab, 0x66, 0xe9, 0xed, 0x55, 0xb3, 0xf4, 0x83, 0x4f, 0x53, 0x39, 0x18, 0xf7, 0x83, 0x98, + 0x67, 0x6d, 0x73, 0xa5, 0xe2, 0xef, 0xb1, 0x48, 0x4e, 0xcd, 0xe6, 0xee, 0x3b, 0xfa, 0xad, 0x0e, + 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x55, 0x6e, 0x3e, 0xc1, 0x3b, 0x06, 0x00, 0x00, } func (this *Coin) Equal(that interface{}) bool { @@ -796,162 +1038,1137 @@ func (m *SimulationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { - offset -= sovTypes(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Coin) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTypes(uint64(l)) - return n -} - -func (m *DecCoin) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) +func (m *TxResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - l = m.Amount.Size() - n += 1 + l + sovTypes(uint64(l)) - return n + return dAtA[:n], nil } -func (m *IntProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Int.Size() - n += 1 + l + sovTypes(uint64(l)) - return n +func (m *TxResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *DecProto) Size() (n int) { - if m == nil { - return 0 - } +func (m *TxResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = m.Dec.Size() - n += 1 + l + sovTypes(uint64(l)) - return n -} - -func (m *ValAddresses) Size() (n int) { - if m == nil { - return 0 + if len(m.Timestamp) > 0 { + i -= len(m.Timestamp) + copy(dAtA[i:], m.Timestamp) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Timestamp))) + i-- + dAtA[i] = 0x62 } - var l int - _ = l - if len(m.Addresses) > 0 { - for _, b := range m.Addresses { - l = len(b) - n += 1 + l + sovTypes(uint64(l)) + if m.Tx != nil { + { + size, err := m.Tx.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x5a } - return n -} - -func (m *GasInfo) Size() (n int) { - if m == nil { - return 0 + if m.GasUsed != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.GasUsed)) + i-- + dAtA[i] = 0x50 } - var l int - _ = l if m.GasWanted != 0 { - n += 1 + sovTypes(uint64(m.GasWanted)) + i = encodeVarintTypes(dAtA, i, uint64(m.GasWanted)) + i-- + dAtA[i] = 0x48 } - if m.GasUsed != 0 { - n += 1 + sovTypes(uint64(m.GasUsed)) + if len(m.Info) > 0 { + i -= len(m.Info) + copy(dAtA[i:], m.Info) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Info))) + i-- + dAtA[i] = 0x42 } - return n -} - -func (m *Result) Size() (n int) { - if m == nil { - return 0 + if len(m.Logs) > 0 { + for iNdEx := len(m.Logs) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Logs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) + if len(m.RawLog) > 0 { + i -= len(m.RawLog) + copy(dAtA[i:], m.RawLog) + i = encodeVarintTypes(dAtA, i, uint64(len(m.RawLog))) + i-- + dAtA[i] = 0x32 } - l = len(m.Log) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x2a } - if len(m.Events) > 0 { - for _, e := range m.Events { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } + if m.Code != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Code)) + i-- + dAtA[i] = 0x20 } - return n -} - -func (m *SimulationResponse) Size() (n int) { - if m == nil { + if len(m.Codespace) > 0 { + i -= len(m.Codespace) + copy(dAtA[i:], m.Codespace) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Codespace))) + i-- + dAtA[i] = 0x1a + } + if len(m.TxHash) > 0 { + i -= len(m.TxHash) + copy(dAtA[i:], m.TxHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.TxHash))) + i-- + dAtA[i] = 0x12 + } + if m.Height != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Height)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ABCIMessageLog) 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 *ABCIMessageLog) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ABCIMessageLog) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Events) > 0 { + for iNdEx := len(m.Events) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Events[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.Log) > 0 { + i -= len(m.Log) + copy(dAtA[i:], m.Log) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Log))) + i-- + dAtA[i] = 0x12 + } + if m.MsgIndex != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *StringEvent) 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 *StringEvent) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StringEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Attributes) > 0 { + for iNdEx := len(m.Attributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Attributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Type) > 0 { + i -= len(m.Type) + copy(dAtA[i:], m.Type) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Type))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *Attribute) 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 *Attribute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Attribute) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Value) > 0 { + i -= len(m.Value) + copy(dAtA[i:], m.Value) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Value))) + i-- + dAtA[i] = 0x12 + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Coin) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.Amount.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *DecCoin) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.Amount.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *IntProto) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Int.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *DecProto) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Dec.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *ValAddresses) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Addresses) > 0 { + for _, b := range m.Addresses { + l = len(b) + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *GasInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.GasWanted != 0 { + n += 1 + sovTypes(uint64(m.GasWanted)) + } + if m.GasUsed != 0 { + n += 1 + sovTypes(uint64(m.GasUsed)) + } + return n +} + +func (m *Result) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Log) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *SimulationResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.GasInfo.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.Result != nil { + l = m.Result.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *TxResponse) Size() (n int) { + if m == nil { return 0 } - var l int - _ = l - l = m.GasInfo.Size() - n += 1 + l + sovTypes(uint64(l)) - if m.Result != nil { - l = m.Result.Size() - n += 1 + l + sovTypes(uint64(l)) + var l int + _ = l + if m.Height != 0 { + n += 1 + sovTypes(uint64(m.Height)) + } + l = len(m.TxHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Codespace) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Code != 0 { + n += 1 + sovTypes(uint64(m.Code)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.RawLog) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Logs) > 0 { + for _, e := range m.Logs { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + l = len(m.Info) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.GasWanted != 0 { + n += 1 + sovTypes(uint64(m.GasWanted)) + } + if m.GasUsed != 0 { + n += 1 + sovTypes(uint64(m.GasUsed)) + } + if m.Tx != nil { + l = m.Tx.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Timestamp) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ABCIMessageLog) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MsgIndex != 0 { + n += 1 + sovTypes(uint64(m.MsgIndex)) + } + l = len(m.Log) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Events) > 0 { + for _, e := range m.Events { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *StringEvent) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Type) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if len(m.Attributes) > 0 { + for _, e := range m.Attributes { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *Attribute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Value) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *ValAddresses) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ValAddresses{`, + `Addresses:` + fmt.Sprintf("%v", this.Addresses) + `,`, + `}`, + }, "") + return s +} +func (this *ABCIMessageLog) String() string { + if this == nil { + return "nil" + } + repeatedStringForEvents := "[]StringEvent{" + for _, f := range this.Events { + repeatedStringForEvents += strings.Replace(strings.Replace(f.String(), "StringEvent", "StringEvent", 1), `&`, ``, 1) + "," + } + repeatedStringForEvents += "}" + s := strings.Join([]string{`&ABCIMessageLog{`, + `MsgIndex:` + fmt.Sprintf("%v", this.MsgIndex) + `,`, + `Log:` + fmt.Sprintf("%v", this.Log) + `,`, + `Events:` + repeatedStringForEvents + `,`, + `}`, + }, "") + return s +} +func (this *StringEvent) String() string { + if this == nil { + return "nil" + } + repeatedStringForAttributes := "[]Attribute{" + for _, f := range this.Attributes { + repeatedStringForAttributes += fmt.Sprintf("%v", f) + "," + } + repeatedStringForAttributes += "}" + s := strings.Join([]string{`&StringEvent{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Attributes:` + repeatedStringForAttributes + `,`, + `}`, + }, "") + return s +} +func valueToStringTypes(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *Coin) 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 ErrIntOverflowTypes + } + 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: Coin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Coin: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DecCoin) 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 ErrIntOverflowTypes + } + 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: DecCoin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DecCoin: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *IntProto) 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 ErrIntOverflowTypes + } + 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: IntProto: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: IntProto: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Int", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Int.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DecProto) 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 ErrIntOverflowTypes + } + 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: DecProto: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DecProto: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Dec", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Dec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF } - return n + return nil } +func (m *ValAddresses) 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 ErrIntOverflowTypes + } + 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: ValAddresses: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValAddresses: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Addresses = append(m.Addresses, make([]byte, postIndex-iNdEx)) + copy(m.Addresses[len(m.Addresses)-1], dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } -func sovTypes(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTypes(x uint64) (n int) { - return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *ValAddresses) String() string { - if this == nil { - return "nil" + if iNdEx > l { + return io.ErrUnexpectedEOF } - s := strings.Join([]string{`&ValAddresses{`, - `Addresses:` + fmt.Sprintf("%v", this.Addresses) + `,`, - `}`, - }, "") - return s + return nil } -func valueToStringTypes(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" +func (m *GasInfo) 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 ErrIntOverflowTypes + } + 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: GasInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GasInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType) + } + m.GasWanted = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasWanted |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) + } + m.GasUsed = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasUsed |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil } -func (m *Coin) Unmarshal(dAtA []byte) error { +func (m *Result) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -970,19 +2187,53 @@ func (m *Coin) Unmarshal(dAtA []byte) error { if b < 0x80 { break } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Coin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Coin: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Result: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Result: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1010,13 +2261,13 @@ func (m *Coin) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Denom = string(dAtA[iNdEx:postIndex]) + m.Log = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1026,23 +2277,23 @@ func (m *Coin) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Events = append(m.Events, types.Event{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1070,7 +2321,7 @@ func (m *Coin) Unmarshal(dAtA []byte) error { } return nil } -func (m *DecCoin) Unmarshal(dAtA []byte) error { +func (m *SimulationResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1093,17 +2344,17 @@ func (m *DecCoin) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DecCoin: wiretype end group for non-group") + return fmt.Errorf("proto: SimulationResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DecCoin: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: SimulationResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field GasInfo", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1113,29 +2364,30 @@ func (m *DecCoin) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.Denom = string(dAtA[iNdEx:postIndex]) + if err := m.GasInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1145,23 +2397,25 @@ func (m *DecCoin) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if m.Result == nil { + m.Result = &Result{} + } + if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1189,7 +2443,7 @@ func (m *DecCoin) Unmarshal(dAtA []byte) error { } return nil } -func (m *IntProto) Unmarshal(dAtA []byte) error { +func (m *TxResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1212,15 +2466,34 @@ func (m *IntProto) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: IntProto: wiretype end group for non-group") + return fmt.Errorf("proto: TxResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: IntProto: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: TxResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) + } + m.Height = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Height |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Int", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field TxHash", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1248,66 +2521,160 @@ func (m *IntProto) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Int.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + m.TxHash = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Codespace", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF } + m.Codespace = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) } - if skippy < 0 { + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - if (iNdEx + skippy) < 0 { + postIndex := iNdEx + intStringLen + if postIndex < 0 { return ErrInvalidLengthTypes } - if (iNdEx + skippy) > l { + if postIndex > l { return io.ErrUnexpectedEOF } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DecProto) 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 ErrIntOverflowTypes + m.Data = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RawLog", wireType) } - if iNdEx >= l { + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + m.RawLog = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Logs", wireType) } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DecProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DecProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Logs = append(m.Logs, ABCIMessageLog{}) + if err := m.Logs[len(m.Logs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Dec", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1335,68 +2702,87 @@ func (m *DecProto) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Dec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Info = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType) } - if skippy < 0 { + m.GasWanted = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasWanted |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) + } + m.GasUsed = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.GasUsed |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Tx", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { return ErrInvalidLengthTypes } - if (iNdEx + skippy) < 0 { + postIndex := iNdEx + msglen + if postIndex < 0 { return ErrInvalidLengthTypes } - if (iNdEx + skippy) > l { + if postIndex > l { return io.ErrUnexpectedEOF } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ValAddresses) 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 ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF + if m.Tx == nil { + m.Tx = &types1.Any{} } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ValAddresses: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ValAddresses: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + iNdEx = postIndex + case 12: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1406,23 +2792,23 @@ func (m *ValAddresses) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.Addresses = append(m.Addresses, make([]byte, postIndex-iNdEx)) - copy(m.Addresses[len(m.Addresses)-1], dAtA[iNdEx:postIndex]) + m.Timestamp = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -1448,7 +2834,7 @@ func (m *ValAddresses) Unmarshal(dAtA []byte) error { } return nil } -func (m *GasInfo) Unmarshal(dAtA []byte) error { +func (m *ABCIMessageLog) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1471,17 +2857,17 @@ func (m *GasInfo) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: GasInfo: wiretype end group for non-group") + return fmt.Errorf("proto: ABCIMessageLog: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: GasInfo: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: ABCIMessageLog: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field GasWanted", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) } - m.GasWanted = 0 + m.MsgIndex = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1491,16 +2877,16 @@ func (m *GasInfo) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.GasWanted |= uint64(b&0x7F) << shift + m.MsgIndex |= uint32(b&0x7F) << shift if b < 0x80 { break } } case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field GasUsed", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) } - m.GasUsed = 0 + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1510,11 +2896,58 @@ func (m *GasInfo) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.GasUsed |= uint64(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Log = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Events = append(m.Events, StringEvent{}) + if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTypes(dAtA[iNdEx:]) @@ -1539,7 +2972,7 @@ func (m *GasInfo) Unmarshal(dAtA []byte) error { } return nil } -func (m *Result) Unmarshal(dAtA []byte) error { +func (m *StringEvent) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1562,49 +2995,15 @@ func (m *Result) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Result: wiretype end group for non-group") + return fmt.Errorf("proto: StringEvent: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Result: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: StringEvent: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Log", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1632,11 +3031,11 @@ func (m *Result) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Log = string(dAtA[iNdEx:postIndex]) + m.Type = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -1663,8 +3062,8 @@ func (m *Result) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Events = append(m.Events, types.Event{}) - if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Attributes = append(m.Attributes, Attribute{}) + if err := m.Attributes[len(m.Attributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -1692,7 +3091,7 @@ func (m *Result) Unmarshal(dAtA []byte) error { } return nil } -func (m *SimulationResponse) Unmarshal(dAtA []byte) error { +func (m *Attribute) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1715,17 +3114,17 @@ func (m *SimulationResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: SimulationResponse: wiretype end group for non-group") + return fmt.Errorf("proto: Attribute: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: SimulationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Attribute: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GasInfo", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1735,30 +3134,29 @@ func (m *SimulationResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.GasInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Key = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1768,27 +3166,23 @@ func (m *SimulationResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - if m.Result == nil { - m.Result = &Result{} - } - if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Value = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex diff --git a/types/types.proto b/types/types.proto index c26219caa789..e1fd7ec94579 100644 --- a/types/types.proto +++ b/types/types.proto @@ -3,20 +3,21 @@ package cosmos_sdk.v1; import "third_party/proto/gogoproto/gogo.proto"; import "third_party/proto/tendermint/abci/types/types.proto"; +import "google/protobuf/any.proto"; -option go_package = "github.com/cosmos/cosmos-sdk/types"; +option go_package = "github.com/cosmos/cosmos-sdk/types"; option (gogoproto.goproto_stringer_all) = false; -option (gogoproto.stringer_all) = false; +option (gogoproto.stringer_all) = false; // Coin defines a token with a denomination and an amount. // // NOTE: The amount field is an Int which implements the custom method // signatures required by gogoproto. message Coin { - option (gogoproto.equal) = true; + option (gogoproto.equal) = true; - string denom = 1; - string amount = 2 [(gogoproto.customtype) = "Int", (gogoproto.nullable) = false]; + string denom = 1; + string amount = 2 [(gogoproto.customtype) = "Int", (gogoproto.nullable) = false]; } // DecCoin defines a token with a denomination and a decimal amount. @@ -24,57 +25,104 @@ message Coin { // NOTE: The amount field is an Dec which implements the custom method // signatures required by gogoproto. message DecCoin { - option (gogoproto.equal) = true; + option (gogoproto.equal) = true; - string denom = 1; - string amount = 2 [(gogoproto.customtype) = "Dec", (gogoproto.nullable) = false]; + string denom = 1; + string amount = 2 [(gogoproto.customtype) = "Dec", (gogoproto.nullable) = false]; } // IntProto defines a Protobuf wrapper around an Int object. message IntProto { - string int = 1 [(gogoproto.customtype) = "Int", (gogoproto.nullable) = false]; + string int = 1 [(gogoproto.customtype) = "Int", (gogoproto.nullable) = false]; } // DecProto defines a Protobuf wrapper around a Dec object. message DecProto { - string dec = 1 [(gogoproto.customtype) = "Dec", (gogoproto.nullable) = false]; + string dec = 1 [(gogoproto.customtype) = "Dec", (gogoproto.nullable) = false]; } // ValAddresses defines a repeated set of validator addresses. message ValAddresses { - option (gogoproto.stringer) = true; + option (gogoproto.stringer) = true; - repeated bytes addresses = 1 [(gogoproto.casttype) = "ValAddress"]; + repeated bytes addresses = 1 [(gogoproto.casttype) = "ValAddress"]; } // GasInfo defines tx execution gas context. message GasInfo { - // GasWanted is the maximum units of work we allow this tx to perform. - uint64 gas_wanted = 1 [(gogoproto.moretags) = "yaml:\"gas_wanted\""]; + // GasWanted is the maximum units of work we allow this tx to perform. + uint64 gas_wanted = 1 [(gogoproto.moretags) = "yaml:\"gas_wanted\""]; - // GasUsed is the amount of gas actually consumed. - uint64 gas_used = 2 [(gogoproto.moretags) = "yaml:\"gas_used\""]; + // GasUsed is the amount of gas actually consumed. + uint64 gas_used = 2 [(gogoproto.moretags) = "yaml:\"gas_used\""]; } // Result is the union of ResponseFormat and ResponseCheckTx. message Result { - option (gogoproto.goproto_getters) = false; + option (gogoproto.goproto_getters) = false; - // Data is any data returned from message or handler execution. It MUST be length - // prefixed in order to separate data from multiple message executions. - bytes data = 1; + // Data is any data returned from message or handler execution. It MUST be length + // prefixed in order to separate data from multiple message executions. + bytes data = 1; - // Log contains the log information from message or handler execution. - string log = 2; + // Log contains the log information from message or handler execution. + string log = 2; - // Events contains a slice of Event objects that were emitted during message or - // handler execution. - repeated tendermint.abci.types.Event events = 3 [(gogoproto.nullable) = false]; + // Events contains a slice of Event objects that were emitted during message or + // handler execution. + repeated tendermint.abci.types.Event events = 3 [(gogoproto.nullable) = false]; } // SimulationResponse defines the response generated when a transaction is // successfully simulated. message SimulationResponse { - GasInfo gas_info = 1 [(gogoproto.embed) = true, (gogoproto.nullable) = false]; - Result result = 2; + GasInfo gas_info = 1 [(gogoproto.embed) = true, (gogoproto.nullable) = false]; + Result result = 2; +} + +// TxResponse defines a structure containing relevant tx data and metadata. The +// tags are stringified and the log is JSON decoded. +message TxResponse { + option (gogoproto.goproto_getters) = false; + + int64 height = 1; + string txhash = 2 [(gogoproto.customname) = "TxHash"]; + string codespace = 3; + uint32 code = 4; + string data = 5; + string raw_log = 6; + repeated ABCIMessageLog logs = 7 [(gogoproto.castrepeated) = "ABCIMessageLogs", (gogoproto.nullable) = false]; + string info = 8; + int64 gas_wanted = 9; + int64 gas_used = 10; + google.protobuf.Any tx = 11; + string timestamp = 12; +} + +// ABCIMessageLog defines a structure containing an indexed tx ABCI message log. +message ABCIMessageLog { + option (gogoproto.stringer) = true; + + uint32 msg_index = 1; + string log = 2; + + // Events contains a slice of Event objects that were emitted during some + // execution. + repeated StringEvent events = 3 [(gogoproto.castrepeated) = "StringEvents", (gogoproto.nullable) = false]; +} + +// StringAttribute defines en Event object wrapper where all the attributes +// contain key/value pairs that are strings instead of raw bytes. +message StringEvent { + option (gogoproto.stringer) = true; + + string type = 1; + repeated Attribute attributes = 2 [(gogoproto.nullable) = false]; +} + +// Attribute defines an attribute wrapper where the key and value are +// strings instead of raw bytes. +message Attribute { + string key = 1; + string value = 2; } diff --git a/x/auth/alias.go b/x/auth/alias.go index 036100bf885a..9aa937665c98 100644 --- a/x/auth/alias.go +++ b/x/auth/alias.go @@ -22,7 +22,6 @@ const ( DefaultSigVerifyCostSecp256k1 = types.DefaultSigVerifyCostSecp256k1 QueryAccount = types.QueryAccount QueryParams = types.QueryParams - MaxGasWanted = types.MaxGasWanted Minter = types.Minter Burner = types.Burner Staking = types.Staking diff --git a/x/auth/ante/ante.go b/x/auth/ante/ante.go index ab9e804b958f..30e0072178bb 100644 --- a/x/auth/ante/ante.go +++ b/x/auth/ante/ante.go @@ -2,6 +2,7 @@ package ante import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/types" ibcante "github.com/cosmos/cosmos-sdk/x/ibc/ante" ibckeeper "github.com/cosmos/cosmos-sdk/x/ibc/keeper" @@ -29,3 +30,26 @@ func NewAnteHandler( ibcante.NewProofVerificationDecorator(ibcKeeper.ClientKeeper, ibcKeeper.ChannelKeeper), // innermost AnteDecorator ) } + +// NewProtoAnteHandler returns an AnteHandler that checks and increments sequence +// numbers, checks signatures & account numbers, and deducts fees from the first +// signer for the protobuf Tx format. +func NewProtoAnteHandler( + ak AccountKeeper, bankKeeper types.BankKeeper, ibcKeeper ibckeeper.Keeper, + sigGasConsumer SignatureVerificationGasConsumer, +) sdk.AnteHandler { + return sdk.ChainAnteDecorators( + NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first + NewMempoolFeeDecorator(), + NewValidateBasicDecorator(), + NewValidateMemoDecorator(ak), + NewConsumeGasForTxSizeDecorator(ak), + NewSetPubKeyDecorator(ak), // SetPubKeyDecorator must be called before all signature verification decorators + NewValidateSigCountDecorator(ak), + NewDeductFeeDecorator(ak, bankKeeper), + NewSigGasConsumeDecorator(ak, sigGasConsumer), + NewProtoSigVerificationDecorator(ak, signing.DefaultSignModeHandler()), + NewIncrementSequenceDecorator(ak), + ibcante.NewProofVerificationDecorator(ibcKeeper.ClientKeeper, ibcKeeper.ChannelKeeper), // innermost AnteDecorator + ) +} diff --git a/x/auth/ante/basic.go b/x/auth/ante/basic.go index b1ed1e8d3691..f55b79d4a67c 100644 --- a/x/auth/ante/basic.go +++ b/x/auth/ante/basic.go @@ -7,11 +7,19 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/multisig" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + types3 "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( - _ TxWithMemo = (*types.StdTx)(nil) // assert StdTx implements TxWithMemo + _ types3.TxWithMemo = (*types.StdTx)(nil) // assert StdTx implements TxWithMemo ) // ValidateBasicDecorator will call tx.ValidateBasic and return any non-nil error. @@ -37,12 +45,6 @@ func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulat return next(ctx, tx, simulate) } -// Tx must have GetMemo() method to use ValidateMemoDecorator -type TxWithMemo interface { - sdk.Tx - GetMemo() string -} - // ValidateMemoDecorator will validate memo given the parameters passed in // If memo is too large decorator returns with error, otherwise call next AnteHandler // CONTRACT: Tx must implement TxWithMemo interface @@ -57,7 +59,7 @@ func NewValidateMemoDecorator(ak AccountKeeper) ValidateMemoDecorator { } func (vmd ValidateMemoDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - memoTx, ok := tx.(TxWithMemo) + memoTx, ok := tx.(types3.TxWithMemo) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") } @@ -95,7 +97,7 @@ func NewConsumeGasForTxSizeDecorator(ak AccountKeeper) ConsumeTxSizeGasDecorator } func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - sigTx, ok := tx.(SigVerifiableTx) + sigTx, ok := tx.(types3.SigTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid tx type") } diff --git a/x/auth/ante/fee.go b/x/auth/ante/fee.go index 900caf18d578..2fc6f1317c9e 100644 --- a/x/auth/ante/fee.go +++ b/x/auth/ante/fee.go @@ -5,21 +5,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( - _ FeeTx = (*types.StdTx)(nil) // assert StdTx implements FeeTx + _ txtypes.FeeTx = (*types.StdTx)(nil) // assert StdTx implements FeeTx ) -// FeeTx defines the interface to be implemented by Tx to use the FeeDecorators -type FeeTx interface { - sdk.Tx - GetGas() uint64 - GetFee() sdk.Coins - FeePayer() sdk.AccAddress -} - // MempoolFeeDecorator will check if the transaction's fee is at least as large // as the local validator's minimum gasFee (defined in validator config). // If fee is too low, decorator returns error and tx is rejected from mempool. @@ -33,7 +26,7 @@ func NewMempoolFeeDecorator() MempoolFeeDecorator { } func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { - feeTx, ok := tx.(FeeTx) + feeTx, ok := tx.(txtypes.FeeTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx") } @@ -82,7 +75,7 @@ func NewDeductFeeDecorator(ak AccountKeeper, bk types.BankKeeper) DeductFeeDecor } func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { - feeTx, ok := tx.(FeeTx) + feeTx, ok := tx.(txtypes.FeeTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx") } diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 762d53f8c7c0..e45176e06c67 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -3,6 +3,11 @@ package ante import ( "bytes" "encoding/hex" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" + + types3 "github.com/cosmos/cosmos-sdk/types/tx" + + types2 "github.com/cosmos/cosmos-sdk/x/auth/ante/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" @@ -20,7 +25,7 @@ var ( simSecp256k1Pubkey secp256k1.PubKeySecp256k1 simSecp256k1Sig [64]byte - _ SigVerifiableTx = (*types.StdTx)(nil) // assert StdTx implements SigVerifiableTx + _ types2.SigVerifiableTx = (*types.StdTx)(nil) // assert StdTx implements SigVerifiableTx ) func init() { @@ -34,15 +39,6 @@ func init() { // This is where apps can define their own PubKey type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params) error -// SigVerifiableTx defines a Tx interface for all signature verification decorators -type SigVerifiableTx interface { - sdk.Tx - GetSignatures() [][]byte - GetSigners() []sdk.AccAddress - GetPubKeys() []crypto.PubKey // If signer already has pubkey in context, this list will have nil in its place - GetSignBytes(ctx sdk.Context, acc types.AccountI) []byte -} - // SetPubKeyDecorator sets PubKeys in context for any signer which does not already have pubkey set // PubKeys must be set in context for all signers before any other sigverify decorators run // CONTRACT: Tx must implement SigVerifiableTx interface @@ -57,7 +53,7 @@ func NewSetPubKeyDecorator(ak AccountKeeper) SetPubKeyDecorator { } func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - sigTx, ok := tx.(SigVerifiableTx) + sigTx, ok := tx.(types3.SigTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid tx type") } @@ -114,7 +110,7 @@ func NewSigGasConsumeDecorator(ak AccountKeeper, sigGasConsumer SignatureVerific } func (sgcd SigGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { - sigTx, ok := tx.(SigVerifiableTx) + sigTx, ok := tx.(types3.SigTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") } @@ -171,7 +167,7 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul if ctx.IsReCheckTx() { return next(ctx, tx, simulate) } - sigTx, ok := tx.(SigVerifiableTx) + sigTx, ok := tx.(types2.SigVerifiableTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") } @@ -236,7 +232,7 @@ func NewIncrementSequenceDecorator(ak AccountKeeper) IncrementSequenceDecorator } func (isd IncrementSequenceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - sigTx, ok := tx.(SigVerifiableTx) + sigTx, ok := tx.(types3.SigTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") } @@ -269,7 +265,7 @@ func NewValidateSigCountDecorator(ak AccountKeeper) ValidateSigCountDecorator { } func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - sigTx, ok := tx.(SigVerifiableTx) + sigTx, ok := tx.(types3.SigTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a sigTx") } diff --git a/x/auth/ante/sigverify_proto.go b/x/auth/ante/sigverify_proto.go new file mode 100644 index 000000000000..e3dd7b2a3b13 --- /dev/null +++ b/x/auth/ante/sigverify_proto.go @@ -0,0 +1,83 @@ +package ante + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + types "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + auth "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +type ProtoSigVerificationDecorator struct { + ak AccountKeeper + handler types.SignModeHandler +} + +func NewProtoSigVerificationDecorator(ak AccountKeeper, signModeHandler types.SignModeHandler) ProtoSigVerificationDecorator { + return ProtoSigVerificationDecorator{ + ak: ak, + handler: signModeHandler, + } +} + +func (svd ProtoSigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + // no need to verify signatures on recheck tx + if ctx.IsReCheckTx() { + return next(ctx, tx, simulate) + } + sigTx, ok := tx.(types.ProtoTx) + if !ok { + return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") + } + + // stdSigs contains the sequence number, account number, and signatures. + // When simulating, this would just be a 0-length slice. + sigs, err := sigTx.GetSignatureData() + if err != nil { + return ctx, err + } + + // stdSigs contains the sequence number, account number, and signatures. + // When simulating, this would just be a 0-length slice. + signerAddrs := sigTx.GetSigners() + signerAccs := make([]auth.AccountI, len(signerAddrs)) + + // check that signer length and signature length are the same + if len(sigs) != len(signerAddrs) { + return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "invalid number of signer; expected: %d, got %d", len(signerAddrs), len(sigs)) + } + + for i, sig := range sigs { + signerAcc, err := GetSignerAcc(ctx, svd.ak, signerAddrs[i]) + if err != nil { + return ctx, err + } + + signerAccs[i] = signerAcc + + // retrieve pubkey + pubKey := signerAccs[i].GetPubKey() + if !simulate && pubKey == nil { + return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, "pubkey on account is not set") + } + + genesis := ctx.BlockHeight() == 0 + var accNum uint64 + if !genesis { + accNum = signerAcc.GetAccountNumber() + } + + data := types.SigningData{ + PublicKey: signerAcc.GetPubKey(), + ChainID: ctx.ChainID(), + AccountNumber: accNum, + AccountSequence: signerAcc.GetSequence(), + } + + if !signing.VerifySignature(data, sig, tx, svd.handler) { + return ctx, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "signature verification failed; verify correct account sequence and chain-id") + } + } + + return next(ctx, tx, simulate) +} diff --git a/x/auth/ante/types/types.go b/x/auth/ante/types/types.go new file mode 100644 index 000000000000..29150f6ca7b0 --- /dev/null +++ b/x/auth/ante/types/types.go @@ -0,0 +1,15 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" + types2 "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// SigVerifiableTx defines a Tx interface for all signature verification decorators +type SigVerifiableTx interface { + types.Tx + txtypes.SigTx + GetSignBytes(ctx types.Context, acc types2.AccountI) []byte +} + diff --git a/x/auth/client/cli/broadcast.go b/x/auth/client/cli/broadcast.go index 9e24d63e5a38..7f6ff6b8914c 100644 --- a/x/auth/client/cli/broadcast.go +++ b/x/auth/client/cli/broadcast.go @@ -4,16 +4,16 @@ import ( "errors" "strings" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) // GetBroadcastCommand returns the tx broadcast command. -func GetBroadcastCommand(cdc *codec.Codec) *cobra.Command { +func GetBroadcastCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "broadcast [file_path]", Short: "Broadcast transactions generated offline", @@ -26,18 +26,18 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.NewContext().WithCodec(cdc) + clientCtx = clientCtx.Init() if clientCtx.Offline { return errors.New("cannot broadcast tx during offline mode") } - stdTx, err := authclient.ReadStdTxFromFile(clientCtx.Codec, args[0]) + stdTx, err := authclient.ReadTxFromFile(clientCtx, args[0]) if err != nil { return err } - txBytes, err := clientCtx.Codec.MarshalBinaryBare(stdTx) + txBytes, err := clientCtx.TxGenerator.TxEncoder()(stdTx) if err != nil { return err } diff --git a/x/auth/client/cli/broadcast_test.go b/x/auth/client/cli/broadcast_test.go index 11d41df89e51..2aa881bb0bcc 100644 --- a/x/auth/client/cli/broadcast_test.go +++ b/x/auth/client/cli/broadcast_test.go @@ -5,17 +5,20 @@ import ( "path/filepath" "testing" + "github.com/cosmos/cosmos-sdk/client" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/spf13/viper" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/tests" ) func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { - cdc := codec.New() - cmd := GetBroadcastCommand(cdc) + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + cmd := GetBroadcastCommand(clientCtx) viper.Set(flags.FlagOffline, true) @@ -24,8 +27,9 @@ func TestGetBroadcastCommand_OfflineFlag(t *testing.T) { } func TestGetBroadcastCommand_WithoutOfflineFlag(t *testing.T) { - cdc := codec.New() - cmd := GetBroadcastCommand(cdc) + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator) + cmd := GetBroadcastCommand(clientCtx) viper.Set(flags.FlagOffline, false) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index b831ee348a72..9c5cdd106a82 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -45,9 +45,9 @@ func TestCLIValidateSignatures(t *testing.T) { success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) require.True(t, success) - stdTx := cli.UnmarshalStdTx(t, f.Cdc, stdout) + stdTx := f.UnmarshalTxJSON(stdout) - require.Equal(t, len(stdTx.Msgs), 1) + require.Equal(t, len(stdTx.GetMsgs()), 1) require.Equal(t, 1, len(stdTx.GetSignatures())) require.Equal(t, fooAddr.String(), stdTx.GetSigners()[0].String()) @@ -60,8 +60,8 @@ func TestCLIValidateSignatures(t *testing.T) { require.True(t, success) // modify the transaction - stdTx.Memo = "MODIFIED-ORIGINAL-TX-BAD" - bz := cli.MarshalStdTx(t, f.Cdc, stdTx) + stdTx.SetMemo("MODIFIED-ORIGINAL-TX-BAD") + bz := f.MarshalTx(stdTx) modSignedTxFile, cleanup := tests.WriteToNewTempFile(t, string(bz)) t.Cleanup(cleanup) @@ -140,9 +140,9 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { success, stdout, stderr := bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--generate-only") require.True(t, success) require.Empty(t, stderr) - msg := cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, msg.Fee.Gas, uint64(flags.DefaultGasLimit)) - require.Equal(t, len(msg.Msgs), 1) + msg := f.UnmarshalTxJSON(stdout) + require.Equal(t, msg.GetGas(), uint64(flags.DefaultGasLimit)) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Test generate sendTx with --gas=$amount @@ -150,18 +150,18 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { require.True(t, success) require.Empty(t, stderr) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, msg.Fee.Gas, uint64(100)) - require.Equal(t, len(msg.Msgs), 1) + msg = f.UnmarshalTxJSON(stdout) + require.Equal(t, msg.GetGas(), uint64(100)) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Test generate sendTx, estimate gas success, stdout, stderr = bankcli.TxSend(f, fooAddr.String(), barAddr, sdk.NewCoin(cli.Denom, sendTokens), "--generate-only") require.True(t, success) require.Empty(t, stderr) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.True(t, msg.Fee.Gas > 0) - require.Equal(t, len(msg.Msgs), 1) + msg = f.UnmarshalTxJSON(stdout) + require.True(t, msg.GetGas() > 0) + require.Equal(t, len(msg.GetMsgs()), 1) // Write the output to disk unsignedTxFile, cleanup := tests.WriteToNewTempFile(t, stdout) @@ -186,8 +186,8 @@ func TestCLISendGenerateSignAndBroadcast(t *testing.T) { // Sign transaction success, stdout, _ = testutil.TxSign(f, cli.KeyFoo, unsignedTxFile.Name()) require.True(t, success) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.Equal(t, len(msg.Msgs), 1) + msg = f.UnmarshalTxJSON(stdout) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 1, len(msg.GetSignatures())) require.Equal(t, fooAddr.String(), msg.GetSigners()[0].String()) @@ -309,7 +309,7 @@ func TestCLIEncode(t *testing.T) { // Check that the transaction decodes as epxceted var decodedTx auth.StdTx - require.Nil(t, f.Cdc.UnmarshalBinaryBare(decodedBytes, &decodedTx)) + require.Nil(t, f.Amino.UnmarshalBinaryBare(decodedBytes, &decodedTx)) require.Equal(t, "deadbeef", decodedTx.Memo) } diff --git a/x/auth/client/cli/decode.go b/x/auth/client/cli/decode.go index efd124921b52..2fde4790a39c 100644 --- a/x/auth/client/cli/decode.go +++ b/x/auth/client/cli/decode.go @@ -9,29 +9,27 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) const flagHex = "hex" -// GetDecodeCommand returns the decode command to take Amino-serialized bytes +// GetDecodeCommand returns the decode command to take serialized bytes // and turn it into a JSONified transaction. -func GetDecodeCommand(codec *codec.Codec) *cobra.Command { +func GetDecodeCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "decode [amino-byte-string]", - Short: "Decode an amino-encoded transaction string.", + Short: "Decode an binary encoded transaction string.", Args: cobra.ExactArgs(1), - RunE: runDecodeTxString(codec), + RunE: runDecodeTxString(clientCtx), } cmd.Flags().BoolP(flagHex, "x", false, "Treat input as hexadecimal instead of base64") return flags.PostCommands(cmd)[0] } -func runDecodeTxString(codec *codec.Codec) func(cmd *cobra.Command, args []string) (err error) { +func runDecodeTxString(clientCtx client.Context) func(cmd *cobra.Command, args []string) (err error) { return func(cmd *cobra.Command, args []string) (err error) { - clientCtx := client.NewContext().WithCodec(codec).WithOutput(cmd.OutOrStdout()) + clientCtx = clientCtx.Init().WithOutput(cmd.OutOrStdout()) var txBytes []byte if viper.GetBool(flagHex) { @@ -43,12 +41,11 @@ func runDecodeTxString(codec *codec.Codec) func(cmd *cobra.Command, args []strin return err } - var stdTx authtypes.StdTx - err = clientCtx.Codec.UnmarshalBinaryBare(txBytes, &stdTx) + tx, err := clientCtx.TxGenerator.TxDecoder()(txBytes) if err != nil { return err } - return clientCtx.PrintOutput(stdTx) + return clientCtx.PrintOutput(tx) } } diff --git a/x/auth/client/cli/encode.go b/x/auth/client/cli/encode.go index c97533c859ef..653f8b389a1a 100644 --- a/x/auth/client/cli/encode.go +++ b/x/auth/client/cli/encode.go @@ -7,7 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" ) @@ -20,7 +19,7 @@ func (txr txEncodeRespStr) String() string { // GetEncodeCommand returns the encode command to take a JSONified transaction and turn it into // Amino-serialized bytes -func GetEncodeCommand(cdc *codec.Codec) *cobra.Command { +func GetEncodeCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "encode [file]", Short: "Encode transactions generated offline", @@ -29,15 +28,15 @@ Read a transaction from , serialize it to the Amino wire protocol, and out If you supply a dash (-) argument in place of an input filename, the command reads from standard input.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx := client.NewContext().WithCodec(cdc) + cliCtx := clientCtx.Init() - stdTx, err := authclient.ReadStdTxFromFile(clientCtx.Codec, args[0]) + tx, err := authclient.ReadTxFromFile(cliCtx, args[0]) if err != nil { return } - // re-encode it via the Amino wire protocol - txBytes, err := clientCtx.Codec.MarshalBinaryBare(stdTx) + // re-encode it + txBytes, err := cliCtx.TxGenerator.TxEncoder()(tx) if err != nil { return err } diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go index 132d61ed3080..601c04e49408 100644 --- a/x/auth/client/cli/tx.go +++ b/x/auth/client/cli/tx.go @@ -4,12 +4,11 @@ import ( "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { +func GetTxCmd(ctx client.Context) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Auth transaction subcommands", @@ -18,9 +17,9 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command { RunE: client.ValidateCmd, } txCmd.AddCommand( - GetMultiSignCommand(cdc), - GetSignCommand(cdc), - GetValidateSignaturesCommand(cdc), + GetMultiSignCommand(ctx), + GetSignCommand(ctx), + GetValidateSignaturesCommand(ctx), GetSignBatchCommand(cdc), ) return txCmd diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 58002e4a1244..1a98a9f3accf 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -3,16 +3,20 @@ package cli import ( "bufio" "fmt" - "io/ioutil" "os" "strings" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/codec" + types2 "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,7 +26,7 @@ import ( ) // GetSignCommand returns the sign command -func GetMultiSignCommand(cdc *codec.Codec) *cobra.Command { +func GetMultiSignCommand(ctx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "multisign [file] [name] [[signature]...]", Short: "Generate multisig signatures for transactions generated offline", @@ -45,7 +49,7 @@ recommended to set such parameters manually. version.ClientName, ), ), - RunE: makeMultiSignCmd(cdc), + RunE: makeMultiSignCmd(ctx), Args: cobra.MinimumNArgs(3), } @@ -56,9 +60,9 @@ recommended to set such parameters manually. return flags.PostCommands(cmd)[0] } -func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeMultiSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) (err error) { - stdTx, err := authclient.ReadStdTxFromFile(cdc, args[0]) + stdTx, err := authclient.ReadTxFromFile(clientCtx, args[0]) if err != nil { return } @@ -78,10 +82,10 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) return fmt.Errorf("%q must be of type %s: %s", args[1], keyring.TypeMulti, multisigInfo.GetType()) } - multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) - multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) - clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) - txBldr := types.NewTxBuilderFromCLI(inBuf) + multisigPub := multisigInfo.GetPubKey().(multisig.MultisigPubKey) + multisigSig := multisig.NewMultisig(len(multisigPub.GetPubKeys())) + clientCtx := clientCtx.InitWithInput(inBuf) + txFactory := tx.NewFactoryFromCLI(inBuf) if !clientCtx.Offline { accnum, seq, err := types.NewAccountRetriever(authclient.Codec).GetAccountNumberSequence(clientCtx, multisigInfo.GetAddress()) @@ -89,43 +93,70 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) return err } - txBldr = txBldr.WithAccountNumber(accnum).WithSequence(seq) + txFactory = txFactory.WithAccountNumber(accnum).WithSequence(seq) + } + + feeTx := stdTx.(types2.FeeTx) + fee := types.StdFee{ + Amount: feeTx.GetFee(), + Gas: feeTx.GetGas(), } + memoTx := stdTx.(types2.TxWithMemo) + // read each signature and add it to the multisig if valid for i := 2; i < len(args); i++ { - stdSig, err := readAndUnmarshalStdSignature(cdc, args[i]) + stdSig, err := readAndUnmarshalStdSignature(clientCtx, args[i]) if err != nil { return err } + signingData := types2.SigningData{ + PublicKey: stdSig.PubKey, + ChainID: txFactory.ChainID(), + AccountNumber: txFactory.AccountNumber(), + AccountSequence: txFactory.Sequence(), + } + // Validate each signature - sigBytes := types.StdSignBytes( - txBldr.ChainID(), txBldr.AccountNumber(), txBldr.Sequence(), - stdTx.Fee, stdTx.GetMsgs(), stdTx.GetMemo(), - ) - if ok := stdSig.GetPubKey().VerifyBytes(sigBytes, stdSig.Signature); !ok { + if ok := signing.VerifySignature(signingData, stdSig.Data, stdTx, clientCtx.TxGenerator.SignModeHandler()); !ok { return fmt.Errorf("couldn't verify signature") } - if err := multisigSig.AddSignatureFromPubKey(stdSig.Signature, stdSig.GetPubKey(), multisigPub.PubKeys); err != nil { + if err := multisig.AddSignatureFromPubKey(multisigSig, stdSig.Data, stdSig.PubKey, multisigPub.GetPubKeys()); err != nil { return err } } - newStdSig := types.StdSignature{Signature: cdc.MustMarshalBinaryBare(multisigSig), PubKey: multisigPub.Bytes()} //nolint:staticcheck - newTx := types.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, []types.StdSignature{newStdSig}, stdTx.GetMemo()) //nolint:staticcheck + newStdSig := types.StdSignature{Signature: clientCtx.Codec.MustMarshalBinaryBare(multisigSig), PubKey: multisigPub.Bytes()} //nolint:staticcheck + newTx := types.NewStdTx(stdTx.GetMsgs(), fee, []types.StdSignature{newStdSig}, memoTx.GetMemo()) //nolint:staticcheck + + txBldr, err := clientCtx.TxGenerator.WrapTxBuilder(stdTx) + if err != nil { + return err + } + + sigBldr := client.SignatureBuilder{ + PubKey: multisigPub, + Data: multisigSig, + } + + err = txBldr.SetSignatures(sigBldr) + + if err != nil { + return err + } sigOnly := viper.GetBool(flagSigOnly) var json []byte switch { case sigOnly && clientCtx.Indent: - json, err = cdc.MarshalJSONIndent(newTx.Signatures[0], "", " ") + json, err = getSignatureBuilderJSON(clientCtx.JSONMarshaler, sigBldr, true) case sigOnly && !clientCtx.Indent: - json, err = cdc.MarshalJSON(newTx.Signatures[0]) + json, err = getSignatureBuilderJSON(clientCtx.JSONMarshaler, sigBldr, false) case !sigOnly && clientCtx.Indent: - json, err = cdc.MarshalJSONIndent(newTx, "", " ") + json, err = codec.MarshalJSONIndent(clientCtx.JSONMarshaler, newTx) default: - json, err = cdc.MarshalJSON(newTx) + json, err = clientCtx.JSONMarshaler.MarshalJSON(newTx) } if err != nil { return err @@ -150,13 +181,14 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) } } -func readAndUnmarshalStdSignature(cdc *codec.Codec, filename string) (stdSig types.StdSignature, err error) { //nolint:staticcheck - var bytes []byte - if bytes, err = ioutil.ReadFile(filename); err != nil { - return - } - if err = cdc.UnmarshalJSON(bytes, &stdSig); err != nil { - return - } - return +func readAndUnmarshalStdSignature(clientCtx client.Context, filename string) (stdSig client.SignatureBuilder, err error) { //nolint:staticcheck + //var bytes []byte + //if bytes, err = ioutil.ReadFile(filename); err != nil { + // return + //} + //if err = clientCtx.JSONMarshaler.UnmarshalJSON(bytes, &stdSig); err != nil { + // return + //} + //return + panic("TODO: json signatures") } diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index dbeabf05600a..87c814168830 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -8,6 +8,11 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + sdk "github.com/cosmos/cosmos-sdk/types" + types2 "github.com/cosmos/cosmos-sdk/types/tx" + client2 "github.com/cosmos/cosmos-sdk/x/auth/client" + + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" @@ -150,7 +155,7 @@ func setOutputFile(cmd *cobra.Command) (func(), error) { } // GetSignCommand returns the transaction sign command. -func GetSignCommand(codec *codec.Codec) *cobra.Command { +func GetSignCommand(ctx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "sign [file]", Short: "Sign transactions generated offline", @@ -170,7 +175,7 @@ key. It implies --signature-only. Full multisig signed transactions may eventual be generated via the 'multisign' command. `, PreRun: preSignCmd, - RunE: makeSignCmd(codec), + RunE: makeSignCmd(ctx), Args: cobra.ExactArgs(1), } @@ -199,18 +204,22 @@ func preSignCmd(cmd *cobra.Command, _ []string) { } } -func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeSignCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - clientCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) + clientCtx, txFactory, tx, err := readTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { return err } - + // // if --signature-only is on, then override --append - var newTx types.StdTx generateSignatureOnly := viper.GetBool(flagSigOnly) multisigAddrStr := viper.GetString(flagMultisig) + txBldr, err := clientCtx.TxGenerator.WrapTxBuilder(tx) + if err != nil { + return err + } + if multisigAddrStr != "" { var multisigAddr sdk.AccAddress @@ -218,20 +227,22 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error if err != nil { return err } - newTx, err = authclient.SignStdTxWithSignerAddress( - txBldr, clientCtx, multisigAddr, clientCtx.GetFromName(), stdTx, clientCtx.Offline, + + err = client2.SignStdTxWithSignerAddress( + txFactory, clientCtx, multisigAddr, clientCtx.GetFromName(), txBldr, clientCtx.Offline, ) + generateSignatureOnly = true } else { appendSig := viper.GetBool(flagAppend) && !generateSignatureOnly - newTx, err = authclient.SignStdTx(txBldr, clientCtx, clientCtx.GetFromName(), stdTx, appendSig, clientCtx.Offline) + err = client2.SignStdTx(txFactory, clientCtx, clientCtx.GetFromName(), txBldr, appendSig, clientCtx.Offline) } if err != nil { return err } - json, err := getSignatureJSON(cdc, newTx, clientCtx.Indent, generateSignatureOnly) + json, err := getSignatureJSON(clientCtx.JSONMarshaler, txBldr.GetTx(), clientCtx.Indent, generateSignatureOnly) if err != nil { return err } @@ -255,23 +266,32 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error } } -func getSignatureJSON(cdc *codec.Codec, newTx types.StdTx, indent, generateSignatureOnly bool) ([]byte, error) { +func getSignatureJSON(cdc codec.JSONMarshaler, newTx types2.SigTx, indent, generateSignatureOnly bool) ([]byte, error) { switch generateSignatureOnly { case true: - switch indent { - case true: - return cdc.MarshalJSONIndent(newTx.Signatures[0], "", " ") - - default: - return cdc.MarshalJSON(newTx.Signatures[0]) + sigData, err := newTx.GetSignatureData() + pubKeys := newTx.GetPubKeys() + if err != nil { + return nil, err } - default: - switch indent { - case true: - return cdc.MarshalJSONIndent(newTx, "", " ") - default: - return cdc.MarshalJSON(newTx) - } + return getSignatureBuilderJSON(cdc, client.SignatureBuilder{ + PubKey: pubKeys[0], + Data: sigData[0], + }, indent) + + default: + panic("TODO") + //switch indent { + //case true: + // return codec.MarshalJSONIndent(cdc, newTx) + // + //default: + // return cdc.MarshalJSON(newTx) + //} } } + +func getSignatureBuilderJSON(cdc codec.JSONMarshaler, sigBuilder client.SignatureBuilder, indent bool) ([]byte, error) { + panic("TODO: getSignatureBuilderJSON") +} diff --git a/x/auth/client/cli/validate_sigs.go b/x/auth/client/cli/validate_sigs.go index 7782021a78bf..1400d5a2f758 100644 --- a/x/auth/client/cli/validate_sigs.go +++ b/x/auth/client/cli/validate_sigs.go @@ -7,16 +7,18 @@ import ( "github.com/spf13/cobra" + multisig2 "github.com/cosmos/cosmos-sdk/crypto/multisig" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" authclient "github.com/cosmos/cosmos-sdk/x/auth/client" - "github.com/cosmos/cosmos-sdk/x/auth/types" ) -func GetValidateSignaturesCommand(codec *codec.Codec) *cobra.Command { +func GetValidateSignaturesCommand(clientCtx client.Context) *cobra.Command { cmd := &cobra.Command{ Use: "validate-signatures [file]", Short: "Validate transactions signatures", @@ -29,16 +31,16 @@ given transaction. If the --offline flag is also set, signature validation over transaction will be not be performed as that will require RPC communication with a full node. `, PreRun: preSignCmd, - RunE: makeValidateSignaturesCmd(codec), + RunE: makeValidateSignaturesCmd(clientCtx), Args: cobra.ExactArgs(1), } return flags.PostCommands(cmd)[0] } -func makeValidateSignaturesCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { +func makeValidateSignaturesCmd(clientCtx client.Context) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - clientCtx, txBldr, stdTx, err := readStdTxAndInitContexts(cdc, cmd, args[0]) + clientCtx, txBldr, stdTx, err := readTxAndInitContexts(clientCtx, cmd, args[0]) if err != nil { return err } @@ -55,17 +57,24 @@ func makeValidateSignaturesCmd(cdc *codec.Codec) func(cmd *cobra.Command, args [ // expected signers. In addition, if offline has not been supplied, the signature is // verified over the transaction sign bytes. Returns false if the validation fails. func printAndValidateSigs( - cmd *cobra.Command, clientCtx client.Context, chainID string, stdTx types.StdTx, offline bool, + cmd *cobra.Command, clientCtx client.Context, chainID string, tx sdk.Tx, offline bool, ) bool { + sigTx := tx.(txtypes.SigTx) + signModeHandler := clientCtx.TxGenerator.SignModeHandler() + cmd.Println("Signers:") - signers := stdTx.GetSigners() + signers := sigTx.GetSigners() for i, signer := range signers { cmd.Printf(" %v: %v\n", i, signer.String()) } success := true - sigs := stdTx.Signatures + sigs, err := sigTx.GetSignatureData() + if err != nil { + panic(err) + } + pubKeys := sigTx.GetPubKeys() cmd.Println("") cmd.Println("Signatures:") @@ -75,9 +84,10 @@ func printAndValidateSigs( for i, sig := range sigs { var ( + pubKey = pubKeys[i] multiSigHeader string multiSigMsg string - sigAddr = sdk.AccAddress(sig.GetPubKey().Address()) + sigAddr = sdk.AccAddress(pubKey.Address()) sigSanity = "OK" ) @@ -89,43 +99,65 @@ func printAndValidateSigs( // Validate the actual signature over the transaction bytes since we can // reach out to a full node to query accounts. if !offline && success { - acc, err := types.NewAccountRetriever(authclient.Codec).GetAccount(clientCtx, sigAddr) + accNum, accSeq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, sigAddr) if err != nil { cmd.Printf("failed to get account: %s\n", sigAddr) return false } - sigBytes := types.StdSignBytes( - chainID, acc.GetAccountNumber(), acc.GetSequence(), - stdTx.Fee, stdTx.GetMsgs(), stdTx.GetMemo(), - ) - - if ok := sig.GetPubKey().VerifyBytes(sigBytes, sig.Signature); !ok { - sigSanity = "ERROR: signature invalid" - success = false + signingData := txtypes.SigningData{ + PublicKey: pubKey, + ChainID: chainID, + AccountNumber: accNum, + AccountSequence: accSeq, } - } - multiPK, ok := sig.GetPubKey().(multisig.PubKeyMultisigThreshold) - if ok { - var multiSig multisig.Multisignature - clientCtx.Codec.MustUnmarshalBinaryBare(sig.Signature, &multiSig) - - var b strings.Builder - b.WriteString("\n MultiSig Signatures:\n") + switch sig := sig.(type) { + case *txtypes.SingleSignatureData: + sigBytes, err := signModeHandler.GetSignBytes(sig.SignMode, signingData, tx) + if err != nil { + sigSanity = "ERROR: can't get sign bytes" + success = false + } - for i := 0; i < multiSig.BitArray.Size(); i++ { - if multiSig.BitArray.GetIndex(i) { - addr := sdk.AccAddress(multiPK.PubKeys[i].Address().Bytes()) - b.WriteString(fmt.Sprintf(" %d: %s (weight: %d)\n", i, addr, 1)) + if ok := pubKey.VerifyBytes(sigBytes, sig.Signature); !ok { + sigSanity = "ERROR: signature invalid" + success = false + } + case *txtypes.MultiSignatureData: + multiPK, ok := pubKey.(multisig2.MultisigPubKey) + if ok { + if !multiPK.VerifyMultisignature(func(mode txtypes.SignMode) ([]byte, error) { + signingData.Mode = mode + return signModeHandler.GetSignBytes(mode, signingData, tx) + }, sig) { + sigSanity = "ERROR: signature invalid" + success = false + } + + var b strings.Builder + b.WriteString("\n MultiSig Signatures:\n") + + pks := multiPK.GetPubKeys() + for i := 0; i < sig.BitArray.Size(); i++ { + if sig.BitArray.GetIndex(i) { + addr := sdk.AccAddress(pks[i].Address().Bytes()) + b.WriteString(fmt.Sprintf(" %d: %s (weight: %d)\n", i, addr, 1)) + } + } + + multiSigHeader = fmt.Sprintf(" [multisig threshold: %d/%d]", multiPK.Threshold(), len(pks)) + multiSigMsg = b.String() + cmd.Printf(" %d: %s\t\t\t[%s]%s%s\n", i, sigAddr.String(), sigSanity, multiSigHeader, multiSigMsg) + } else { + sigSanity = "ERROR: expected multisig pub key" + success = false } + default: + sigSanity = "ERROR: unexpected ModeInfo" + success = false } - - multiSigHeader = fmt.Sprintf(" [multisig threshold: %d/%d]", multiPK.K, len(multiPK.PubKeys)) - multiSigMsg = b.String() } - - cmd.Printf(" %d: %s\t\t\t[%s]%s%s\n", i, sigAddr.String(), sigSanity, multiSigHeader, multiSigMsg) } cmd.Println("") @@ -133,17 +165,15 @@ func printAndValidateSigs( return success } -func readStdTxAndInitContexts(cdc *codec.Codec, cmd *cobra.Command, filename string) ( - client.Context, types.TxBuilder, types.StdTx, error, -) { - stdTx, err := authclient.ReadStdTxFromFile(cdc, filename) +func readTxAndInitContexts(clientCtx client.Context, cmd *cobra.Command, filename string) (client.Context, tx.Factory, sdk.Tx, error) { + stdTx, err := authclient.ReadTxFromFile(clientCtx, filename) if err != nil { - return client.Context{}, types.TxBuilder{}, types.StdTx{}, err + return clientCtx, tx.Factory{}, nil, err } inBuf := bufio.NewReader(cmd.InOrStdin()) - clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) - txBldr := types.NewTxBuilderFromCLI(inBuf) + clientCtx = clientCtx.InitWithInput(inBuf) + txFactory := tx.NewFactoryFromCLI(inBuf) - return clientCtx, txBldr, stdTx, nil + return clientCtx, txFactory, stdTx, nil } diff --git a/x/auth/client/query.go b/x/auth/client/query.go index 7d5cbacb88a1..d68c9cae1e3c 100644 --- a/x/auth/client/query.go +++ b/x/auth/client/query.go @@ -74,31 +74,31 @@ func QueryTxsByEvents(clientCtx client.Context, events []string, page, limit int // QueryTx queries for a single transaction by a hash string in hex format. An // error is returned if the transaction does not exist or cannot be queried. -func QueryTx(clientCtx client.Context, hashHexStr string) (sdk.TxResponse, error) { +func QueryTx(clientCtx client.Context, hashHexStr string) (*sdk.TxResponse, error) { hash, err := hex.DecodeString(hashHexStr) if err != nil { - return sdk.TxResponse{}, err + return nil, err } node, err := clientCtx.GetNode() if err != nil { - return sdk.TxResponse{}, err + return nil, err } resTx, err := node.Tx(hash, !clientCtx.TrustNode) if err != nil { - return sdk.TxResponse{}, err + return nil, err } if !clientCtx.TrustNode { if err = ValidateTxResult(clientCtx, resTx); err != nil { - return sdk.TxResponse{}, err + return nil, err } } resBlocks, err := getBlocksForTxResults(clientCtx, []*ctypes.ResultTx{resTx}) if err != nil { - return sdk.TxResponse{}, err + return nil, err } out, err := formatTxResult(clientCtx.Codec, resTx, resBlocks[resTx.Height]) @@ -110,9 +110,9 @@ func QueryTx(clientCtx client.Context, hashHexStr string) (sdk.TxResponse, error } // formatTxResults parses the indexed txs into a slice of TxResponse objects. -func formatTxResults(cdc *codec.Codec, resTxs []*ctypes.ResultTx, resBlocks map[int64]*ctypes.ResultBlock) ([]sdk.TxResponse, error) { +func formatTxResults(cdc *codec.Codec, resTxs []*ctypes.ResultTx, resBlocks map[int64]*ctypes.ResultBlock) ([]*sdk.TxResponse, error) { var err error - out := make([]sdk.TxResponse, len(resTxs)) + out := make([]*sdk.TxResponse, len(resTxs)) for i := range resTxs { out[i], err = formatTxResult(cdc, resTxs[i], resBlocks[resTxs[i].Height]) if err != nil { @@ -160,10 +160,10 @@ func getBlocksForTxResults(clientCtx client.Context, resTxs []*ctypes.ResultTx) return resBlocks, nil } -func formatTxResult(cdc *codec.Codec, resTx *ctypes.ResultTx, resBlock *ctypes.ResultBlock) (sdk.TxResponse, error) { +func formatTxResult(cdc *codec.Codec, resTx *ctypes.ResultTx, resBlock *ctypes.ResultBlock) (*sdk.TxResponse, error) { tx, err := parseTx(cdc, resTx.Tx) if err != nil { - return sdk.TxResponse{}, err + return nil, err } return sdk.NewResponseResultTx(resTx, tx, resBlock.Block.Time.Format(time.RFC3339)), nil diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index d8dfb531b051..c528f79976ae 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -9,6 +9,10 @@ import ( "os" "strings" + types "github.com/cosmos/cosmos-sdk/types/tx" + + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/gogo/protobuf/jsonpb" "github.com/pkg/errors" "github.com/spf13/viper" @@ -178,60 +182,51 @@ func PrintUnsignedStdTx(txBldr authtypes.TxBuilder, clientCtx client.Context, ms // SignStdTx appends a signature to a StdTx and returns a copy of it. If appendSig // is false, it replaces the signatures already attached with the new signature. // Don't perform online validation or lookups if offline is true. -func SignStdTx( - txBldr authtypes.TxBuilder, clientCtx client.Context, name string, - stdTx authtypes.StdTx, appendSig bool, offline bool, -) (authtypes.StdTx, error) { - - var signedStdTx authtypes.StdTx - +func SignStdTx(txBldr tx.Factory, clientCtx client.Context, name string, stdTx client.TxBuilder, appendSig bool, offline bool) error { info, err := txBldr.Keybase().Key(name) if err != nil { - return signedStdTx, err + return err } addr := info.GetPubKey().Address() // check whether the address is a signer - if !isTxSigner(sdk.AccAddress(addr), stdTx.GetSigners()) { - return signedStdTx, fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) + if !isTxSigner(sdk.AccAddress(addr), stdTx.GetTx().(types.SigTx).GetSigners()) { + return fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) } if !offline { txBldr, err = populateAccountFromState(txBldr, clientCtx, sdk.AccAddress(addr)) if err != nil { - return signedStdTx, err + return err } } - return txBldr.SignStdTx(name, stdTx, appendSig) + return tx.Sign(txBldr, name, stdTx) } // SignStdTxWithSignerAddress attaches a signature to a StdTx and returns a copy of a it. // Don't perform online validation or lookups if offline is true, else // populate account and sequence numbers from a foreign account. -func SignStdTxWithSignerAddress( - txBldr authtypes.TxBuilder, clientCtx client.Context, - addr sdk.AccAddress, name string, stdTx authtypes.StdTx, offline bool, -) (signedStdTx authtypes.StdTx, err error) { - - // check whether the address is a signer - if !isTxSigner(addr, stdTx.GetSigners()) { - return signedStdTx, fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) +func SignStdTxWithSignerAddress(txFactory tx.Factory, clientCtx client.Context, addr sdk.AccAddress, name string, txBuilder client.TxBuilder, offline bool) error { + //check whether the address is a signer + if !isTxSigner(addr, txBuilder.GetTx().GetSigners()) { + return fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) } + var err error if !offline { - txBldr, err = populateAccountFromState(txBldr, clientCtx, addr) + txFactory, err = populateAccountFromState(txFactory, clientCtx, addr) if err != nil { - return signedStdTx, err + return err } } - return txBldr.SignStdTx(name, stdTx, false) + return tx.Sign(txFactory, name, txBuilder) } // Read and decode a StdTx from the given filename. Can pass "-" to read from stdin. -func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx, err error) { +func ReadTxFromFile(ctx client.Context, filename string) (tx sdk.Tx, err error) { var bytes []byte if filename == "-" { @@ -244,11 +239,7 @@ func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx return } - if err = cdc.UnmarshalJSON(bytes, &stdTx); err != nil { - return - } - - return + return ctx.TxGenerator.TxJSONDecoder()(bytes) } // NewBatchScanner returns a new BatchScanner to read newline-delimited StdTx transactions from r. @@ -285,11 +276,9 @@ func (bs *BatchScanner) Scan() bool { return true } -func populateAccountFromState( - txBldr authtypes.TxBuilder, clientCtx client.Context, addr sdk.AccAddress, -) (authtypes.TxBuilder, error) { +func populateAccountFromState(txBldr tx.Factory, clientCtx client.Context, addr sdk.AccAddress) (tx.Factory, error) { - num, seq, err := authtypes.NewAccountRetriever(Codec).GetAccountNumberSequence(clientCtx, addr) + num, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr) if err != nil { return txBldr, err } diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index 3e4bd6adec79..20cffe3a3d36 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -8,6 +8,12 @@ import ( "strings" "testing" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" + types "github.com/cosmos/cosmos-sdk/types/tx" + "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" @@ -116,24 +122,29 @@ func TestConfiguredTxEncoder(t *testing.T) { compareEncoders(t, customEncoder, encoder) } -func TestReadStdTxFromFile(t *testing.T) { +func TestReadTxFromFile(t *testing.T) { t.Parallel() cdc := codec.New() sdk.RegisterCodec(cdc) + txGen := simappparams.MakeEncodingConfig().TxGenerator + clientCtx := client.Context{} + clientCtx = clientCtx.WithTxGenerator(txGen) // Build a test transaction - fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") + txBuilder := txGen.NewTxBuilder() + txBuilder.SetGasLimit(50000) + txBuilder.SetFee(sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + txBuilder.SetMemo("foomemo") // Write it to the file - encodedTx, _ := cdc.MarshalJSON(stdTx) + encodedTx, _ := txGen.TxJSONEncoder()(txBuilder.GetTx()) jsonTxFile := writeToNewTempFile(t, string(encodedTx)) defer os.Remove(jsonTxFile.Name()) // Read it back - decodedTx, err := ReadStdTxFromFile(cdc, jsonTxFile.Name()) + decodedTx, err := ReadTxFromFile(clientCtx, jsonTxFile.Name()) require.NoError(t, err) - require.Equal(t, decodedTx.Memo, "foomemo") + require.Equal(t, decodedTx.(types.TxWithMemo).GetMemo(), "foomemo") } func TestBatchScanner_Scan(t *testing.T) { diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index 13018004cc24..ed27aa0a1f0d 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -188,7 +188,7 @@ func (ak AccountKeeper) decodeAccount(bz []byte) types.AccountI { // the Marshaler interface, it is treated as a Proto-defined message and // serialized that way. Otherwise, it falls back on the internal Amino codec. func (ak AccountKeeper) MarshalAccount(accountI types.AccountI) ([]byte, error) { - return codec.MarshalAny(ak.cdc, accountI) + return ak.cdc.MarshalAny(accountI) } // UnmarshalEvidence returns an Evidence interface from raw encoded evidence @@ -196,7 +196,7 @@ func (ak AccountKeeper) MarshalAccount(accountI types.AccountI) ([]byte, error) // failure. func (ak AccountKeeper) UnmarshalAccount(bz []byte) (types.AccountI, error) { var acc types.AccountI - if err := codec.UnmarshalAny(ak.cdc, &acc, bz); err != nil { + if err := ak.cdc.UnmarshalAny(bz, &acc); err != nil { return nil, err } diff --git a/x/auth/keeper/keeper_test.go b/x/auth/keeper/keeper_test.go index e3f5d7f3d88b..0863e08a2d55 100644 --- a/x/auth/keeper/keeper_test.go +++ b/x/auth/keeper/keeper_test.go @@ -5,9 +5,7 @@ import ( "github.com/stretchr/testify/require" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -108,7 +106,7 @@ func TestSupply_ValidatePermissions(t *testing.T) { maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking} maccPerms[randomPerm] = []string{"random"} - appCodec := std.NewAppCodec(app.Codec(), codectypes.NewInterfaceRegistry()) + appCodec, _, _ := simapp.MakeCodecs() keeper := auth.NewAccountKeeper( appCodec, app.GetKey(types.StoreKey), app.GetSubspace(types.ModuleName), types.ProtoBaseAccount, maccPerms, diff --git a/x/auth/legacy/v0_39/migrate_test.go b/x/auth/legacy/v0_39/migrate_test.go index 76eb51e21e61..616be276181e 100644 --- a/x/auth/legacy/v0_39/migrate_test.go +++ b/x/auth/legacy/v0_39/migrate_test.go @@ -1,6 +1,7 @@ package v039_test import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "testing" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/auth/module.go b/x/auth/module.go index 291654a114a3..17a4727069e1 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -66,7 +66,7 @@ func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Rout // GetTxCmd returns the root tx command for the auth module. func (AppModuleBasic) GetTxCmd(clientCtx client.Context) *cobra.Command { - return cli.GetTxCmd(clientCtx.Codec) + return cli.GetTxCmd(clientCtx) } // GetQueryCmd returns the root query command for the auth module. diff --git a/x/auth/simulation/decoder_test.go b/x/auth/simulation/decoder_test.go index 6603d0083cb9..57e150f2b951 100644 --- a/x/auth/simulation/decoder_test.go +++ b/x/auth/simulation/decoder_test.go @@ -22,7 +22,7 @@ var ( func TestDecodeStore(t *testing.T) { app := simapp.Setup(false) - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() acc := types.NewBaseAccountWithAddress(delAddr1) dec := simulation.NewDecodeStore(app.AccountKeeper) diff --git a/x/auth/types/client_tx.go b/x/auth/types/client_tx.go index 0dcbe3ffc7d2..75779feb8e0c 100644 --- a/x/auth/types/client_tx.go +++ b/x/auth/types/client_tx.go @@ -1,11 +1,14 @@ package types import ( - "github.com/tendermint/tendermint/crypto" + "fmt" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" + "github.com/cosmos/cosmos-sdk/crypto/multisig" sdk "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types/tx" ) // StdTxBuilder wraps StdTx to implement to the context.TxBuilder interface @@ -16,7 +19,7 @@ type StdTxBuilder struct { var _ client.TxBuilder = &StdTxBuilder{} // GetTx implements TxBuilder.GetTx -func (s *StdTxBuilder) GetTx() sdk.Tx { +func (s *StdTxBuilder) GetTx() types.SigTx { return s.StdTx } @@ -26,42 +29,54 @@ func (s *StdTxBuilder) SetMsgs(msgs ...sdk.Msg) error { return nil } -// GetSignatures implements TxBuilder.GetSignatures -func (s StdTxBuilder) GetSignatures() []sdk.Signature { - res := make([]sdk.Signature, len(s.Signatures)) - for i, sig := range s.Signatures { - res[i] = sig +func SignatureDataToSig(data types.SignatureData) []byte { + if data == nil { + return nil + } + + switch data := data.(type) { + case *types.SingleSignatureData: + return data.Signature + case *types.MultiSignatureData: + n := len(data.Signatures) + sigs := make([][]byte, n) + for i, s := range data.Signatures { + sigs[i] = SignatureDataToSig(s) + } + msig := multisig.AminoMultisignature{ + BitArray: data.BitArray, + Sigs: sigs, + } + return legacy_global.Cdc.MustMarshalBinaryBare(msig) + default: + panic("unexpected case") } - return res } // SetSignatures implements TxBuilder.SetSignatures -func (s *StdTxBuilder) SetSignatures(signatures ...client.Signature) error { +func (s *StdTxBuilder) SetSignatures(signatures ...client.SignatureBuilder) error { sigs := make([]StdSignature, len(signatures)) for i, sig := range signatures { - pubKey := sig.GetPubKey() + pubKey := sig.PubKey var pubKeyBz []byte if pubKey != nil { pubKeyBz = pubKey.Bytes() } sigs[i] = StdSignature{ PubKey: pubKeyBz, - Signature: sig.GetSignature(), + Signature: SignatureDataToSig(sig.Data), } } s.Signatures = sigs return nil } -// GetFee implements TxBuilder.GetFee -func (s StdTxBuilder) GetFee() sdk.Fee { - return s.Fee +func (s *StdTxBuilder) SetFee(amount sdk.Coins) { + s.Fee.Amount = amount } -// SetFee implements TxBuilder.SetFee -func (s *StdTxBuilder) SetFee(fee client.Fee) error { - s.Fee = StdFee{Amount: fee.GetAmount(), Gas: fee.GetGas()} - return nil +func (s *StdTxBuilder) SetGasLimit(limit uint64) { + s.Fee.Gas = limit } // SetMemo implements TxBuilder.SetMemo @@ -79,49 +94,68 @@ type StdTxGenerator struct { Cdc *codec.Codec } +func (s StdTxGenerator) SignModeHandler() types.SignModeHandler { + return LegacyAminoJSONHandler{} +} + var _ client.TxGenerator = StdTxGenerator{} -// NewTx implements TxGenerator.NewTx -func (s StdTxGenerator) NewTx() client.TxBuilder { +// NewTxBuilder implements TxGenerator.NewTxBuilder +func (s StdTxGenerator) NewTxBuilder() client.TxBuilder { return &StdTxBuilder{} } -// NewFee implements TxGenerator.NewFee -func (s StdTxGenerator) NewFee() client.Fee { - return &StdFee{} -} - -// NewSignature implements TxGenerator.NewSignature -func (s StdTxGenerator) NewSignature() client.Signature { - return &StdSignature{} +func (s StdTxGenerator) WrapTxBuilder(tx sdk.Tx) (client.TxBuilder, error) { + stdTx, ok := tx.(StdTx) + if !ok { + return nil, fmt.Errorf("expected %T, got %T", StdTx{}, tx) + } + return &StdTxBuilder{StdTx: stdTx}, nil } // MarshalTx implements TxGenerator.MarshalTx -func (s StdTxGenerator) MarshalTx(tx sdk.Tx) ([]byte, error) { - return DefaultTxEncoder(s.Cdc)(tx) +func (s StdTxGenerator) TxEncoder() sdk.TxEncoder { + return DefaultTxEncoder(s.Cdc) } -var _ client.Fee = &StdFee{} +func (s StdTxGenerator) TxDecoder() sdk.TxDecoder { + return DefaultTxDecoder(s.Cdc) +} -// SetGas implements Fee.SetGas -func (fee *StdFee) SetGas(gas uint64) { - fee.Gas = gas +func (s StdTxGenerator) TxJSONEncoder() sdk.TxEncoder { + return func(tx sdk.Tx) ([]byte, error) { + return s.Cdc.MarshalJSON(tx) + } } -// SetAmount implements Fee.SetAmount -func (fee *StdFee) SetAmount(coins sdk.Coins) { - fee.Amount = coins +func (s StdTxGenerator) TxJSONDecoder() sdk.TxDecoder { + return DefaultJSONTxDecoder(s.Cdc) } -var _ client.Signature = &StdSignature{} +type LegacyAminoJSONHandler struct{} -// SetPubKey implements Signature.SetPubKey -func (ss *StdSignature) SetPubKey(key crypto.PubKey) error { - ss.PubKey = key.Bytes() - return nil +var _ types.SignModeHandler = LegacyAminoJSONHandler{} + +func (h LegacyAminoJSONHandler) DefaultMode() types.SignMode { + return types.SignMode_SIGN_MODE_LEGACY_AMINO_JSON +} + +func (LegacyAminoJSONHandler) Modes() []types.SignMode { + return []types.SignMode{types.SignMode_SIGN_MODE_LEGACY_AMINO_JSON} } -// SetSignature implements Signature.SetSignature -func (ss *StdSignature) SetSignature(bytes []byte) { - ss.Signature = bytes +func (LegacyAminoJSONHandler) GetSignBytes(_ types.SignMode, data types.SigningData, tx sdk.Tx) ([]byte, error) { + feeTx, ok := tx.(types.FeeTx) + if !ok { + return nil, fmt.Errorf("expected FeeTx, got %T", tx) + } + + memoTx, ok := tx.(types.TxWithMemo) + if !ok { + return nil, fmt.Errorf("expected TxWithMemo, got %T", tx) + } + + return StdSignBytes( + data.ChainID, data.AccountNumber, data.AccountSequence, StdFee{Amount: feeTx.GetFee(), Gas: feeTx.GetGas()}, tx.GetMsgs(), memoTx.GetMemo(), + ), nil } diff --git a/x/auth/types/codec.go b/x/auth/types/codec.go index 30ebf84a043a..d951f5a5f83e 100644 --- a/x/auth/types/codec.go +++ b/x/auth/types/codec.go @@ -2,6 +2,7 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" ) diff --git a/x/auth/types/common_test.go b/x/auth/types/common_test.go index 4f361059ad3c..8eac4d021a80 100644 --- a/x/auth/types/common_test.go +++ b/x/auth/types/common_test.go @@ -5,6 +5,6 @@ import ( ) var ( - app = simapp.Setup(false) - appCodec, _ = simapp.MakeCodecs() + app = simapp.Setup(false) + appCodec, _, _ = simapp.MakeCodecs() ) diff --git a/x/auth/types/genesis.go b/x/auth/types/genesis.go index 6e6631e1e8e5..7a4df84b62b0 100644 --- a/x/auth/types/genesis.go +++ b/x/auth/types/genesis.go @@ -29,7 +29,7 @@ func DefaultGenesisState() GenesisState { // GetGenesisStateFromAppState returns x/auth GenesisState given raw application // genesis state. -func GetGenesisStateFromAppState(cdc codec.Marshaler, appState map[string]json.RawMessage) GenesisState { +func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]json.RawMessage) GenesisState { var genesisState GenesisState if appState[ModuleName] != nil { diff --git a/x/auth/types/stdtx.go b/x/auth/types/stdtx.go index 6b6f8ac51030..f1838d0804eb 100644 --- a/x/auth/types/stdtx.go +++ b/x/auth/types/stdtx.go @@ -13,11 +13,9 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + types "github.com/cosmos/cosmos-sdk/types/tx" ) -// MaxGasWanted defines the max gas allowed. -const MaxGasWanted = uint64((1 << 63) - 1) - // Deprecated: StdFee includes the amount of coins paid in fees and the maximum // gas to be used by the transaction. The ratio yields an effective "gasprice", // which must be above some miminum to be accepted into the mempool. @@ -141,7 +139,11 @@ func CountSubKeys(pub crypto.PubKey) int { // DEPRECATED // --------------------------------------------------------------------------- -var _ sdk.Tx = (*StdTx)(nil) +var ( + _ sdk.Tx = (*StdTx)(nil) + _ types.SigTx = (*StdTx)(nil) + _ codectypes.UnpackInterfacesMessage = StdTx{} +) // StdTx is a standard way to wrap a Msg with Fee and Signatures. // NOTE: the first signature is the fee payer (Signatures must not be nil). @@ -169,10 +171,10 @@ func (tx StdTx) GetMsgs() []sdk.Msg { return tx.Msgs } func (tx StdTx) ValidateBasic() error { stdSigs := tx.GetSignatures() - if tx.Fee.Gas > MaxGasWanted { + if tx.Fee.Gas > types.MaxGasWanted { return sdkerrors.Wrapf( sdkerrors.ErrInvalidRequest, - "invalid gas supplied; %d > %d", tx.Fee.Gas, MaxGasWanted, + "invalid gas supplied; %d > %d", tx.Fee.Gas, types.MaxGasWanted, ) } if tx.Fee.Amount.IsAnyNegative() { @@ -275,6 +277,57 @@ func (tx StdTx) FeePayer() sdk.AccAddress { return sdk.AccAddress{} } +func stdSignatureToSignatureV2(pk crypto.PubKey, sig []byte) types.SignatureData { + switch pk := pk.(type) { + case multisig2.MultisigPubKey: + var multisignature multisig.Multisignature + legacy_global.Cdc.MustUnmarshalBinaryBare(sig, &multisignature) + sigs := make([]types.SignatureData, len(multisignature.Sigs)) + size := multisignature.BitArray.Size() + sigIndex := 0 + pubKeys := pk.GetPubKeys() + + for i := 0; i < size; i++ { + if multisignature.BitArray.GetIndex(i) { + sigs[i] = stdSignatureToSignatureV2(pubKeys[i], multisignature.Sigs[sigIndex]) + sigIndex++ + } + } + + return &types.MultiSignatureData{ + BitArray: &types2.CompactBitArray{ + ExtraBitsStored: uint32(multisignature.BitArray.ExtraBitsStored), + Elems: multisignature.BitArray.Elems, + }, + Signatures: sigs, + } + default: + return &types.SingleSignatureData{ + SignMode: types.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, + Signature: sig, + } + } +} + +func (tx StdTx) GetSignatureData() ([]types.SignatureData, error) { + sigs := tx.Signatures + res := make([]types.SignatureData, len(sigs)) + for i, sig := range sigs { + res[i] = stdSignatureToSignatureV2(sig.GetPubKey(), sig.Signature) + } + return res, nil +} + +func (tx StdTx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { + for _, m := range tx.Msgs { + err := codectypes.UnpackInterfaces(m, unpacker) + if err != nil { + return err + } + } + return nil +} + // StdSignDoc is replay-prevention structure. // It includes the result of msg.GetSignBytes(), // as well as the ChainID (prevent cross chain replay) @@ -338,21 +391,28 @@ func DefaultTxDecoder(cdc *codec.Codec) sdk.TxDecoder { } } -// DefaultTxEncoder logic for standard transaction encoding -func DefaultTxEncoder(cdc *codec.Codec) sdk.TxEncoder { - return func(tx sdk.Tx) ([]byte, error) { - return cdc.MarshalBinaryBare(tx) - } -} +func DefaultJSONTxDecoder(cdc *codec.Codec) sdk.TxDecoder { + return func(txBytes []byte) (sdk.Tx, error) { + var tx = StdTx{} -var _ codectypes.UnpackInterfacesMessage = StdTx{} + if len(txBytes) == 0 { + return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx bytes are empty") + } -func (tx StdTx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - for _, m := range tx.Msgs { - err := codectypes.UnpackInterfaces(m, unpacker) + // StdTx.Msg is an interface. The concrete types + // are registered by MakeTxCodec + err := cdc.UnmarshalJSON(txBytes, &tx) if err != nil { - return err + return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error()) } + + return tx, nil + } +} + +// DefaultTxEncoder logic for standard transaction encoding +func DefaultTxEncoder(cdc *codec.Codec) sdk.TxEncoder { + return func(tx sdk.Tx) ([]byte, error) { + return cdc.MarshalBinaryBare(tx) } - return nil } diff --git a/x/auth/types/txbuilder.go b/x/auth/types/txbuilder.go index fd5598492a5c..03c7ac2eb978 100644 --- a/x/auth/types/txbuilder.go +++ b/x/auth/types/txbuilder.go @@ -14,7 +14,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// TxBuilder implements a transaction context created in SDK modules. +// deprecated: TxBuilder implements a transaction context created in SDK modules. type TxBuilder struct { txEncoder sdk.TxEncoder keybase keyring.Keyring diff --git a/x/auth/vesting/types/common_test.go b/x/auth/vesting/types/common_test.go index 4f361059ad3c..8eac4d021a80 100644 --- a/x/auth/vesting/types/common_test.go +++ b/x/auth/vesting/types/common_test.go @@ -5,6 +5,6 @@ import ( ) var ( - app = simapp.Setup(false) - appCodec, _ = simapp.MakeCodecs() + app = simapp.Setup(false) + appCodec, _, _ = simapp.MakeCodecs() ) diff --git a/x/auth/vesting/types/vesting_account.go b/x/auth/vesting/types/vesting_account.go index 0f34228a0282..6f3288026d79 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -2,6 +2,7 @@ package types import ( "errors" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "time" "github.com/cosmos/cosmos-sdk/codec/legacy" diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 2fff4f728ba5..252dd9ec73ee 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -111,7 +111,8 @@ func TestSendNotEnoughBalance(t *testing.T) { sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err = simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{sendMsg}, []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) + txGen := app.GetEncodingConfig().TxGenerator + _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{sendMsg}, []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) require.Error(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 67)}) @@ -178,7 +179,7 @@ func TestSendToModuleAcc(t *testing.T) { origSeq := res1.GetSequence() header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err = simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{test.msg}, []uint64{origAccNum}, []uint64{origSeq}, test.expSimPass, test.expPass, priv1) + _, _, err = simapp.SignCheckDeliver(t, app.GetEncodingConfig().TxGenerator, app.BaseApp, header, []sdk.Msg{test.msg}, []uint64{origAccNum}, []uint64{origSeq}, test.expSimPass, test.expPass, priv1) if test.expPass { require.NoError(t, err) } else { @@ -248,7 +249,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) + _, _, err := simapp.SignCheckDeliver(t, app.GetEncodingConfig().TxGenerator, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) if tc.expPass { require.NoError(t, err) } else { @@ -299,7 +300,7 @@ func TestMsgMultiSendMultipleOut(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) + _, _, err := simapp.SignCheckDeliver(t, app.GetEncodingConfig().TxGenerator, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) for _, eb := range tc.expectedBalances { @@ -353,7 +354,7 @@ func TestMsgMultiSendMultipleInOut(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) + _, _, err := simapp.SignCheckDeliver(t, app.GetEncodingConfig().TxGenerator, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) for _, eb := range tc.expectedBalances { @@ -405,7 +406,8 @@ func TestMsgMultiSendDependent(t *testing.T) { for _, tc := range testCases { header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) + txGen := app.GetEncodingConfig().TxGenerator + _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, tc.msgs, tc.accNums, tc.accSeqs, tc.expSimPass, tc.expPass, tc.privKeys...) require.NoError(t, err) for _, eb := range tc.expectedBalances { diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index a66e8d593d61..0261686eac01 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -33,7 +33,7 @@ func BenchmarkOneBankSendTxPerBlock(b *testing.B) { benchmarkApp.Commit() // Precompute all txs - txs := simapp.GenSequenceOfTxs([]sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) + txs := simapp.GenSequenceOfTxs(simapp.MakeEncodingConfig().TxGenerator, []sdk.Msg{sendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) b.ResetTimer() height := int64(3) @@ -73,7 +73,7 @@ func BenchmarkOneBankMultiSendTxPerBlock(b *testing.B) { benchmarkApp.Commit() // Precompute all txs - txs := simapp.GenSequenceOfTxs([]sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) + txs := simapp.GenSequenceOfTxs(simapp.MakeEncodingConfig().TxGenerator, []sdk.Msg{multiSendMsg1}, []uint64{0}, []uint64{uint64(0)}, b.N, priv1) b.ResetTimer() height := int64(3) diff --git a/x/bank/client/cli/cli_test.go b/x/bank/client/cli/cli_test.go index 743d348731ad..4dbcd6af4bb1 100644 --- a/x/bank/client/cli/cli_test.go +++ b/x/bank/client/cli/cli_test.go @@ -55,10 +55,10 @@ func TestCLISend(t *testing.T) { ) require.Empty(t, stderr) require.True(t, success) - msg := cli.UnmarshalStdTx(f.T, f.Cdc, stdout) + msg := f.UnmarshalTxJSON(stdout) t.Log(msg) - require.NotZero(t, msg.Fee.Gas) - require.Len(t, msg.Msgs, 1) + require.NotZero(t, msg.GetGas()) + require.Len(t, msg.GetMsgs(), 1) require.Len(t, msg.GetSignatures(), 0) // Check state didn't change diff --git a/x/bank/client/testutil/helpers.go b/x/bank/client/testutil/helpers.go index c09de98ac873..c7609683c2fa 100644 --- a/x/bank/client/testutil/helpers.go +++ b/x/bank/client/testutil/helpers.go @@ -32,7 +32,7 @@ func QueryAccount(f *cli.Fixtures, address sdk.AccAddress, flags ...string) auth value := initRes["value"] var acc auth.BaseAccount - err = f.Cdc.UnmarshalJSON(value, &acc) + err = f.JSONMarshaler.UnmarshalJSON(value, &acc) require.NoError(f.T, err, "value %v, err %v", string(value), err) return acc @@ -46,7 +46,7 @@ func QueryBalances(f *cli.Fixtures, address sdk.AccAddress, flags ...string) sdk var balances sdk.Coins - require.NoError(f.T, f.Cdc.UnmarshalJSON([]byte(out), &balances), "out %v\n", out) + require.NoError(f.T, f.JSONMarshaler.UnmarshalJSON([]byte(out), &balances), "out %v\n", out) return balances } @@ -57,7 +57,7 @@ func QueryTotalSupply(f *cli.Fixtures, flags ...string) (totalSupply sdk.Coins) res, errStr := tests.ExecuteT(f.T, cmd, "") require.Empty(f.T, errStr) - err := f.Cdc.UnmarshalJSON([]byte(res), &totalSupply) + err := f.JSONMarshaler.UnmarshalJSON([]byte(res), &totalSupply) require.NoError(f.T, err) return totalSupply } @@ -69,7 +69,7 @@ func QueryTotalSupplyOf(f *cli.Fixtures, denom string, flags ...string) sdk.Int require.Empty(f.T, errStr) var supplyOf sdk.Int - err := f.Cdc.UnmarshalJSON([]byte(res), &supplyOf) + err := f.JSONMarshaler.UnmarshalJSON([]byte(res), &supplyOf) require.NoError(f.T, err) return supplyOf } diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 6c0fa582c038..7d50426628e5 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -353,7 +353,7 @@ func (k BaseKeeper) trackUndelegation(ctx sdk.Context, addr sdk.AccAddress, amt // the Marshaler interface, it is treated as a Proto-defined message and // serialized that way. Otherwise, it falls back on the internal Amino codec. func (k BaseKeeper) MarshalSupply(supplyI exported.SupplyI) ([]byte, error) { - return codec.MarshalAny(k.cdc, supplyI) + return k.cdc.MarshalAny(supplyI) } // UnmarshalSupply returns a Supply interface from raw encoded supply @@ -361,7 +361,7 @@ func (k BaseKeeper) MarshalSupply(supplyI exported.SupplyI) ([]byte, error) { // failure. func (k BaseKeeper) UnmarshalSupply(bz []byte) (exported.SupplyI, error) { var evi exported.SupplyI - if err := codec.UnmarshalAny(k.cdc, &evi, bz); err != nil { + if err := k.cdc.UnmarshalAny(bz, &evi); err != nil { return nil, err } diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index ed1fa4a558d9..37e06577e86d 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -207,7 +207,7 @@ func (suite *IntegrationTestSuite) TestSupply_MintCoins() { func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1}) - appCodec, _ := simapp.MakeCodecs() + appCodec, _, _ := simapp.MakeCodecs() // add module accounts to supply keeper maccPerms := simapp.GetMaccPerms() diff --git a/x/bank/legacy/v0_39/migrate_test.go b/x/bank/legacy/v0_39/migrate_test.go index 1b61ccdcb89e..3d8e9d0c3fef 100644 --- a/x/bank/legacy/v0_39/migrate_test.go +++ b/x/bank/legacy/v0_39/migrate_test.go @@ -1,6 +1,7 @@ package v039_test import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "testing" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 8023a376f675..2e8d4f22b2df 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -104,15 +104,8 @@ func sendMsgSend( } } - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - privkeys..., - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, privkeys...) _, _, err = app.Deliver(tx) if err != nil { @@ -215,10 +208,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope // sendMsgMultiSend sends a transaction with a MsgMultiSend from a provided random // account. // nolint: interfacer -func sendMsgMultiSend( - r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, - msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey, -) error { +func sendMsgMultiSend(r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey) error { accountNumbers := make([]uint64, len(msg.Inputs)) sequenceNumbers := make([]uint64, len(msg.Inputs)) @@ -246,15 +236,8 @@ func sendMsgMultiSend( } } - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - accountNumbers, - sequenceNumbers, - privkeys..., - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, accountNumbers, sequenceNumbers, privkeys...) _, _, err = app.Deliver(tx) if err != nil { diff --git a/x/bank/types/codec.go b/x/bank/types/codec.go index ce5c48388008..239624a5f8cb 100644 --- a/x/bank/types/codec.go +++ b/x/bank/types/codec.go @@ -2,6 +2,7 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/bank/types/genesis.go b/x/bank/types/genesis.go index 2ff55476e6c9..d744c2a16cb3 100644 --- a/x/bank/types/genesis.go +++ b/x/bank/types/genesis.go @@ -65,7 +65,7 @@ func DefaultGenesisState() GenesisState { // GetGenesisStateFromAppState returns x/bank GenesisState given raw application // genesis state. -func GetGenesisStateFromAppState(cdc *codec.Codec, appState map[string]json.RawMessage) GenesisState { +func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]json.RawMessage) GenesisState { var genesisState GenesisState if appState[ModuleName] != nil { diff --git a/x/capability/simulation/decoder_test.go b/x/capability/simulation/decoder_test.go index 8f10e9085421..6b2f9ec0032e 100644 --- a/x/capability/simulation/decoder_test.go +++ b/x/capability/simulation/decoder_test.go @@ -14,7 +14,7 @@ import ( ) func TestDecodeStore(t *testing.T) { - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() dec := simulation.NewDecodeStore(cdc) capOwners := types.CapabilityOwners{ diff --git a/x/crisis/types/codec.go b/x/crisis/types/codec.go index 33cf7198249d..14b7485658c5 100644 --- a/x/crisis/types/codec.go +++ b/x/crisis/types/codec.go @@ -2,6 +2,7 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" ) @@ -9,7 +10,7 @@ import ( // RegisterCodec registers the necessary x/crisis interfaces and concrete types // on the provided Amino codec. These types are used for Amino JSON serialization. func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgVerifyInvariant{}, "cosmos-sdk/MsgVerifyInvariant", nil) + cdc.RegisterConcrete(&MsgVerifyInvariant{}, "cosmos-sdk/MsgVerifyInvariant", nil) } var ( diff --git a/x/distribution/client/cli/cli_test.go b/x/distribution/client/cli/cli_test.go index d2c63acd69c1..d5301f9b9276 100644 --- a/x/distribution/client/cli/cli_test.go +++ b/x/distribution/client/cli/cli_test.go @@ -22,18 +22,18 @@ func TestCLIWithdrawRewards(t *testing.T) { genesisState := f.GenesisState() inflationMin := sdk.MustNewDecFromStr("1.0") var mintData mint.GenesisState - f.Cdc.UnmarshalJSON(genesisState[mint.ModuleName], &mintData) + f.JSONMarshaler.UnmarshalJSON(genesisState[mint.ModuleName], &mintData) mintData.Minter.Inflation = inflationMin mintData.Params.InflationMin = inflationMin mintData.Params.InflationMax = sdk.MustNewDecFromStr("1.0") - mintDataBz, err := f.Cdc.MarshalJSON(mintData) + mintDataBz, err := f.JSONMarshaler.MarshalJSON(mintData) require.NoError(t, err) genesisState[mint.ModuleName] = mintDataBz genFile := filepath.Join(f.SimdHome, "config", "genesis.json") genDoc, err := tmtypes.GenesisDocFromFile(genFile) require.NoError(t, err) - genDoc.AppState, err = f.Cdc.MarshalJSON(genesisState) + genDoc.AppState, err = f.JSONMarshaler.MarshalJSON(genesisState) require.NoError(t, genDoc.SaveAs(genFile)) // start simd server diff --git a/x/distribution/client/testutil/helpers.go b/x/distribution/client/testutil/helpers.go index 975d31674a64..202e703f76e4 100644 --- a/x/distribution/client/testutil/helpers.go +++ b/x/distribution/client/testutil/helpers.go @@ -24,7 +24,7 @@ func QueryRewards(f *cli.Fixtures, delAddr sdk.AccAddress, flags ...string) dist require.Empty(f.T, errStr) var rewards distribution.QueryDelegatorTotalRewardsResponse - err := f.Cdc.UnmarshalJSON([]byte(res), &rewards) + err := f.JSONMarshaler.UnmarshalJSON([]byte(res), &rewards) require.NoError(f.T, err) return rewards } diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index 7fddb1625c7b..75ddee153864 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -23,7 +23,7 @@ var ( ) func TestDecodeDistributionStore(t *testing.T) { - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() dec := simulation.NewDecodeStore(cdc) decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.OneDec())} diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index fb3170e59aea..01aec0c6ead9 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -100,15 +100,8 @@ func SimulateMsgSetWithdrawAddress(ak types.AccountKeeper, bk types.BankKeeper, msg := types.NewMsgSetWithdrawAddress(simAccount.Address, simToAccount.Address) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -147,15 +140,8 @@ func SimulateMsgWithdrawDelegatorReward(ak types.AccountKeeper, bk types.BankKee msg := types.NewMsgWithdrawDelegatorReward(simAccount.Address, validator.GetOperator()) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -197,15 +183,8 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban msg := types.NewMsgWithdrawValidatorCommission(validator.GetOperator()) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -247,15 +226,8 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k } msg := types.NewMsgFundCommunityPool(fundAmount, funder.Address) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - funder.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, funder.PrivKey) _, _, err = app.Deliver(tx) if err != nil { diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go index 869b8316310e..f28a70778de0 100644 --- a/x/distribution/types/codec.go +++ b/x/distribution/types/codec.go @@ -2,6 +2,7 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,6 +17,7 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(&MsgSetWithdrawAddress{}, "cosmos-sdk/MsgModifyWithdrawAddress", nil) cdc.RegisterConcrete(&MsgFundCommunityPool{}, "cosmos-sdk/MsgFundCommunityPool", nil) cdc.RegisterConcrete(&CommunityPoolSpendProposal{}, "cosmos-sdk/CommunityPoolSpendProposal", nil) + cdc.RegisterConcrete(FeePool{}, "cosmos-sdk/FeePool", nil) } func RegisterInterfaces(registry types.InterfaceRegistry) { diff --git a/x/evidence/keeper/infraction_test.go b/x/evidence/keeper/infraction_test.go index 6c2506f1d295..e697f8325547 100644 --- a/x/evidence/keeper/infraction_test.go +++ b/x/evidence/keeper/infraction_test.go @@ -3,6 +3,8 @@ package keeper_test import ( "time" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/evidence/types" "github.com/cosmos/cosmos-sdk/x/staking" diff --git a/x/evidence/keeper/keeper.go b/x/evidence/keeper/keeper.go index ce629ff0bc4d..861129169212 100644 --- a/x/evidence/keeper/keeper.go +++ b/x/evidence/keeper/keeper.go @@ -173,7 +173,7 @@ func (k Keeper) MustMarshalEvidence(evidence exported.Evidence) []byte { // the Marshaler interface, it is treated as a Proto-defined message and // serialized that way. Otherwise, it falls back on the internal Amino codec. func (k Keeper) MarshalEvidence(evidenceI exported.Evidence) ([]byte, error) { - return codec.MarshalAny(k.cdc, evidenceI) + return k.cdc.MarshalAny(evidenceI) } // UnmarshalEvidence returns an Evidence interface from raw encoded evidence @@ -181,7 +181,7 @@ func (k Keeper) MarshalEvidence(evidenceI exported.Evidence) ([]byte, error) { // failure. func (k Keeper) UnmarshalEvidence(bz []byte) (exported.Evidence, error) { var evi exported.Evidence - if err := codec.UnmarshalAny(k.cdc, &evi, bz); err != nil { + if err := k.cdc.UnmarshalAny(bz, &evi); err != nil { return nil, err } diff --git a/x/evidence/keeper/querier_test.go b/x/evidence/keeper/querier_test.go index 7433f099a074..249d1a8dabb1 100644 --- a/x/evidence/keeper/querier_test.go +++ b/x/evidence/keeper/querier_test.go @@ -3,14 +3,11 @@ package keeper_test import ( "strings" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - - "github.com/cosmos/cosmos-sdk/std" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/x/evidence/exported" "github.com/cosmos/cosmos-sdk/x/evidence/types" - - abci "github.com/tendermint/tendermint/abci/types" ) const ( @@ -20,7 +17,7 @@ const ( func (suite *KeeperTestSuite) TestQueryEvidence_Existing() { ctx := suite.ctx.WithIsCheckTx(false) numEvidence := 100 - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _, _ := simapp.MakeCodecs() evidence := suite.populateEvidence(ctx, numEvidence) query := abci.RequestQuery{ @@ -39,7 +36,7 @@ func (suite *KeeperTestSuite) TestQueryEvidence_Existing() { func (suite *KeeperTestSuite) TestQueryEvidence_NonExisting() { ctx := suite.ctx.WithIsCheckTx(false) - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _, _ := simapp.MakeCodecs() numEvidence := 100 suite.populateEvidence(ctx, numEvidence) @@ -55,7 +52,7 @@ func (suite *KeeperTestSuite) TestQueryEvidence_NonExisting() { func (suite *KeeperTestSuite) TestQueryAllEvidence() { ctx := suite.ctx.WithIsCheckTx(false) - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _, _ := simapp.MakeCodecs() numEvidence := 100 suite.populateEvidence(ctx, numEvidence) @@ -75,7 +72,7 @@ func (suite *KeeperTestSuite) TestQueryAllEvidence() { func (suite *KeeperTestSuite) TestQueryAllEvidence_InvalidPagination() { ctx := suite.ctx.WithIsCheckTx(false) - cdc := std.NewAppCodec(suite.app.Codec(), codectypes.NewInterfaceRegistry()) + cdc, _, _ := simapp.MakeCodecs() numEvidence := 100 suite.populateEvidence(ctx, numEvidence) diff --git a/x/evidence/types/codec.go b/x/evidence/types/codec.go index bee5be2cf9da..fa4a4d815f8b 100644 --- a/x/evidence/types/codec.go +++ b/x/evidence/types/codec.go @@ -2,6 +2,7 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/genutil/alias.go b/x/genutil/alias.go index 8639a7368a01..898f27dca7a6 100644 --- a/x/genutil/alias.go +++ b/x/genutil/alias.go @@ -22,9 +22,6 @@ var ( GenesisStateFromGenDoc = types.GenesisStateFromGenDoc GenesisStateFromGenFile = types.GenesisStateFromGenFile ValidateGenesis = types.ValidateGenesis - - // variable aliases - ModuleCdc = types.ModuleCdc ) type ( diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 5de254415358..3afbba045fa7 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -1,34 +1,24 @@ package cli import ( - "bufio" - "bytes" - "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" - "github.com/pkg/errors" "github.com/spf13/cobra" flag "github.com/spf13/pflag" - "github.com/spf13/viper" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" tmos "github.com/tendermint/tendermint/libs/os" - tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - authclient "github.com/cosmos/cosmos-sdk/x/auth/client" - "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -43,155 +33,156 @@ type StakingMsgBuildingHelpers interface { // nolint: errcheck func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, smbh StakingMsgBuildingHelpers, genBalIterator types.GenesisBalancesIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command { - ipDefault, _ := server.ExternalIP() - fsCreateValidator, flagNodeID, flagPubKey, flagAmount, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault) - - cmd := &cobra.Command{ - Use: "gentx", - Short: "Generate a genesis tx carrying a self delegation", - Args: cobra.NoArgs, - Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'. - - It creates a genesis transaction to create a validator. - The following default parameters are included: - %s`, defaultsDesc), - - RunE: func(cmd *cobra.Command, args []string) error { - - config := ctx.Config - config.SetRoot(viper.GetString(flags.FlagHome)) - nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config) - if err != nil { - return errors.Wrap(err, "failed to initialize node validator files") - } - - // Read --nodeID, if empty take it from priv_validator.json - if nodeIDString := viper.GetString(flagNodeID); nodeIDString != "" { - nodeID = nodeIDString - } - // Read --pubkey, if empty take it from priv_validator.json - if valPubKeyString := viper.GetString(flagPubKey); valPubKeyString != "" { - valPubKey, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, valPubKeyString) - if err != nil { - return errors.Wrap(err, "failed to get consensus node public key") - } - } - - genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile()) - if err != nil { - return errors.Wrapf(err, "failed to read genesis doc file %s", config.GenesisFile()) - } - - var genesisState map[string]json.RawMessage - if err = cdc.UnmarshalJSON(genDoc.AppState, &genesisState); err != nil { - return errors.Wrap(err, "failed to unmarshal genesis state") - } - - if err = mbm.ValidateGenesis(cdc, genesisState); err != nil { - return errors.Wrap(err, "failed to validate genesis state") - } - - inBuf := bufio.NewReader(cmd.InOrStdin()) - kb, err := keyring.New(sdk.KeyringServiceName(), - viper.GetString(flags.FlagKeyringBackend), viper.GetString(flagClientHome), inBuf) - if err != nil { - return errors.Wrap(err, "failed to initialize keybase") - } - - name := viper.GetString(flags.FlagName) - key, err := kb.Key(name) - if err != nil { - return errors.Wrap(err, "failed to read from keybase") - } - - // Set flags for creating gentx - viper.Set(flags.FlagHome, viper.GetString(flagClientHome)) - smbh.PrepareFlagsForTxCreateValidator(config, nodeID, genDoc.ChainID, valPubKey) - - // Fetch the amount of coins staked - amount := viper.GetString(flagAmount) - coins, err := sdk.ParseCoins(amount) - if err != nil { - return errors.Wrap(err, "failed to parse coins") - } - - err = genutil.ValidateAccountInGenesis(genesisState, genBalIterator, key.GetAddress(), coins, cdc) - if err != nil { - return errors.Wrap(err, "failed to validate account in genesis") - } - - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) - clientCtx := client.NewContextWithInput(inBuf).WithCodec(cdc) - - // Set the generate-only flag here after the CLI context has - // been created. This allows the from name/key to be correctly populated. - // - // TODO: Consider removing the manual setting of generate-only in - // favor of a 'gentx' flag in the create-validator command. - viper.Set(flags.FlagGenerateOnly, true) - - // create a 'create-validator' message - txBldr, msg, err := smbh.BuildCreateValidatorMsg(clientCtx, txBldr) - if err != nil { - return errors.Wrap(err, "failed to build create-validator message") - } - - if key.GetType() == keyring.TypeOffline || key.GetType() == keyring.TypeMulti { - cmd.PrintErrln("Offline key passed in. Use `tx sign` command to sign.") - return authclient.PrintUnsignedStdTx(txBldr, clientCtx, []sdk.Msg{msg}) - } - - // write the unsigned transaction to the buffer - w := bytes.NewBuffer([]byte{}) - clientCtx = clientCtx.WithOutput(w) - - if err = authclient.PrintUnsignedStdTx(txBldr, clientCtx, []sdk.Msg{msg}); err != nil { - return errors.Wrap(err, "failed to print unsigned std tx") - } - - // read the transaction - stdTx, err := readUnsignedGenTxFile(cdc, w) - if err != nil { - return errors.Wrap(err, "failed to read unsigned gen tx file") - } - - // sign the transaction and write it to the output file - signedTx, err := authclient.SignStdTx(txBldr, clientCtx, name, stdTx, false, true) - if err != nil { - return errors.Wrap(err, "failed to sign std tx") - } - - // Fetch output file name - outputDocument := viper.GetString(flags.FlagOutputDocument) - if outputDocument == "" { - outputDocument, err = makeOutputFilepath(config.RootDir, nodeID) - if err != nil { - return errors.Wrap(err, "failed to create output file path") - } - } - - if err := writeSignedGenTx(cdc, outputDocument, signedTx); err != nil { - return errors.Wrap(err, "failed to write signed gen tx") - } - - cmd.PrintErrf("Genesis transaction written to %q\n", outputDocument) - return nil - - }, - } - - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory") - cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory") - cmd.Flags().String(flags.FlagName, "", "name of private key with which to sign the gentx") - cmd.Flags().String(flags.FlagOutputDocument, "", - "write the genesis transaction JSON document to the given file instead of the default location") - cmd.Flags().AddFlagSet(fsCreateValidator) - cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") - viper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend)) - - cmd.MarkFlagRequired(flags.FlagName) - - return cmd + panic("TODO") + //ipDefault, _ := server.ExternalIP() + //fsCreateValidator, flagNodeID, flagPubKey, flagAmount, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault) + // + //cmd := &cobra.Command{ + // Use: "gentx", + // Short: "Generate a genesis tx carrying a self delegation", + // Args: cobra.NoArgs, + // Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'. + // + // It creates a genesis transaction to create a validator. + // The following default parameters are included: + // %s`, defaultsDesc), + // + // RunE: func(cmd *cobra.Command, args []string) error { + // + // config := ctx.Config + // config.SetRoot(viper.GetString(flags.FlagHome)) + // nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config) + // if err != nil { + // return errors.Wrap(err, "failed to initialize node validator files") + // } + // + // // Read --nodeID, if empty take it from priv_validator.json + // if nodeIDString := viper.GetString(flagNodeID); nodeIDString != "" { + // nodeID = nodeIDString + // } + // // Read --pubkey, if empty take it from priv_validator.json + // if valPubKeyString := viper.GetString(flagPubKey); valPubKeyString != "" { + // valPubKey, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, valPubKeyString) + // if err != nil { + // return errors.Wrap(err, "failed to get consensus node public key") + // } + // } + // + // genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile()) + // if err != nil { + // return errors.Wrapf(err, "failed to read genesis doc file %s", config.GenesisFile()) + // } + // + // var genesisState map[string]json.RawMessage + // if err = cdc.UnmarshalJSON(genDoc.AppState, &genesisState); err != nil { + // return errors.Wrap(err, "failed to unmarshal genesis state") + // } + // + // if err = mbm.ValidateGenesis(cdc, genesisState); err != nil { + // return errors.Wrap(err, "failed to validate genesis state") + // } + // + // inBuf := bufio.NewReader(cmd.InOrStdin()) + // kb, err := keyring.New(sdk.KeyringServiceName(), + // viper.GetString(flags.FlagKeyringBackend), viper.GetString(flagClientHome), inBuf) + // if err != nil { + // return errors.Wrap(err, "failed to initialize keybase") + // } + // + // name := viper.GetString(flags.FlagName) + // key, err := kb.Key(name) + // if err != nil { + // return errors.Wrap(err, "failed to read from keybase") + // } + // + // // Set flags for creating gentx + // viper.Set(flags.FlagHome, viper.GetString(flagClientHome)) + // smbh.PrepareFlagsForTxCreateValidator(config, nodeID, genDoc.ChainID, valPubKey) + // + // // Fetch the amount of coins staked + // amount := viper.GetString(flagAmount) + // coins, err := sdk.ParseCoins(amount) + // if err != nil { + // return errors.Wrap(err, "failed to parse coins") + // } + // + // err = genutil.ValidateAccountInGenesis(genesisState, genBalIterator, key.GetAddress(), coins, cdc) + // if err != nil { + // return errors.Wrap(err, "failed to validate account in genesis") + // } + // + // txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc)) + // cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + // + // // Set the generate-only flag here after the CLI context has + // // been created. This allows the from name/key to be correctly populated. + // // + // // TODO: Consider removing the manual setting of generate-only in + // // favor of a 'gentx' flag in the create-validator command. + // viper.Set(flags.FlagGenerateOnly, true) + // + // // create a 'create-validator' message + // txBldr, msg, err := smbh.BuildCreateValidatorMsg(cliCtx, txBldr) + // if err != nil { + // return errors.Wrap(err, "failed to build create-validator message") + // } + // + // if key.GetType() == keyring.TypeOffline || key.GetType() == keyring.TypeMulti { + // cmd.PrintErrln("Offline key passed in. Use `tx sign` command to sign.") + // return authclient.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}) + // } + // + // // write the unsigned transaction to the buffer + // w := bytes.NewBuffer([]byte{}) + // cliCtx = cliCtx.WithOutput(w) + // + // if err = authclient.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil { + // return errors.Wrap(err, "failed to print unsigned std tx") + // } + // + // // read the transaction + // stdTx, err := readUnsignedGenTxFile(cdc, w) + // if err != nil { + // return errors.Wrap(err, "failed to read unsigned gen tx file") + // } + // + // // sign the transaction and write it to the output file + // signedTx, err := authclient.SignStdTx(txBldr, cliCtx, name, stdTx, false, true) + // if err != nil { + // return errors.Wrap(err, "failed to sign std tx") + // } + // + // // Fetch output file name + // outputDocument := viper.GetString(flags.FlagOutputDocument) + // if outputDocument == "" { + // outputDocument, err = makeOutputFilepath(config.RootDir, nodeID) + // if err != nil { + // return errors.Wrap(err, "failed to create output file path") + // } + // } + // + // if err := writeSignedGenTx(cdc, outputDocument, signedTx); err != nil { + // return errors.Wrap(err, "failed to write signed gen tx") + // } + // + // cmd.PrintErrf("Genesis transaction written to %q\n", outputDocument) + // return nil + // + // }, + //} + // + //cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory") + //cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory") + //cmd.Flags().String(flags.FlagName, "", "name of private key with which to sign the gentx") + //cmd.Flags().String(flags.FlagOutputDocument, "", + // "write the genesis transaction JSON document to the given file instead of the default location") + //cmd.Flags().AddFlagSet(fsCreateValidator) + //cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") + //viper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend)) + // + //cmd.MarkFlagRequired(flags.FlagName) + // + //return cmd } func makeOutputFilepath(rootDir, nodeID string) (string, error) { diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 3fb52fc7fbbd..aafd48961421 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -2,6 +2,7 @@ package cli import ( "bytes" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "io" "os" "testing" diff --git a/x/genutil/genesis.go b/x/genutil/genesis.go index c8564bdc4e2d..98824b45c4f6 100644 --- a/x/genutil/genesis.go +++ b/x/genutil/genesis.go @@ -3,20 +3,20 @@ package genutil import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/genutil/types" ) // InitGenesis - initialize accounts and deliver genesis transactions func InitGenesis( - ctx sdk.Context, cdc *codec.Codec, stakingKeeper types.StakingKeeper, + ctx sdk.Context, stakingKeeper types.StakingKeeper, deliverTx deliverTxfn, genesisState GenesisState, + txJSONDecoder sdk.TxDecoder, txBinaryEncoder sdk.TxEncoder, ) []abci.ValidatorUpdate { var validators []abci.ValidatorUpdate if len(genesisState.GenTxs) > 0 { - validators = DeliverGenTxs(ctx, cdc, genesisState.GenTxs, stakingKeeper, deliverTx) + validators = DeliverGenTxs(ctx, genesisState.GenTxs, stakingKeeper, deliverTx, txJSONDecoder, txBinaryEncoder) } return validators diff --git a/x/genutil/gentx.go b/x/genutil/gentx.go index 064a67387b8b..f33031684872 100644 --- a/x/genutil/gentx.go +++ b/x/genutil/gentx.go @@ -94,15 +94,21 @@ type deliverTxfn func(abci.RequestDeliverTx) abci.ResponseDeliverTx // invokes the provided deliverTxfn with the decoded StdTx. It returns the result // of the staking module's ApplyAndReturnValidatorSetUpdates. func DeliverGenTxs( - ctx sdk.Context, cdc *codec.Codec, genTxs []json.RawMessage, + ctx sdk.Context, genTxs []json.RawMessage, stakingKeeper types.StakingKeeper, deliverTx deliverTxfn, + txJSONDecoder sdk.TxDecoder, txBinaryEncoder sdk.TxEncoder, ) []abci.ValidatorUpdate { for _, genTx := range genTxs { - var tx authtypes.StdTx - cdc.MustUnmarshalJSON(genTx, &tx) + tx, err := txJSONDecoder(genTx) + if err != nil { + panic(err) + } - bz := cdc.MustMarshalBinaryBare(tx) + bz, err := txBinaryEncoder(tx) + if err != nil { + panic(err) + } res := deliverTx(abci.RequestDeliverTx{Tx: bz}) if !res.IsOK() { diff --git a/x/genutil/module.go b/x/genutil/module.go index ccff8649c90a..52f873fc6825 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -63,20 +63,26 @@ func (AppModuleBasic) GetQueryCmd(clientCtx client.Context) *cobra.Command { ret type AppModule struct { AppModuleBasic - accountKeeper types.AccountKeeper - stakingKeeper types.StakingKeeper - deliverTx deliverTxfn + accountKeeper types.AccountKeeper + stakingKeeper types.StakingKeeper + deliverTx deliverTxfn + txJSONDecoder sdk.TxDecoder + txBinaryEncoder sdk.TxEncoder } // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper types.AccountKeeper, - stakingKeeper types.StakingKeeper, deliverTx deliverTxfn) module.AppModule { + stakingKeeper types.StakingKeeper, deliverTx deliverTxfn, + txJSONDecoder sdk.TxDecoder, txBinaryEncoder sdk.TxEncoder, +) module.AppModule { return module.NewGenesisOnlyAppModule(AppModule{ - AppModuleBasic: AppModuleBasic{}, - accountKeeper: accountKeeper, - stakingKeeper: stakingKeeper, - deliverTx: deliverTx, + AppModuleBasic: AppModuleBasic{}, + accountKeeper: accountKeeper, + stakingKeeper: stakingKeeper, + deliverTx: deliverTx, + txJSONDecoder: txJSONDecoder, + txBinaryEncoder: txBinaryEncoder, }) } @@ -85,7 +91,7 @@ func NewAppModule(accountKeeper types.AccountKeeper, func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState cdc.MustUnmarshalJSON(data, &genesisState) - return InitGenesis(ctx, ModuleCdc, am.stakingKeeper, am.deliverTx, genesisState) + return InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txJSONDecoder, am.txBinaryEncoder) } // ExportGenesis returns the exported genesis state as raw bytes for the genutil diff --git a/x/gov/client/cli/cli_test.go b/x/gov/client/cli/cli_test.go index e77a0a241a3d..b7478c7425b3 100644 --- a/x/gov/client/cli/cli_test.go +++ b/x/gov/client/cli/cli_test.go @@ -42,9 +42,9 @@ func TestCLISubmitProposal(t *testing.T) { fooAddr.String(), "Text", "Test", "test", sdk.NewCoin(cli.Denom, proposalTokens), "--generate-only", "-y") require.True(t, success) require.Empty(t, stderr) - msg := cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) + msg := f.UnmarshalTxJSON(stdout) + require.NotZero(t, msg.GetGas()) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Test --dry-run @@ -80,9 +80,9 @@ func TestCLISubmitProposal(t *testing.T) { success, stdout, stderr = testutil.TxGovDeposit(f, 1, fooAddr.String(), sdk.NewCoin(cli.Denom, depositTokens), "--generate-only") require.True(t, success) require.Empty(t, stderr) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) + msg = f.UnmarshalTxJSON(stdout) + require.NotZero(t, msg.GetGas()) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Run the deposit transaction @@ -114,9 +114,9 @@ func TestCLISubmitProposal(t *testing.T) { success, stdout, stderr = testutil.TxGovVote(f, 1, gov.OptionYes, fooAddr.String(), "--generate-only") require.True(t, success) require.Empty(t, stderr) - msg = cli.UnmarshalStdTx(t, f.Cdc, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) + msg = f.UnmarshalTxJSON(stdout) + require.NotZero(t, msg.GetGas()) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Vote on the proposal diff --git a/x/gov/client/testutil/helpers.go b/x/gov/client/testutil/helpers.go index f6be84a5f1aa..8f7184d5e3ab 100644 --- a/x/gov/client/testutil/helpers.go +++ b/x/gov/client/testutil/helpers.go @@ -22,7 +22,7 @@ func QueryGovParamDeposit(f *cli.Fixtures) gov.DepositParams { out, _ := tests.ExecuteT(f.T, cmd, "") var depositParam gov.DepositParams - err := f.Cdc.UnmarshalJSON([]byte(out), &depositParam) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &depositParam) require.NoError(f.T, err, "out %v\n, err %v", out, err) return depositParam } @@ -33,7 +33,7 @@ func QueryGovParamVoting(f *cli.Fixtures) gov.VotingParams { out, _ := tests.ExecuteT(f.T, cmd, "") var votingParam gov.VotingParams - err := f.Cdc.UnmarshalJSON([]byte(out), &votingParam) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &votingParam) require.NoError(f.T, err, "out %v\n, err %v", out, err) return votingParam } @@ -44,7 +44,7 @@ func QueryGovParamTallying(f *cli.Fixtures) gov.TallyParams { out, _ := tests.ExecuteT(f.T, cmd, "") var tallyingParam gov.TallyParams - err := f.Cdc.UnmarshalJSON([]byte(out), &tallyingParam) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &tallyingParam) require.NoError(f.T, err, "out %v\n, err %v", out, err) return tallyingParam } @@ -55,7 +55,7 @@ func QueryGovProposal(f *cli.Fixtures, proposalID int, flags ...string) gov.Prop out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var proposal gov.Proposal - err := f.Cdc.UnmarshalJSON([]byte(out), &proposal) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &proposal) require.NoError(f.T, err, "out %v\n, err %v", out, err) return proposal } @@ -70,7 +70,7 @@ func QueryGovProposals(f *cli.Fixtures, flags ...string) gov.Proposals { require.Empty(f.T, stderr) var out gov.Proposals - err := f.Cdc.UnmarshalJSON([]byte(stdout), &out) + err := f.JSONMarshaler.UnmarshalJSON([]byte(stdout), &out) require.NoError(f.T, err) return out } @@ -81,7 +81,7 @@ func QueryGovVote(f *cli.Fixtures, proposalID int, voter sdk.AccAddress, flags . out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var vote gov.Vote - err := f.Cdc.UnmarshalJSON([]byte(out), &vote) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &vote) require.NoError(f.T, err, "out %v\n, err %v", out, err) return vote } @@ -92,7 +92,7 @@ func QueryGovVotes(f *cli.Fixtures, proposalID int, flags ...string) []gov.Vote out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var votes []gov.Vote - err := f.Cdc.UnmarshalJSON([]byte(out), &votes) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &votes) require.NoError(f.T, err, "out %v\n, err %v", out, err) return votes } @@ -103,7 +103,7 @@ func QueryGovDeposit(f *cli.Fixtures, proposalID int, depositor sdk.AccAddress, out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var deposit gov.Deposit - err := f.Cdc.UnmarshalJSON([]byte(out), &deposit) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &deposit) require.NoError(f.T, err, "out %v\n, err %v", out, err) return deposit } @@ -114,7 +114,7 @@ func QueryGovDeposits(f *cli.Fixtures, propsalID int, flags ...string) []gov.Dep out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "") var deposits []gov.Deposit - err := f.Cdc.UnmarshalJSON([]byte(out), &deposits) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &deposits) require.NoError(f.T, err, "out %v\n, err %v", out, err) return deposits } diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 6739dc1bc224..9e13d4c668f4 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -52,7 +52,7 @@ func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposal var deposits []types.Deposit for _, info := range searchResult.Txs { - for _, msg := range info.Tx.GetMsgs() { + for _, msg := range info.GetTx().GetMsgs() { if msg.Type() == types.TypeMsgDeposit { depMsg := msg.(*types.MsgDeposit) @@ -93,7 +93,7 @@ func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVot } nextTxPage++ for _, info := range searchResult.Txs { - for _, msg := range info.Tx.GetMsgs() { + for _, msg := range info.GetTx().GetMsgs() { if msg.Type() == types.TypeMsgVote { voteMsg := msg.(*types.MsgVote) @@ -136,7 +136,7 @@ func QueryVoteByTxQuery(clientCtx client.Context, params types.QueryVoteParams) return nil, err } for _, info := range searchResult.Txs { - for _, msg := range info.Tx.GetMsgs() { + for _, msg := range info.GetTx().GetMsgs() { // there should only be a single vote under the given conditions if msg.Type() == types.TypeMsgVote { voteMsg := msg.(*types.MsgVote) @@ -176,7 +176,7 @@ func QueryDepositByTxQuery(clientCtx client.Context, params types.QueryDepositPa } for _, info := range searchResult.Txs { - for _, msg := range info.Tx.GetMsgs() { + for _, msg := range info.GetTx().GetMsgs() { // there should only be a single deposit under the given conditions if msg.Type() == types.TypeMsgDeposit { depMsg := msg.(*types.MsgDeposit) @@ -215,7 +215,7 @@ func QueryProposerByTxQuery(clientCtx client.Context, proposalID uint64) (Propos } for _, info := range searchResult.Txs { - for _, msg := range info.Tx.GetMsgs() { + for _, msg := range info.GetTx().GetMsgs() { // there should only be a single proposal under the given conditions if msg.Type() == types.TypeMsgSubmitProposal { subMsg := msg.(*types.MsgSubmitProposal) diff --git a/x/gov/keeper/common_test.go b/x/gov/keeper/common_test.go index 2cac40eb6223..684df32ef572 100644 --- a/x/gov/keeper/common_test.go +++ b/x/gov/keeper/common_test.go @@ -16,7 +16,7 @@ func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sd valAddrs := simapp.ConvertAddrsToValAddrs(addrs) pks := simapp.CreateTestPubKeys(5) - appCodec, _ := simapp.MakeCodecs() + appCodec, _, _ := simapp.MakeCodecs() app.StakingKeeper = staking.NewKeeper( appCodec, app.GetKey(staking.StoreKey), diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 20087f4a11ef..e82b0452c1f7 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -23,7 +23,7 @@ var ( ) func TestDecodeStore(t *testing.T) { - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() dec := simulation.NewDecodeStore(cdc) endTime := time.Now().UTC() diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 80da7c5b0da7..4a8783d365d0 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -142,15 +142,8 @@ func SimulateSubmitProposal( } } - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -224,15 +217,8 @@ func SimulateMsgDeposit(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Ke } } - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -282,15 +268,8 @@ func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k kee return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to generate fees"), nil, err } - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { diff --git a/x/gov/types/codec.go b/x/gov/types/codec.go index 6fdb45821823..9af2180b079f 100644 --- a/x/gov/types/codec.go +++ b/x/gov/types/codec.go @@ -2,6 +2,7 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/ibc/07-tendermint/tendermint_test.go b/x/ibc/07-tendermint/tendermint_test.go index 8d05ddaddb75..ef74ae2e587d 100644 --- a/x/ibc/07-tendermint/tendermint_test.go +++ b/x/ibc/07-tendermint/tendermint_test.go @@ -1,6 +1,7 @@ package tendermint_test import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "testing" "time" diff --git a/x/mint/simulation/decoder_test.go b/x/mint/simulation/decoder_test.go index 0d69dc331b03..fb7fb95c5c72 100644 --- a/x/mint/simulation/decoder_test.go +++ b/x/mint/simulation/decoder_test.go @@ -15,7 +15,7 @@ import ( ) func TestDecodeStore(t *testing.T) { - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() dec := simulation.NewDecodeStore(cdc) minter := types.NewMinter(sdk.OneDec(), sdk.NewDec(15)) diff --git a/x/params/keeper/querier.go b/x/params/keeper/querier.go index ac218e05e9a9..83f3d993524f 100644 --- a/x/params/keeper/querier.go +++ b/x/params/keeper/querier.go @@ -1,6 +1,7 @@ package keeper import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" abci "github.com/tendermint/tendermint/abci/types" "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index f8cdb3e17aa1..c1493ea328ad 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -64,7 +64,8 @@ func TestSlashingMsgs(t *testing.T) { ) header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) + txGen := simapp.MakeEncodingConfig().TxGenerator + _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) @@ -81,7 +82,7 @@ func TestSlashingMsgs(t *testing.T) { // unjail should fail with unknown validator header = abci.Header{Height: app.LastBlockHeight() + 1} - _, res, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{unjailMsg}, []uint64{0}, []uint64{1}, false, false, priv1) + _, res, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{unjailMsg}, []uint64{0}, []uint64{1}, false, false, priv1) require.Error(t, err) require.Nil(t, res) require.True(t, errors.Is(slashing.ErrValidatorNotJailed, err)) diff --git a/x/slashing/client/testutil/helpers.go b/x/slashing/client/testutil/helpers.go index 48ce2401a101..95ff01bb45ef 100644 --- a/x/slashing/client/testutil/helpers.go +++ b/x/slashing/client/testutil/helpers.go @@ -17,7 +17,7 @@ func QuerySigningInfo(f *cli.Fixtures, val string) slashing.ValidatorSigningInfo require.Empty(f.T, errStr) var sinfo slashing.ValidatorSigningInfo - err := f.Cdc.UnmarshalJSON([]byte(res), &sinfo) + err := f.JSONMarshaler.UnmarshalJSON([]byte(res), &sinfo) require.NoError(f.T, err) return sinfo } @@ -29,7 +29,7 @@ func QuerySlashingParams(f *cli.Fixtures) slashing.Params { require.Empty(f.T, errStr) var params slashing.Params - err := f.Cdc.UnmarshalJSON([]byte(res), ¶ms) + err := f.JSONMarshaler.UnmarshalJSON([]byte(res), ¶ms) require.NoError(f.T, err) return params } diff --git a/x/slashing/keeper/test_common.go b/x/slashing/keeper/test_common.go index fd8cbdb4dd7b..19ac2991b6fd 100644 --- a/x/slashing/keeper/test_common.go +++ b/x/slashing/keeper/test_common.go @@ -5,6 +5,8 @@ package keeper import ( "github.com/tendermint/tendermint/crypto" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" diff --git a/x/slashing/module.go b/x/slashing/module.go index d8f1627311af..44d213ccde7d 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -7,6 +7,8 @@ import ( "github.com/gogo/protobuf/grpc" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/gorilla/mux" "github.com/spf13/cobra" @@ -78,6 +80,10 @@ func (AppModuleBasic) GetQueryCmd(clientCtx client.Context) *cobra.Command { return cli.GetQueryCmd(StoreKey, clientCtx.Codec) } +func (b AppModuleBasic) RegisterInterfaceTypes(registry cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + //____________________________________________________________________________ // AppModule implements an application module for the slashing module. diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 8fbe78823846..8e788912fd6d 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -27,7 +27,7 @@ var ( ) func TestDecodeStore(t *testing.T) { - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() dec := simulation.NewDecodeStore(cdc) info := types.NewValidatorSigningInfo(consAddr1, 0, 1, time.Now().UTC(), false, 0) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index e597913f35d4..72899cb072ee 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -86,15 +86,8 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee msg := types.NewMsgUnjail(validator.GetOperator()) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, res, err := app.Deliver(tx) diff --git a/x/slashing/types/codec.go b/x/slashing/types/codec.go index 5d52f7cb2621..0f706883b55a 100644 --- a/x/slashing/types/codec.go +++ b/x/slashing/types/codec.go @@ -11,6 +11,12 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(&MsgUnjail{}, "cosmos-sdk/MsgUnjail", nil) } +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgUnjail{}, + ) +} + var ( amino = codec.New() diff --git a/x/staking/app_test.go b/x/staking/app_test.go index 635898ee923d..230495087287 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -69,7 +69,8 @@ func TestStakingMsgs(t *testing.T) { ) header := abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err := simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) + txGen := simapp.MakeEncodingConfig().TxGenerator + _, _, err := simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{createValidatorMsg}, []uint64{0}, []uint64{0}, true, true, priv1) require.NoError(t, err) simapp.CheckBalance(t, app, addr1, sdk.Coins{genCoin.Sub(bondCoin)}) @@ -89,7 +90,7 @@ func TestStakingMsgs(t *testing.T) { editValidatorMsg := staking.NewMsgEditValidator(sdk.ValAddress(addr1), description, nil, nil) header = abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err = simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{editValidatorMsg}, []uint64{0}, []uint64{1}, true, true, priv1) + _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{editValidatorMsg}, []uint64{0}, []uint64{1}, true, true, priv1) require.NoError(t, err) validator = checkValidator(t, app, sdk.ValAddress(addr1), true) @@ -100,7 +101,7 @@ func TestStakingMsgs(t *testing.T) { delegateMsg := staking.NewMsgDelegate(addr2, sdk.ValAddress(addr1), bondCoin) header = abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err = simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{delegateMsg}, []uint64{1}, []uint64{0}, true, true, priv2) + _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{delegateMsg}, []uint64{1}, []uint64{0}, true, true, priv2) require.NoError(t, err) simapp.CheckBalance(t, app, addr2, sdk.Coins{genCoin.Sub(bondCoin)}) @@ -109,7 +110,7 @@ func TestStakingMsgs(t *testing.T) { // begin unbonding beginUnbondingMsg := staking.NewMsgUndelegate(addr2, sdk.ValAddress(addr1), bondCoin) header = abci.Header{Height: app.LastBlockHeight() + 1} - _, _, err = simapp.SignCheckDeliver(t, app.Codec(), app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, []uint64{1}, []uint64{1}, true, true, priv2) + _, _, err = simapp.SignCheckDeliver(t, txGen, app.BaseApp, header, []sdk.Msg{beginUnbondingMsg}, []uint64{1}, []uint64{1}, true, true, priv2) require.NoError(t, err) // delegation should exist anymore diff --git a/x/staking/client/cli/cli_test.go b/x/staking/client/cli/cli_test.go index 24ee0026ce58..d479bd2414c2 100644 --- a/x/staking/client/cli/cli_test.go +++ b/x/staking/client/cli/cli_test.go @@ -39,9 +39,9 @@ func TestCLICreateValidator(t *testing.T) { require.True(f.T, success) require.Empty(f.T, stderr) - msg := cli.UnmarshalStdTx(f.T, f.Cdc, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) + msg := f.UnmarshalTxJSON(stdout) + require.NotZero(t, msg.GetGas()) + require.Equal(t, len(msg.GetMsgs()), 1) require.Equal(t, 0, len(msg.GetSignatures())) // Test --dry-run diff --git a/x/staking/client/testutil/helpers.go b/x/staking/client/testutil/helpers.go index b9694d2e93d5..a42b006e5c7e 100644 --- a/x/staking/client/testutil/helpers.go +++ b/x/staking/client/testutil/helpers.go @@ -37,7 +37,7 @@ func QueryStakingValidator(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...str var validator staking.Validator - err := f.Cdc.UnmarshalJSON([]byte(out), &validator) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &validator) require.NoError(f.T, err, "out %v\n, err %v", out, err) return validator @@ -50,7 +50,7 @@ func QueryStakingUnbondingDelegationsFrom(f *cli.Fixtures, valAddr sdk.ValAddres var ubds []staking.UnbondingDelegation - err := f.Cdc.UnmarshalJSON([]byte(out), &ubds) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &ubds) require.NoError(f.T, err, "out %v\n, err %v", out, err) return ubds @@ -63,7 +63,7 @@ func QueryStakingDelegationsTo(f *cli.Fixtures, valAddr sdk.ValAddress, flags .. var delegations []staking.Delegation - err := f.Cdc.UnmarshalJSON([]byte(out), &delegations) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &delegations) require.NoError(f.T, err, "out %v\n, err %v", out, err) return delegations @@ -76,7 +76,7 @@ func QueryStakingPool(f *cli.Fixtures, flags ...string) staking.Pool { var pool staking.Pool - err := f.Cdc.UnmarshalJSON([]byte(out), &pool) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), &pool) require.NoError(f.T, err, "out %v\n, err %v", out, err) return pool @@ -89,7 +89,7 @@ func QueryStakingParameters(f *cli.Fixtures, flags ...string) staking.Params { var params staking.Params - err := f.Cdc.UnmarshalJSON([]byte(out), ¶ms) + err := f.JSONMarshaler.UnmarshalJSON([]byte(out), ¶ms) require.NoError(f.T, err, "out %v\n, err %v", out, err) return params diff --git a/x/staking/legacy/v0_34/types.go b/x/staking/legacy/v0_34/types.go index 062fb3176044..009375cd3859 100644 --- a/x/staking/legacy/v0_34/types.go +++ b/x/staking/legacy/v0_34/types.go @@ -3,6 +3,7 @@ package v0_34 import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "time" "github.com/tendermint/tendermint/crypto" diff --git a/x/staking/legacy/v0_36/types.go b/x/staking/legacy/v0_36/types.go index 0f90d1de9678..f70271619939 100644 --- a/x/staking/legacy/v0_36/types.go +++ b/x/staking/legacy/v0_36/types.go @@ -3,6 +3,7 @@ package v0_36 import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "time" "github.com/tendermint/tendermint/crypto" diff --git a/x/staking/module.go b/x/staking/module.go index 693496db1bb2..4cac80fe234c 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -7,6 +7,8 @@ import ( "github.com/gogo/protobuf/grpc" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/gorilla/mux" "github.com/spf13/cobra" flag "github.com/spf13/pflag" @@ -31,6 +33,7 @@ var ( _ module.AppModule = AppModule{} _ module.AppModuleBasic = AppModuleBasic{} _ module.AppModuleSimulation = AppModule{} + _ module.InterfaceModule = AppModuleBasic{} ) // AppModuleBasic defines the basic application module used by the staking module. @@ -102,6 +105,10 @@ func (AppModuleBasic) BuildCreateValidatorMsg(clientCtx client.Context, return cli.BuildCreateValidatorMsg(clientCtx, txBldr) } +func (b AppModuleBasic) RegisterInterfaceTypes(registry cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + //____________________________________________________________________________ // AppModule implements an application module for the staking module. diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 67e26be1e810..50f556f071d4 100644 --- a/x/staking/simulation/decoder_test.go +++ b/x/staking/simulation/decoder_test.go @@ -2,6 +2,7 @@ package simulation_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "testing" "time" @@ -33,7 +34,7 @@ func makeTestCodec() (cdc *codec.Codec) { } func TestDecodeStore(t *testing.T) { - cdc, _ := simapp.MakeCodecs() + cdc, _, _ := simapp.MakeCodecs() dec := simulation.NewDecodeStore(cdc) bondTime := time.Now().UTC() diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index bcdc4ee3f4b5..46286ee2cf32 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -151,15 +151,8 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k msg := types.NewMsgCreateValidator(address, simAccount.PubKey, selfDelegation, description, commission, sdk.OneInt()) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -217,15 +210,8 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee msg := types.NewMsgEditValidator(address, description, &newCommissionRate, nil) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -285,15 +271,8 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K msg := types.NewMsgDelegate(simAccount.Address, val.GetOperator(), bondAmt) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -367,15 +346,8 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "unable to generate fees"), nil, err } - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { @@ -472,15 +444,8 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k sdk.NewCoin(k.BondDenom(ctx), redAmt), ) - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - helpers.DefaultGenTxGas, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - simAccount.PrivKey, - ) + txGen := simappparams.MakeEncodingConfig().TxGenerator + tx := helpers.GenTx(txGen, []sdk.Msg{msg}, fees, helpers.DefaultGenTxGas, chainID, []uint64{account.GetAccountNumber()}, []uint64{account.GetSequence()}, simAccount.PrivKey) _, _, err = app.Deliver(tx) if err != nil { diff --git a/x/staking/types/codec.go b/x/staking/types/codec.go index 3f402945d6ee..ad65f4b69881 100644 --- a/x/staking/types/codec.go +++ b/x/staking/types/codec.go @@ -2,8 +2,9 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/codec/legacy_global" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) // RegisterCodec registers the necessary x/staking interfaces and concrete types @@ -16,6 +17,16 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(&MsgBeginRedelegate{}, "cosmos-sdk/MsgBeginRedelegate", nil) } +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgCreateValidator{}, + &MsgEditValidator{}, + &MsgDelegate{}, + &MsgUndelegate{}, + &MsgBeginRedelegate{}, + ) +} + var ( amino = codec.New() diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index e914a87e8792..1b457d0133a1 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -1,6 +1,7 @@ package types import ( + "github.com/cosmos/cosmos-sdk/codec/legacy_global" "math/rand" "reflect" "sort"