@agoric/cosmos 0.34.1 → 0.34.2-dev-8c14632.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Makefile CHANGED
@@ -76,13 +76,12 @@ compile-helper: go-mod-cache
76
76
 
77
77
  compile-libdaemon: go-mod-cache
78
78
  go build -v $(MOD_READONLY) $(BUILD_FLAGS) -buildmode=c-shared -o build/libagcosmosdaemon.so ./cmd/libdaemon/main.go
79
- test "`uname -s 2>/dev/null`" != Darwin || install_name_tool -id $$PWD/build/libagcosmosdaemon.so build/libagcosmosdaemon.so
80
79
 
81
- go-mod-cache: ../../go.sum
80
+ go-mod-cache: go.sum
82
81
  @echo "--> Download go modules to local cache"
83
82
  @go mod download
84
83
 
85
- ../../go.sum: ../../go.mod
84
+ go.sum: go.mod
86
85
  @echo "--> Ensure dependencies have not been modified"
87
86
  GO111MODULE=on go mod verify
88
87
 
@@ -0,0 +1,35 @@
1
+ package agoric
2
+
3
+ import (
4
+ sdk "github.com/cosmos/cosmos-sdk/types"
5
+ )
6
+
7
+ const (
8
+ // Bech32MainPrefix defines the Bech32 prefix used by all types
9
+ Bech32MainPrefix = "agoric"
10
+
11
+ // CoinType is used in the slip44 HD key derivation path.
12
+ // https://github.com/satoshilabs/slips/blob/master/slip-0044.md
13
+ CoinType = 564
14
+
15
+ // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address
16
+ Bech32PrefixAccAddr = Bech32MainPrefix
17
+ // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
18
+ Bech32PrefixAccPub = Bech32MainPrefix + sdk.PrefixPublic
19
+ // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
20
+ Bech32PrefixValAddr = Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixOperator
21
+ // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
22
+ Bech32PrefixValPub = Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixOperator + sdk.PrefixPublic
23
+ // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
24
+ Bech32PrefixConsAddr = Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus
25
+ // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
26
+ Bech32PrefixConsPub = Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic
27
+ )
28
+
29
+ // SetAgoricConfig sets the appropriate parameters for the Agoric chain.
30
+ func SetAgoricConfig(config *sdk.Config) {
31
+ config.SetCoinType(CoinType)
32
+ config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub)
33
+ config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub)
34
+ config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub)
35
+ }
package/ante/ante.go ADDED
@@ -0,0 +1,65 @@
1
+ package ante
2
+
3
+ import (
4
+ sdk "github.com/cosmos/cosmos-sdk/types"
5
+ sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
6
+ "github.com/cosmos/cosmos-sdk/x/auth/ante"
7
+ ibcante "github.com/cosmos/ibc-go/v3/modules/core/ante"
8
+ ibckeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper"
9
+ )
10
+
11
+ // HandlerOptions extend the SDK's AnteHandler options by requiring the IBC
12
+ // channel keeper.
13
+ type HandlerOptions struct {
14
+ ante.HandlerOptions
15
+
16
+ IBCKeeper *ibckeeper.Keeper
17
+ FeeCollectorName string
18
+ AdmissionData interface{}
19
+ SwingsetKeeper SwingsetKeeper
20
+ }
21
+
22
+ func NewAnteHandler(opts HandlerOptions) (sdk.AnteHandler, error) {
23
+ if opts.AccountKeeper == nil {
24
+ return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler")
25
+ }
26
+ if opts.BankKeeper == nil {
27
+ return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler")
28
+ }
29
+ if opts.SignModeHandler == nil {
30
+ return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder")
31
+ }
32
+ if opts.AdmissionData == nil {
33
+ return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "admission data is required for AnteHandler")
34
+ }
35
+ if opts.SwingsetKeeper == nil {
36
+ return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "swingset keeper is required for AnteHandler")
37
+ }
38
+
39
+ var sigGasConsumer = opts.SigGasConsumer
40
+ if sigGasConsumer == nil {
41
+ sigGasConsumer = ante.DefaultSigVerificationGasConsumer
42
+ }
43
+
44
+ anteDecorators := []sdk.AnteDecorator{
45
+ ante.NewSetUpContextDecorator(),
46
+ ante.NewRejectExtensionOptionsDecorator(),
47
+ ante.NewMempoolFeeDecorator(),
48
+ ante.NewValidateBasicDecorator(),
49
+ ante.NewTxTimeoutHeightDecorator(),
50
+ ante.NewValidateMemoDecorator(opts.AccountKeeper),
51
+ ante.NewConsumeGasForTxSizeDecorator(opts.AccountKeeper),
52
+ NewInboundDecorator(opts.SwingsetKeeper),
53
+ NewDeductFeeDecorator(opts.AccountKeeper, opts.BankKeeper, opts.FeegrantKeeper, opts.FeeCollectorName),
54
+ // SetPubKeyDecorator must be called before all signature verification decorators
55
+ ante.NewSetPubKeyDecorator(opts.AccountKeeper),
56
+ ante.NewValidateSigCountDecorator(opts.AccountKeeper),
57
+ ante.NewSigGasConsumeDecorator(opts.AccountKeeper, sigGasConsumer),
58
+ ante.NewSigVerificationDecorator(opts.AccountKeeper, opts.SignModeHandler),
59
+ NewAdmissionDecorator(opts.AdmissionData),
60
+ ante.NewIncrementSequenceDecorator(opts.AccountKeeper),
61
+ ibcante.NewAnteDecorator(opts.IBCKeeper),
62
+ }
63
+
64
+ return sdk.ChainAnteDecorators(anteDecorators...), nil
65
+ }
@@ -0,0 +1,26 @@
1
+ package ante
2
+
3
+ import (
4
+ swingtypes "github.com/Agoric/agoric-sdk/golang/cosmos/x/swingset/types"
5
+ sdk "github.com/cosmos/cosmos-sdk/types"
6
+ authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
7
+ )
8
+
9
+ // AccountKeeper defines the contract needed for AccountKeeper related APIs.
10
+ // Interface provides support to use non-sdk AccountKeeper for AnteHandler's decorators.
11
+ type AccountKeeper interface {
12
+ GetParams(ctx sdk.Context) (params authtypes.Params)
13
+ GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI
14
+ SetAccount(ctx sdk.Context, acc authtypes.AccountI)
15
+ GetModuleAddress(moduleName string) sdk.AccAddress
16
+ }
17
+
18
+ // FeegrantKeeper defines the expected feegrant keeper.
19
+ type FeegrantKeeper interface {
20
+ UseGrantedFees(ctx sdk.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error
21
+ }
22
+
23
+ type SwingsetKeeper interface {
24
+ InboundQueueLength(ctx sdk.Context) (int32, error)
25
+ GetState(ctx sdk.Context) swingtypes.State
26
+ }
package/ante/fee.go ADDED
@@ -0,0 +1,96 @@
1
+ package ante
2
+
3
+ import (
4
+ "fmt"
5
+
6
+ sdk "github.com/cosmos/cosmos-sdk/types"
7
+ sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
8
+ "github.com/cosmos/cosmos-sdk/x/auth/types"
9
+ )
10
+
11
+ // DeductFeeDecorator deducts fees from the first signer of the tx
12
+ // If the first signer does not have the funds to pay for the fees, return with InsufficientFunds error
13
+ // Call next AnteHandler if fees successfully deducted
14
+ // CONTRACT: Tx must implement FeeTx interface to use DeductFeeDecorator
15
+ type DeductFeeDecorator struct {
16
+ ak AccountKeeper
17
+ bankKeeper types.BankKeeper
18
+ feegrantKeeper FeegrantKeeper
19
+ feeCollectorName string
20
+ }
21
+
22
+ func NewDeductFeeDecorator(ak AccountKeeper, bk types.BankKeeper, fk FeegrantKeeper, feeCollectorName string) DeductFeeDecorator {
23
+ return DeductFeeDecorator{
24
+ ak: ak,
25
+ bankKeeper: bk,
26
+ feegrantKeeper: fk,
27
+ feeCollectorName: feeCollectorName,
28
+ }
29
+ }
30
+
31
+ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
32
+ feeTx, ok := tx.(sdk.FeeTx)
33
+ if !ok {
34
+ return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx")
35
+ }
36
+
37
+ if addr := dfd.ak.GetModuleAddress(dfd.feeCollectorName); addr == nil {
38
+ return ctx, fmt.Errorf("Fee collector module account (%s) has not been set", dfd.feeCollectorName)
39
+ }
40
+
41
+ fee := feeTx.GetFee()
42
+ feePayer := feeTx.FeePayer()
43
+ feeGranter := feeTx.FeeGranter()
44
+
45
+ deductFeesFrom := feePayer
46
+
47
+ // if feegranter set deduct fee from feegranter account.
48
+ // this works with only when feegrant enabled.
49
+ if feeGranter != nil {
50
+ if dfd.feegrantKeeper == nil {
51
+ return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "fee grants are not enabled")
52
+ } else if !feeGranter.Equals(feePayer) {
53
+ err := dfd.feegrantKeeper.UseGrantedFees(ctx, feeGranter, feePayer, fee, tx.GetMsgs())
54
+
55
+ if err != nil {
56
+ return ctx, sdkerrors.Wrapf(err, "%s not allowed to pay fees from %s", feeGranter, feePayer)
57
+ }
58
+ }
59
+
60
+ deductFeesFrom = feeGranter
61
+ }
62
+
63
+ deductFeesFromAcc := dfd.ak.GetAccount(ctx, deductFeesFrom)
64
+ if deductFeesFromAcc == nil {
65
+ return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "fee payer address: %s does not exist", deductFeesFrom)
66
+ }
67
+
68
+ // deduct the fees
69
+ if !feeTx.GetFee().IsZero() {
70
+ err = DeductFees(dfd.bankKeeper, ctx, deductFeesFromAcc, feeTx.GetFee(), dfd.feeCollectorName)
71
+ if err != nil {
72
+ return ctx, err
73
+ }
74
+ }
75
+
76
+ events := sdk.Events{sdk.NewEvent(sdk.EventTypeTx,
77
+ sdk.NewAttribute(sdk.AttributeKeyFee, feeTx.GetFee().String()),
78
+ )}
79
+ ctx.EventManager().EmitEvents(events)
80
+
81
+ return next(ctx, tx, simulate)
82
+ }
83
+
84
+ // DeductFees deducts fees from the given account.
85
+ func DeductFees(bankKeeper types.BankKeeper, ctx sdk.Context, acc types.AccountI, fees sdk.Coins, feeCollectorName string) error {
86
+ if !fees.IsValid() {
87
+ return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFee, "invalid fee amount: %s", fees)
88
+ }
89
+
90
+ err := bankKeeper.SendCoinsFromAccountToModule(ctx, acc.GetAddress(), feeCollectorName, fees)
91
+ if err != nil {
92
+ return sdkerrors.Wrapf(sdkerrors.ErrInsufficientFunds, err.Error())
93
+ }
94
+
95
+ return nil
96
+ }
@@ -0,0 +1,137 @@
1
+ package ante
2
+
3
+ import (
4
+ "github.com/armon/go-metrics"
5
+
6
+ "github.com/cosmos/cosmos-sdk/telemetry"
7
+ sdk "github.com/cosmos/cosmos-sdk/types"
8
+ sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
9
+
10
+ "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
11
+ swingtypes "github.com/Agoric/agoric-sdk/golang/cosmos/x/swingset/types"
12
+ )
13
+
14
+ /*
15
+ This AnteDecorator enforces a limit on the size of the Swingset inbound queue
16
+ by scanning for Cosmos-messages which end up on Swingset's message queues. Note
17
+ that when running DeliverTx, inbound messages are placed in either the
18
+ actionQueue or the highPriorityQueue (forming the Swingset inbound queue),
19
+ and kept there until processed by SwingSet. Previous Txs in the block will have
20
+ already been added to the inbound queue, so we must reject Txs which would grow
21
+ the actionQueue beyond the allowed inbound size. Additions to the
22
+ highPriorityQueue are exempt of inbound queue size checks but count towards the
23
+ overall inbound queue size, which means the inbound queue can "overflow" its
24
+ limits when adding high priority actions.
25
+
26
+ We would like to reject messages during mempool admission (CheckTx)
27
+ rather than during block execution (DeliverTx), but at CheckTx time
28
+ we don't know how many messages will be allowed at DeliverTx time,
29
+ nor the size of the inbound queue from preceding Txs in the block.
30
+ To mitigate this, x/swingset implements an hysteresis by computing
31
+ the number of messages allowed for mempool admission as if its max
32
+ queue length was lower (e.g. 50%). This is the QueueInboundMempool
33
+ entry in the Swingset state QueueAllowed field. At DeliverTx time
34
+ the QueueInbound entry gives the number of allowed messages.
35
+ */
36
+
37
+ const (
38
+ maxInboundPerTx = 1
39
+ )
40
+
41
+ // TODO: We don't have a more appropriate error type for this.
42
+ var ErrInboundQueueFull = sdkerrors.ErrMempoolIsFull
43
+
44
+ // inboundAnte is an sdk.AnteDecorator which enforces the allowed size of the inbound queue.
45
+ type inboundAnte struct {
46
+ sk SwingsetKeeper
47
+ }
48
+
49
+ // NewInboundDecorator returns an AnteDecorator which honors the allowed size of the inbound queue.
50
+ func NewInboundDecorator(sk SwingsetKeeper) sdk.AnteDecorator {
51
+ return inboundAnte{sk: sk}
52
+ }
53
+
54
+ // AnteHandle implements sdk.AnteDecorator.
55
+ // Lazily consults the Swingset state to avoid overhead when dealing
56
+ // with pure Cosmos-level Txs.
57
+ func (ia inboundAnte) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
58
+ msgs := tx.GetMsgs()
59
+ inboundsAllowed := int32(-1)
60
+ for _, msg := range msgs {
61
+ inbounds := inboundMessages(msg)
62
+ if inbounds == 0 {
63
+ continue
64
+ }
65
+ if inboundsAllowed == -1 {
66
+ var err error
67
+ inboundsAllowed, err = ia.allowedInbound(ctx)
68
+ if err != nil {
69
+ return ctx, err
70
+ }
71
+ }
72
+ isHighPriority, err := ia.isPriorityMessage(ctx, msg)
73
+ if err != nil {
74
+ return ctx, err
75
+ }
76
+ if inboundsAllowed >= inbounds {
77
+ inboundsAllowed -= inbounds
78
+ } else if isHighPriority {
79
+ inboundsAllowed = 0
80
+ } else {
81
+ defer func() {
82
+ telemetry.IncrCounterWithLabels(
83
+ []string{"tx", "ante", "inbound_not_allowed"},
84
+ 1,
85
+ []metrics.Label{
86
+ telemetry.NewLabel("msg", sdk.MsgTypeURL(msg)),
87
+ },
88
+ )
89
+ }()
90
+ return ctx, ErrInboundQueueFull
91
+ }
92
+ }
93
+ return next(ctx, tx, simulate)
94
+ }
95
+
96
+ func (ia inboundAnte) isPriorityMessage(ctx sdk.Context, msg sdk.Msg) (bool, error) {
97
+ if c, ok := msg.(vm.ControllerAdmissionMsg); ok {
98
+ return c.IsHighPriority(ctx, ia.sk)
99
+ }
100
+ return false, nil
101
+ }
102
+
103
+ // allowedInbound returns the allowed number of inbound queue messages or an error.
104
+ // Look up the limit from the swingset state queue sizes: from QueueInboundMempool
105
+ // if we're running CheckTx (for the hysteresis described above), otherwise QueueAllowed.
106
+ func (ia inboundAnte) allowedInbound(ctx sdk.Context) (int32, error) {
107
+ state := ia.sk.GetState(ctx)
108
+ entry := swingtypes.QueueInbound
109
+ if ctx.IsCheckTx() {
110
+ entry = swingtypes.QueueInboundMempool
111
+ }
112
+ allowed, found := swingtypes.QueueSizeEntry(state.QueueAllowed, entry)
113
+ if !found {
114
+ // if number of allowed entries not given, fail closed
115
+ return 0, nil
116
+ }
117
+ actions, err := ia.sk.InboundQueueLength(ctx)
118
+ if err != nil {
119
+ return 0, err
120
+ }
121
+ if actions >= allowed {
122
+ return 0, nil
123
+ }
124
+ allowed -= actions
125
+ if allowed > maxInboundPerTx {
126
+ return maxInboundPerTx, nil
127
+ }
128
+ return allowed, nil
129
+ }
130
+
131
+ // inboundMessages returns the nunber of inbound queue messages in msg.
132
+ func inboundMessages(msg sdk.Msg) int32 {
133
+ if c, ok := msg.(vm.ControllerAdmissionMsg); ok {
134
+ return c.GetInboundMsgCount()
135
+ }
136
+ return 0
137
+ }
@@ -0,0 +1,219 @@
1
+ package ante
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "reflect"
7
+ "testing"
8
+
9
+ swingtypes "github.com/Agoric/agoric-sdk/golang/cosmos/x/swingset/types"
10
+ "github.com/cosmos/cosmos-sdk/codec/types"
11
+ sdk "github.com/cosmos/cosmos-sdk/types"
12
+ "github.com/cosmos/cosmos-sdk/types/tx"
13
+ banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
14
+ "github.com/gogo/protobuf/proto"
15
+ )
16
+
17
+ func TestInboundAnteHandle(t *testing.T) {
18
+ for _, tt := range []struct {
19
+ name string
20
+ checkTx bool
21
+ tx sdk.Tx
22
+ simulate bool
23
+ inboundQueueLength int32
24
+ inboundQueueLengthErr error
25
+ inboundLimit int32
26
+ mempoolLimit int32
27
+ errMsg string
28
+ isHighPriorityOwner bool
29
+ }{
30
+ {
31
+ name: "empty-empty",
32
+ tx: makeTestTx(),
33
+ },
34
+ {
35
+ name: "reject-on-zero-allowed",
36
+ tx: makeTestTx(&swingtypes.MsgDeliverInbound{}),
37
+ errMsg: ErrInboundQueueFull.Error(),
38
+ },
39
+ {
40
+ name: "has-room",
41
+ tx: makeTestTx(&swingtypes.MsgInstallBundle{}),
42
+ inboundLimit: 10,
43
+ inboundQueueLength: 8,
44
+ },
45
+ {
46
+ name: "at-limit",
47
+ tx: makeTestTx(&swingtypes.MsgInstallBundle{}),
48
+ inboundLimit: 10,
49
+ inboundQueueLength: 9,
50
+ },
51
+ {
52
+ name: "no-room",
53
+ tx: makeTestTx(&swingtypes.MsgProvision{}),
54
+ inboundLimit: 10,
55
+ inboundQueueLength: 10,
56
+ errMsg: ErrInboundQueueFull.Error(),
57
+ },
58
+ {
59
+ name: "state-lookup-error",
60
+ tx: makeTestTx(&swingtypes.MsgWalletAction{}, &swingtypes.MsgWalletSpendAction{}),
61
+ inboundLimit: 10,
62
+ inboundQueueLengthErr: fmt.Errorf("sunspots"),
63
+ errMsg: "sunspots",
64
+ },
65
+ {
66
+ name: "allow-non-swingset-msgs",
67
+ tx: makeTestTx(&banktypes.MsgSend{}, &banktypes.MsgSend{}),
68
+ inboundLimit: 1,
69
+ },
70
+ {
71
+ name: "lazy-queue-length-lookup",
72
+ tx: makeTestTx(&banktypes.MsgSend{}, &banktypes.MsgSend{}),
73
+ inboundLimit: 1,
74
+ inboundQueueLengthErr: fmt.Errorf("sunspots"),
75
+ },
76
+ {
77
+ name: "checktx",
78
+ checkTx: true,
79
+ tx: makeTestTx(&swingtypes.MsgDeliverInbound{}),
80
+ inboundLimit: 10,
81
+ mempoolLimit: 5,
82
+ inboundQueueLength: 7,
83
+ errMsg: ErrInboundQueueFull.Error(),
84
+ },
85
+ {
86
+ name: "empty-queue-allowed",
87
+ tx: makeTestTx(&swingtypes.MsgInstallBundle{}),
88
+ inboundLimit: -1,
89
+ errMsg: ErrInboundQueueFull.Error(),
90
+ },
91
+ {
92
+ name: "already-full",
93
+ tx: makeTestTx(&swingtypes.MsgProvision{}),
94
+ inboundLimit: 10,
95
+ inboundQueueLength: 10,
96
+ errMsg: ErrInboundQueueFull.Error(),
97
+ },
98
+ {
99
+ name: "max-per-tx",
100
+ tx: makeTestTx(&swingtypes.MsgWalletAction{}, &swingtypes.MsgWalletSpendAction{}),
101
+ inboundLimit: 10,
102
+ inboundQueueLength: 5,
103
+ errMsg: ErrInboundQueueFull.Error(),
104
+ },
105
+ {
106
+ name: "priority-limit-bypass",
107
+ tx: makeTestTx(&swingtypes.MsgWalletSpendAction{}),
108
+ isHighPriorityOwner: true,
109
+ },
110
+ {
111
+ name: "priority-multi-bypass",
112
+ tx: makeTestTx(&swingtypes.MsgWalletSpendAction{}, &swingtypes.MsgWalletSpendAction{}),
113
+ isHighPriorityOwner: true,
114
+ },
115
+ {
116
+ name: "mixed-priority-limit-first-fail",
117
+ tx: makeTestTx(&swingtypes.MsgWalletSpendAction{}, &swingtypes.MsgProvision{}),
118
+ isHighPriorityOwner: true,
119
+ inboundLimit: 1,
120
+ errMsg: ErrInboundQueueFull.Error(),
121
+ },
122
+ {
123
+ name: "mixed-priority-limit-last-succeed",
124
+ tx: makeTestTx(&swingtypes.MsgProvision{}, &swingtypes.MsgWalletSpendAction{}),
125
+ isHighPriorityOwner: true,
126
+ inboundLimit: 1,
127
+ },
128
+ } {
129
+ t.Run(tt.name, func(t *testing.T) {
130
+ ctx := sdk.Context{}.WithContext(context.Background()).WithIsCheckTx(tt.checkTx)
131
+ emptyQueueAllowed := false
132
+ if tt.inboundLimit == -1 {
133
+ emptyQueueAllowed = true
134
+ }
135
+ mock := mockSwingsetKeeper{
136
+ inboundQueueLength: tt.inboundQueueLength,
137
+ inboundQueueLengthErr: tt.inboundQueueLengthErr,
138
+ inboundLimit: tt.inboundLimit,
139
+ mempoolLimit: tt.mempoolLimit,
140
+ emptyQueueAllowed: emptyQueueAllowed,
141
+ isHighPriorityOwner: tt.isHighPriorityOwner,
142
+ }
143
+ decorator := NewInboundDecorator(mock)
144
+ newCtx, err := decorator.AnteHandle(ctx, tt.tx, tt.simulate, nilAnteHandler)
145
+ if !reflect.DeepEqual(newCtx, ctx) {
146
+ t.Errorf("want ctx %v, got %v", ctx, newCtx)
147
+ }
148
+ if err != nil {
149
+ if tt.errMsg == "" {
150
+ t.Errorf("want no error, got %s", err.Error())
151
+ } else if err.Error() != tt.errMsg {
152
+ t.Errorf("want error %s, got %s", tt.errMsg, err.Error())
153
+ }
154
+ } else if tt.errMsg != "" {
155
+ t.Errorf("want error %s, got none", tt.errMsg)
156
+ }
157
+ })
158
+ }
159
+ }
160
+
161
+ func makeTestTx(msgs ...proto.Message) sdk.Tx {
162
+ wrappedMsgs := make([]*types.Any, len(msgs))
163
+ for i, m := range msgs {
164
+ any, err := types.NewAnyWithValue(m)
165
+ if err != nil {
166
+ panic(err)
167
+ }
168
+ wrappedMsgs[i] = any
169
+ }
170
+ return &tx.Tx{
171
+ Body: &tx.TxBody{
172
+ Messages: wrappedMsgs,
173
+ },
174
+ }
175
+ }
176
+
177
+ func nilAnteHandler(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
178
+ return ctx, nil
179
+ }
180
+
181
+ type mockSwingsetKeeper struct {
182
+ inboundQueueLength int32
183
+ inboundQueueLengthErr error
184
+ inboundLimit int32
185
+ mempoolLimit int32
186
+ emptyQueueAllowed bool
187
+ isHighPriorityOwner bool
188
+ }
189
+
190
+ var _ SwingsetKeeper = mockSwingsetKeeper{}
191
+ var _ swingtypes.SwingSetKeeper = mockSwingsetKeeper{}
192
+
193
+ func (msk mockSwingsetKeeper) InboundQueueLength(ctx sdk.Context) (int32, error) {
194
+ return msk.inboundQueueLength, msk.inboundQueueLengthErr
195
+ }
196
+
197
+ func (msk mockSwingsetKeeper) GetState(ctx sdk.Context) swingtypes.State {
198
+ if msk.emptyQueueAllowed {
199
+ return swingtypes.State{}
200
+ }
201
+ return swingtypes.State{
202
+ QueueAllowed: []swingtypes.QueueSize{
203
+ swingtypes.NewQueueSize(swingtypes.QueueInbound, msk.inboundLimit),
204
+ swingtypes.NewQueueSize(swingtypes.QueueInboundMempool, msk.mempoolLimit),
205
+ },
206
+ }
207
+ }
208
+
209
+ func (msk mockSwingsetKeeper) IsHighPriorityAddress(ctx sdk.Context, addr sdk.AccAddress) (bool, error) {
210
+ return msk.isHighPriorityOwner, nil
211
+ }
212
+
213
+ func (msk mockSwingsetKeeper) GetBeansPerUnit(ctx sdk.Context) map[string]sdk.Uint {
214
+ return nil
215
+ }
216
+
217
+ func (msk mockSwingsetKeeper) ChargeBeans(ctx sdk.Context, addr sdk.AccAddress, beans sdk.Uint) error {
218
+ return fmt.Errorf("not implemented")
219
+ }
@@ -0,0 +1,64 @@
1
+ package ante
2
+
3
+ import (
4
+ "github.com/armon/go-metrics"
5
+
6
+ "github.com/cosmos/cosmos-sdk/telemetry"
7
+ sdk "github.com/cosmos/cosmos-sdk/types"
8
+ sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
9
+
10
+ "github.com/Agoric/agoric-sdk/golang/cosmos/vm"
11
+ )
12
+
13
+ // TODO: We don't have a more appropriate error type for this.
14
+ var ErrAdmissionRefused = sdkerrors.ErrMempoolIsFull
15
+
16
+ // AdmissionDecorator will ask the Controller (such as SwingSet) if it is
17
+ // temporarily rejecting inbound messages. If CheckAdmissibility passes for all
18
+ // messages, decorator calls next AnteHandler in chain.
19
+ type AdmissionDecorator struct {
20
+ data interface{}
21
+ }
22
+
23
+ func NewAdmissionDecorator(data interface{}) AdmissionDecorator {
24
+ return AdmissionDecorator{data: data}
25
+ }
26
+
27
+ // AnteHandle calls CheckAdmissibility for all messages that implement the
28
+ // vm.ControllerAdmissionMsg interface. If it returns an error, refuse the
29
+ // entire transaction.
30
+ func (ad AdmissionDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
31
+ msgs := tx.GetMsgs()
32
+ errors := make([]error, 0, len(msgs))
33
+
34
+ // Ask the controller if we are rejecting messages.
35
+ for _, msg := range tx.GetMsgs() {
36
+ if camsg, ok := msg.(vm.ControllerAdmissionMsg); ok {
37
+ if err := camsg.CheckAdmissibility(ctx, ad.data); err != nil {
38
+ // Only let admission errors interrupt the transaction if we're not
39
+ // simulating, otherwise our gas estimation will be too low.
40
+ if !simulate {
41
+ errors = append(errors, err)
42
+ defer func(msg sdk.Msg) {
43
+ telemetry.IncrCounterWithLabels(
44
+ []string{"tx", "ante", "admission_refused"},
45
+ 1,
46
+ []metrics.Label{
47
+ telemetry.NewLabel("msg", sdk.MsgTypeURL(msg)),
48
+ },
49
+ )
50
+ }(msg)
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ numErrors := len(errors)
57
+ if numErrors > 0 {
58
+ // Add to instrumentation.
59
+
60
+ return ctx, sdkerrors.Wrapf(ErrAdmissionRefused, "controller refused message admission: %s", errors[0].Error())
61
+ }
62
+
63
+ return next(ctx, tx, simulate)
64
+ }