Skip to content

Commit

Permalink
Merge branch 'main' into fix-allowance-typo
Browse files Browse the repository at this point in the history
  • Loading branch information
tac0turtle authored Apr 11, 2024
2 parents a5cbc0b + c56152d commit 971f6c8
Show file tree
Hide file tree
Showing 31 changed files with 946 additions and 143 deletions.
3 changes: 2 additions & 1 deletion client/v2/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,12 @@ Ref: https://keepachangelog.com/en/1.0.0/

* [#19618](https://github.com/cosmos/cosmos-sdk/pull/19618) Marshal enum as string in queries.
* [#19060](https://github.com/cosmos/cosmos-sdk/pull/19060) Use client context from root (or enhanced) command in autocli commands.
* Note, the given command must have a `client.Context` in its context.
* Note, the given command must have a `client.Context` in its context.
* [#19216](https://github.com/cosmos/cosmos-sdk/pull/19216) Do not overwrite TxConfig, use directly the one provided in context. TxConfig should always be set in the `client.Context` in `root.go` of an app.

### Bug Fixes

* [#19976](https://github.com/cosmos/cosmos-sdk/pull/19976) Add encoder for `cosmos.base.v1beta1.DecCoin`.
* [#19377](https://github.com/cosmos/cosmos-sdk/pull/19377) Partly fix comment parsing in autocli.
* [#19060](https://github.com/cosmos/cosmos-sdk/pull/19060) Simplify key flag parsing logic in flag handler.

Expand Down
40 changes: 40 additions & 0 deletions client/v2/autocli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,20 @@ import (
"context"
"fmt"
"io"
"strings"
"time"

autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
"cosmossdk.io/math"
"cosmossdk.io/x/tx/signing/aminojson"
"github.com/cockroachdb/errors"
"github.com/spf13/cobra"
"google.golang.org/protobuf/reflect/protoreflect"

"cosmossdk.io/client/v2/internal/flags"
"cosmossdk.io/client/v2/internal/util"

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

// BuildQueryCommand builds the query commands for all the provided modules. If a custom command is provided for a
Expand Down Expand Up @@ -182,5 +186,41 @@ func encoder(encoder aminojson.Encoder) aminojson.Encoder {

_, err := fmt.Fprintf(w, `"%s"`, (time.Duration(seconds)*time.Second + (time.Duration(nanos) * time.Nanosecond)).String())
return err
}).DefineTypeEncoding("cosmos.base.v1beta1.DecCoin", func(_ *aminojson.Encoder, msg protoreflect.Message, w io.Writer) error {
var (
denomName protoreflect.Name = "denom"
amountName protoreflect.Name = "amount"
)

fields := msg.Descriptor().Fields()
denomField := fields.ByName(denomName)
if denomField == nil {
return fmt.Errorf("expected denom field")
}

denom := msg.Get(denomField).String()

amountField := fields.ByName(amountName)
if amountField == nil {
return fmt.Errorf("expected amount field")
}

amount := msg.Get(amountField).String()
decimalPlace := len(amount) - math.LegacyPrecision
if decimalPlace > 0 {
amount = amount[:decimalPlace] + "." + amount[decimalPlace:]
} else if decimalPlace == 0 {
amount = "0." + amount
} else {
amount = "0." + strings.Repeat("0", -decimalPlace) + amount
}

amountDec, err := math.LegacyNewDecFromStr(amount)
if err != nil {
return fmt.Errorf("invalid amount: %s: %w", amount, err)
}

_, err = fmt.Fprintf(w, `"%s"`, sdk.NewDecCoinFromDec(denom, amountDec)) // TODO(@julienrbrt): Eventually remove this SDK dependency
return err
})
}
2 changes: 1 addition & 1 deletion core/transaction/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type ExecMode uint8
// For backwards compatibility and easier casting, the exec mode values must be the same as in cosmos/cosmos-sdk/types package.
const (
ExecModeCheck ExecMode = iota
_
ExecModeReCheck
ExecModeSimulate
_
_
Expand Down
19 changes: 16 additions & 3 deletions docs/build/building-modules/05-protobuf-annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,21 @@ Encoding instructs the amino json marshaler how to encode certain fields that ma
https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/bank/v1beta1/genesis.proto#L23
```

Another example is how `bytes` is encoded when using the amino json encoding format. The `bytes_as_string` option tells the json marshaler [how to encode bytes as string](https://github.com/pinosu/cosmos-sdk/blob/9879ece09c58068402782fa2096199dc89a23d13/x/tx/signing/aminojson/json_marshal.go#L75).
Another example is a protobuf `bytes` that contains a valid JSON document.
The `inline_json` option tells the json marshaler to embed the JSON bytes into the wrapping document without escaping.

```proto
(amino.encoding) = "bytes_as_string",
```
(amino.encoding) = "inline_json",
```

E.g. the bytes containing `{"foo":123}` in the `envelope` field would lead to the following JSON:

```json
{
"envelope": {
"foo": 123
}
}
```

If the bytes are not valid JSON, this leads to JSON broken documents. Thus a JSON validity check needs to be in place at some point of the process.
4 changes: 2 additions & 2 deletions simapp/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
circuitante.NewCircuitBreakerDecorator(options.CircuitKeeper),
ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
ante.NewValidateBasicDecorator(),
ante.NewValidateBasicDecorator(options.AccountKeeper.Environment()),
ante.NewTxTimeoutHeightDecorator(),
ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, options.TxManager),
ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, options.TxManager, options.AccountKeeper.Environment()),
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker),
Expand Down
6 changes: 4 additions & 2 deletions simapp/app_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,10 @@ var (
Config: appconfig.WrapAny(&slashingmodulev1.Module{}),
},
{
Name: "tx",
Config: appconfig.WrapAny(&txconfigv1.Config{}),
Name: "tx",
Config: appconfig.WrapAny(&txconfigv1.Config{
SkipAnteHandler: true, // SimApp is using non default AnteHandler such as circuit and unorderedtx decorators
}),
},
{
Name: genutiltypes.ModuleName,
Expand Down
28 changes: 28 additions & 0 deletions simapp/app_di.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/auth"
"cosmossdk.io/x/auth/ante"
"cosmossdk.io/x/auth/ante/unorderedtx"
authkeeper "cosmossdk.io/x/auth/keeper"
authsims "cosmossdk.io/x/auth/simulation"
Expand Down Expand Up @@ -292,13 +293,40 @@ func NewSimApp(
}
}

// set custom ante handlers
app.setCustomAnteHandler()

if err := app.Load(loadLatest); err != nil {
panic(err)
}

return app
}

// overwritte default ante handlers with custom ante handlers
// set SkipAnteHandler to true in app config and set custom ante handler on baseapp
func (app *SimApp) setCustomAnteHandler() {
anteHandler, err := NewAnteHandler(
HandlerOptions{
ante.HandlerOptions{
AccountKeeper: app.AuthKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: app.txConfig.SignModeHandler(),
FeegrantKeeper: app.FeeGrantKeeper,
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
},
&app.CircuitBreakerKeeper,
app.UnorderedTxManager,
},
)
if err != nil {
panic(err)
}

// Set the AnteHandler for the app
app.SetAnteHandler(anteHandler)
}

// Close implements the Application interface and closes all necessary application
// resources.
func (app *SimApp) Close() error {
Expand Down
6 changes: 3 additions & 3 deletions types/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ func (c Context) Logger() log.Logger { return c.logge
func (c Context) VoteInfos() []abci.VoteInfo { return c.voteInfo }
func (c Context) GasMeter() storetypes.GasMeter { return c.gasMeter }
func (c Context) BlockGasMeter() storetypes.GasMeter { return c.blockGasMeter }
func (c Context) IsCheckTx() bool { return c.checkTx } // Deprecated: use execMode instead
func (c Context) IsReCheckTx() bool { return c.recheckTx } // Deprecated: use execMode instead
func (c Context) IsCheckTx() bool { return c.checkTx } // Deprecated: use core/transaction service instead
func (c Context) IsReCheckTx() bool { return c.recheckTx } // Deprecated: use core/transaction service instead
func (c Context) IsSigverifyTx() bool { return c.sigverifyTx }
func (c Context) ExecMode() ExecMode { return c.execMode }
func (c Context) ExecMode() ExecMode { return c.execMode } // Deprecated: use core/transaction service instead
func (c Context) MinGasPrices() DecCoins { return c.minGasPrice }
func (c Context) EventManager() EventManagerI { return c.eventManager }
func (c Context) Priority() int64 { return c.priority }
Expand Down
89 changes: 89 additions & 0 deletions types/kv/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package kv_test

import (
"testing"

"github.com/stretchr/testify/assert"

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

func TestAssertKeyAtLeastLength(t *testing.T) {
cases := []struct {
name string
key []byte
length int
expectPanic bool
}{
{
name: "Store key length is less than the given length",
key: []byte("hello"),
length: 10,
expectPanic: true,
},
{
name: "Store key length is equal to the given length",
key: []byte("store-key"),
length: 9,
expectPanic: false,
},
{
name: "Store key length is greater than the given length",
key: []byte("unique"),
length: 3,
expectPanic: false,
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if tc.expectPanic {
assert.Panics(t, func() {
kv.AssertKeyAtLeastLength(tc.key, tc.length)
})
return
}
kv.AssertKeyAtLeastLength(tc.key, tc.length)
})
}
}

func TestAssertKeyLength(t *testing.T) {
cases := []struct {
name string
key []byte
length int
expectPanic bool
}{
{
name: "Store key length is less than the given length",
key: []byte("hello"),
length: 10,
expectPanic: true,
},
{
name: "Store key length is equal to the given length",
key: []byte("store-key"),
length: 9,
expectPanic: false,
},
{
name: "Store key length is greater than the given length",
key: []byte("unique"),
length: 3,
expectPanic: true,
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if tc.expectPanic {
assert.Panics(t, func() {
kv.AssertKeyLength(tc.key, tc.length)
})
return
}
kv.AssertKeyLength(tc.key, tc.length)
})
}
}
1 change: 1 addition & 0 deletions x/auth/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Improvements

* [#19967](https://github.com/cosmos/cosmos-sdk/pull/19967) Refactor ante handlers to use `transaction.Service` for getting exec mode.
* [#18780](https://github.com/cosmos/cosmos-sdk/pull/18780) Move sig verification out of the for loop, into the authenticate method.
* [#19188](https://github.com/cosmos/cosmos-sdk/pull/19188) Remove creation of `BaseAccount` when sending a message to an account that does not exist.
* When signing a transaction with an account that has not been created accountnumber 0 must be used
Expand Down
2 changes: 1 addition & 1 deletion x/auth/ante/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
anteDecorators := []sdk.AnteDecorator{
NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
NewValidateBasicDecorator(),
NewValidateBasicDecorator(options.AccountKeeper.Environment()),
NewTxTimeoutHeightDecorator(),
NewValidateMemoDecorator(options.AccountKeeper),
NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
Expand Down
26 changes: 17 additions & 9 deletions x/auth/ante/basic.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ante

import (
"cosmossdk.io/core/appmodule/v2"
"cosmossdk.io/core/transaction"
errorsmod "cosmossdk.io/errors"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/auth/migrations/legacytx"
Expand All @@ -18,15 +20,20 @@ import (
// If ValidateBasic passes, decorator calls next AnteHandler in chain. Note,
// ValidateBasicDecorator decorator will not get executed on ReCheckTx since it
// is not dependent on application state.
type ValidateBasicDecorator struct{}
type ValidateBasicDecorator struct {
env appmodule.Environment
}

func NewValidateBasicDecorator() ValidateBasicDecorator {
return ValidateBasicDecorator{}
func NewValidateBasicDecorator(env appmodule.Environment) ValidateBasicDecorator {
return ValidateBasicDecorator{
env: env,
}
}

func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, next sdk.AnteHandler) (sdk.Context, error) {
// no need to validate basic on recheck tx, call next antehandler
if ctx.ExecMode() == sdk.ExecModeReCheck {
txService := vbd.env.TransactionService
if txService.ExecMode(ctx) == transaction.ExecModeReCheck {
return next(ctx, tx, false)
}

Expand All @@ -36,7 +43,7 @@ func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool,
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// ValidateMemoDecorator will validate memo given the parameters passed in
Expand Down Expand Up @@ -69,7 +76,7 @@ func (vmd ValidateMemoDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool,
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// ConsumeTxSizeGasDecorator will take in parameters and consume gas proportional
Expand Down Expand Up @@ -101,7 +108,8 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ b
ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*storetypes.Gas(len(ctx.TxBytes())), "txSize")

// simulate gas cost for signatures in simulate mode
if ctx.ExecMode() == sdk.ExecModeSimulate {
txService := cgts.ak.Environment().TransactionService
if txService.ExecMode(ctx) == transaction.ExecModeSimulate {
// in simulate mode, each element should be a nil signature
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
Expand Down Expand Up @@ -143,7 +151,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ b
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// isIncompleteSignature tests whether SignatureData is fully filled in for simulation purposes
Expand Down Expand Up @@ -206,5 +214,5 @@ func (txh TxTimeoutHeightDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ boo
)
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}
2 changes: 1 addition & 1 deletion x/auth/ante/basic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestValidateBasic(t *testing.T) {
invalidTx, err := suite.CreateTestTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), signing.SignMode_SIGN_MODE_DIRECT)
require.NoError(t, err)

vbd := ante.NewValidateBasicDecorator()
vbd := ante.NewValidateBasicDecorator(suite.accountKeeper.Environment())
antehandler := sdk.ChainAnteDecorators(vbd)
_, err = antehandler(suite.ctx, invalidTx, false)

Expand Down
Loading

0 comments on commit 971f6c8

Please sign in to comment.