-
Notifications
You must be signed in to change notification settings - Fork 41
/
ante.go
566 lines (470 loc) · 14.1 KB
/
ante.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
package smartaccount
import (
"encoding/json"
"fmt"
errorsmod "cosmossdk.io/errors"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
sakeeper "github.com/aura-nw/aura/x/smartaccount/keeper"
"github.com/aura-nw/aura/x/smartaccount/types"
typesv1 "github.com/aura-nw/aura/x/smartaccount/types/v1beta1"
sdk "github.com/cosmos/cosmos-sdk/types"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authz "github.com/cosmos/cosmos-sdk/x/authz"
)
// Return tx' signer as SmartAccount, if not return nil
func GetSmartAccountTxSigner(ctx sdk.Context, sigTx authsigning.SigVerifiableTx, saKeeper sakeeper.Keeper) (*typesv1.SmartAccount, error) {
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
return nil, err
}
signerAddrs := sigTx.GetSigners()
// signer of smartaccount tx must stand alone
if len(signerAddrs) != 1 || len(sigs) != 1 {
return nil, nil
}
saAcc, err := saKeeper.GetSmartAccountByAddress(ctx, signerAddrs[0])
if err != nil {
return nil, err
}
return saAcc, nil
}
func GetValidActivateAccountMessage(sigTx authsigning.SigVerifiableTx) (*typesv1.MsgActivateAccount, error) {
msgs := sigTx.GetMsgs()
if len(msgs) != 1 {
// smart account activation message must stand alone
// it will prevent bundling of multiple messages with the activating message as the first message to avoid AnteHandler check
for _, msg := range msgs {
if _, ok := msg.(*typesv1.MsgActivateAccount); ok {
return nil, errorsmod.Wrap(types.ErrInvalidTx, "smart account activation message must stand alone")
}
}
return nil, nil
}
activateMsg, ok := msgs[0].(*typesv1.MsgActivateAccount)
if !ok {
return nil, nil
}
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
return nil, err
}
signer := sigTx.GetSigners()
// do not allow multi signer and signature
if len(signer) != 1 || len(sigs) != 1 {
return nil, errorsmod.Wrap(types.ErrInvalidTx, "smart-account activation tx does not allow multiple signers")
}
return activateMsg, nil
}
// ------------------------- SmartAccount Decorator ------------------------- \\
type SmartAccountDecorator struct {
SaKeeper sakeeper.Keeper
}
func NewSmartAccountDecorator(saKeeper sakeeper.Keeper) *SmartAccountDecorator {
return &SmartAccountDecorator{
SaKeeper: saKeeper,
}
}
// AnteHandle is used for performing basic validity checks on a transaction such that it can be thrown out of the mempool.
func (d *SmartAccountDecorator) AnteHandle(
ctx sdk.Context,
tx sdk.Tx,
simulate bool,
next sdk.AnteHandler,
) (newCtx sdk.Context, err error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, errorsmod.Wrap(types.ErrInvalidTx, "not a SigVerifiableTx")
}
feeTx, ok := tx.(sdk.FeeTx)
if !ok {
return ctx, errorsmod.Wrap(types.ErrInvalidTx, "not a FeeTx")
}
activateMsg, err := GetValidActivateAccountMessage(sigTx)
if err != nil {
return ctx, err
}
if activateMsg == nil {
err = handleSmartAccountTx(ctx, d.SaKeeper, sigTx, feeTx, simulate)
if err != nil {
return ctx, err
}
} else {
err = handleSmartAccountActivate(ctx, d.SaKeeper, activateMsg, simulate)
if err != nil {
return ctx, err
}
}
return next(ctx, tx, simulate)
}
func handleSmartAccountTx(
ctx sdk.Context,
saKeeper sakeeper.Keeper,
sigTx authsigning.SigVerifiableTx,
feeTx sdk.FeeTx,
simulate bool,
) error {
signerAcc, err := GetSmartAccountTxSigner(ctx, sigTx, saKeeper)
if err != nil {
return err
}
// if is not smartaccount tx type
if signerAcc == nil {
// do some thing
return nil
}
// save the account address to the module store. we will need it in the
// posthandler
//
// TODO: a question is that instead of writing to store, can we just put this
// in memory instead. in practice however, the address is deleted in the post
// handler, so it's never actually written to disk, meaning the difference in
// gas consumption should be really small. still worth investigating tho.
// referenced from Larry0x' abstractaccount AnteHandler:
// https://github.com/larry0x/abstract-account/blob/b3c6432e593d450e7c58dae94cdf2a95930f8159/x/abstractaccount/ante.go#L81
saKeeper.SetSignerAddress(ctx, signerAcc.GetAddress())
msgs := sigTx.GetMsgs()
// check if tx messages is allowed for smartaccount
// permitted messages will be determined by the government
err = saKeeper.CheckAllowedMsgs(ctx, msgs)
if err != nil {
return err
}
msgsData, err := types.ParseMessagesString(msgs)
if err != nil {
return err
}
callInfo := types.CallInfo{
Gas: feeTx.GetGas(),
Fee: feeTx.GetFee(),
FeePayer: feeTx.FeePayer().String(),
FeeGranter: feeTx.FeeGranter().String(),
}
emptyAuthzInfo := types.AuthzInfo{
Grantee: "",
}
preExecuteMessage, err := json.Marshal(&types.AccountMsg{
PreExecuteTx: &types.PreExecuteTx{
Msgs: msgsData,
CallInfo: callInfo,
AuthzInfo: emptyAuthzInfo,
},
})
if err != nil {
return err
}
params := saKeeper.GetParams(ctx)
// Call a contract's sudo with a gas limit
//
// using gas for validate SA msgs will not count to tx total used
//
// referenced from Osmosis' protorev posthandler:
// https://github.com/osmosis-labs/osmosis/blob/98025f185ab2ee1b060511ed22679112abcc08fa/x/protorev/keeper/posthandler.go#L42-L43
cacheCtx, write := ctx.CacheContext()
cacheCtx = cacheCtx.WithGasMeter(sdk.NewGasMeter(params.MaxGasExecute))
// execute SA contract for pre-execute transaction with limit gas
// will using cacheCtx instead of ctx to run contract execution
gasRemaining := sudoWithPanicRecover(
cacheCtx,
saKeeper.ContractKeeper,
signerAcc.GetAddress(),
preExecuteMessage,
&err,
)
if err != nil {
return err
}
write()
ctx.EventManager().EmitEvents(cacheCtx.EventManager().Events())
// free gas remaining after validate smartaccount msgs
saKeeper.SetGasRemaining(ctx, gasRemaining)
return nil
}
func handleSmartAccountActivate(
ctx sdk.Context,
saKeeper sakeeper.Keeper,
activateMsg *typesv1.MsgActivateAccount,
simulate bool,
) error {
// get signer of smart account activation message
signer := activateMsg.GetSigners()[0]
// decode string to pubkey
pubKey, err := typesv1.PubKeyDecode(activateMsg.PubKey)
if err != nil {
return err
}
// generate predictable address using Instantiate2's PredicableAddressGenerator
predicAddr, err := types.Instantiate2Address(
ctx,
saKeeper.WasmKeeper,
activateMsg.CodeID,
activateMsg.InitMsg,
activateMsg.Salt,
pubKey,
)
if err != nil {
return err
}
// the signer of the activation message must be the address generated by Instantiate2's PredicableAddressGenerator
if !signer.Equals(predicAddr) {
return errorsmod.Wrap(types.ErrInvalidAddress, "not the same as predicted")
}
if !ctx.IsReCheckTx() && !simulate {
// get smart contract account by address
sAccount := saKeeper.AccountKeeper.GetAccount(ctx, signer)
_, isBase := sAccount.(*authtypes.BaseAccount)
if !isBase {
return errorsmod.Wrap(types.ErrAccountNotFoundForAddress, signer.String())
}
// remove temporary pubkey for account
// wasmd instantiate2 method requires base account with nil pubkey and 0 sequence to be considered an initializable address for smart contract
err = saKeeper.UpdateAccountPubKey(ctx, sAccount, nil)
if err != nil {
return err
}
}
return nil
}
// Call a contract's sudo with panic recover
// In our case, the out of gas happened because there was too much logic on the linked smart contract
// Resulting in consumption exceeding the amount of `MaxGasExecute` gas allowed to execute the sudo call
// Must distinguish between sdk `out of gas` which is caused by too small tx' gasLimit
func sudoWithPanicRecover(
ctx sdk.Context, contractKeeper *wasmkeeper.PermissionedKeeper,
contractAddr sdk.AccAddress, msg []byte, err *error,
) uint64 {
// Recover from panic, return error
//
// referenced from Juno:
// https://github.com/CosmosContracts/juno/blob/3a0bb93303772936362c93e3979d900a39cda68a/app/helpers/contracts.go
defer func() {
if recoveryError := recover(); recoveryError != nil {
// Determine error associated with panic
if isOutofGas, msg := types.IsOutOfGasError(recoveryError); isOutofGas {
*err = types.ErrOutOfGas.Wrapf("%s", msg)
} else {
*err = types.ErrContractExecutionPanic.Wrapf("%s", recoveryError)
}
}
}()
_, *err = contractKeeper.Sudo(
ctx,
contractAddr, // contract address
msg,
)
return ctx.GasMeter().GasRemaining()
}
// ------------------------- SetPubKey Decorator ------------------------- \\
type SetPubKeyDecorator struct {
saKeeper sakeeper.Keeper
}
func NewSetPubKeyDecorator(saKeeper sakeeper.Keeper) *SetPubKeyDecorator {
return &SetPubKeyDecorator{
saKeeper: saKeeper,
}
}
func (d *SetPubKeyDecorator) AnteHandle(
ctx sdk.Context,
tx sdk.Tx,
simulate bool,
next sdk.AnteHandler,
) (newCtx sdk.Context, err error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, errorsmod.Wrap(types.ErrInvalidTx, "not a SigVerifiableTx")
}
activateMsg, err := GetValidActivateAccountMessage(sigTx)
if err != nil {
return ctx, err
}
// if is smart account activation message
if activateMsg != nil {
// get message signer
signer := activateMsg.GetSigners()[0]
// get smartaccount by address, must be inactivate account
sAccount, err := d.saKeeper.IsInactiveAccount(ctx, signer)
if err != nil {
return ctx, err
}
if !ctx.IsReCheckTx() && !simulate {
// decode any to pubkey
pubKey, err := typesv1.PubKeyDecode(activateMsg.PubKey)
if err != nil {
return ctx, err
}
// set temporary pubkey for account
// need this for the next ante signature checks
err = d.saKeeper.UpdateAccountPubKey(ctx, sAccount, pubKey)
if err != nil {
return ctx, err
}
}
return next(ctx, tx, simulate)
}
signerAcc, err := GetSmartAccountTxSigner(ctx, sigTx, d.saKeeper)
if err != nil {
return ctx, err
}
// if is smart account tx skip authante NewSetPubKeyDecorator
// need this to avoid pubkey and address equal check of authante SetPubKeyDecorator
if signerAcc != nil {
// if this is smart account tx and not in simulation mode
// check if pubkey is set
if !simulate && signerAcc.GetPubKey() == nil {
return ctx, errorsmod.Wrap(types.ErrNilPubkey, signerAcc.String())
}
// Also emit the following events, so that txs can be indexed by these
var events sdk.Events
events = append(events, sdk.NewEvent(types.EventTypeSmartAccountTx,
sdk.NewAttribute(sdk.AttributeKeyAccountSequence, fmt.Sprintf("%s/%d", signerAcc.GetAddress(), signerAcc.GetSequence())),
))
// maybe need add more event here
ctx.EventManager().EmitEvents(events)
return next(ctx, tx, simulate)
}
// default authant SetPubKeyDecorator
svd := authante.NewSetPubKeyDecorator(d.saKeeper.AccountKeeper)
return svd.AnteHandle(ctx, tx, simulate, next)
}
// ------------------------- ValidateAuthzTx Decorator ------------------------- \\
type ValidateAuthzTxDecorator struct {
SaKeeper sakeeper.Keeper
}
func NewValidateAuthzTxDecorator(saKeeper sakeeper.Keeper) *ValidateAuthzTxDecorator {
return &ValidateAuthzTxDecorator{
SaKeeper: saKeeper,
}
}
// If smartaccount messages is executed throught MsgAuthzExec, SmartAccountDecorator cannot detect and validate these messages
// using AuthzTxDecorator AnteHandler to provide validation for nested smartaccount msgs
func (d *ValidateAuthzTxDecorator) AnteHandle(
ctx sdk.Context,
tx sdk.Tx,
simulate bool,
next sdk.AnteHandler,
) (newCtx sdk.Context, err error) {
params := d.SaKeeper.GetParams(ctx)
maxGas := params.MaxGasExecute
if d.SaKeeper.HasGasRemaining(ctx) {
// if pre ante handlers has used free gas, get the remaining
maxGas = d.SaKeeper.GetGasRemaining(ctx)
d.SaKeeper.DeleteGasRemaining(ctx)
}
cacheCtx, write := ctx.CacheContext()
cacheCtx = cacheCtx.WithGasMeter(sdk.NewGasMeter(maxGas))
// using gas for validate authz will not count to tx total used
err = validateAuthzTx(cacheCtx, d.SaKeeper, tx, true)
if err != nil {
return ctx, err
}
write()
ctx.EventManager().EmitEvents(cacheCtx.EventManager().Events())
return next(ctx, tx, simulate)
}
func validateAuthzTx(
ctx sdk.Context,
saKeeper sakeeper.Keeper,
tx sdk.Tx,
isAnte bool,
) error {
for _, msg := range tx.GetMsgs() {
if msgExec, ok := msg.(*authz.MsgExec); ok {
msgs, err := msgExec.GetMessages()
if err != nil {
return err
}
err = validateNestedSmartAccountMsgs(
ctx,
saKeeper,
msgs,
msgExec.Grantee,
isAnte,
)
if err != nil {
return err
}
}
}
return nil
}
func validateNestedSmartAccountMsgs(
ctx sdk.Context,
saKeeper sakeeper.Keeper,
msgs []sdk.Msg,
grantee string,
isAnte bool,
) error {
for _, msg := range msgs {
signers := msg.GetSigners()
if len(signers) == 1 {
acc, err := saKeeper.GetSmartAccountByAddress(ctx, signers[0])
if err != nil {
return err
}
if acc != nil {
msgsData, err := types.ParseMessagesString([]sdk.Msg{msg})
if err != nil {
return err
}
// call_info is empty if message is executed throught authz exec
callInfo := types.CallInfo{
Gas: 0,
Fee: sdk.NewCoins(),
FeePayer: "",
FeeGranter: "",
}
authzInfo := types.AuthzInfo{
Grantee: grantee,
}
var execMsg []byte
if isAnte {
execMsg, err = json.Marshal(&types.AccountMsg{
PreExecuteTx: &types.PreExecuteTx{
Msgs: msgsData,
CallInfo: callInfo,
AuthzInfo: authzInfo,
},
})
} else {
execMsg, err = json.Marshal(&types.AccountMsg{
AfterExecuteTx: &types.AfterExecuteTx{
Msgs: msgsData,
CallInfo: callInfo,
AuthzInfo: authzInfo,
},
})
}
if err != nil {
return err
}
if _ = sudoWithPanicRecover(
ctx,
saKeeper.ContractKeeper,
acc.GetAddress(),
execMsg,
&err,
); err != nil {
return err
}
}
}
if msgExec, ok := msg.(*authz.MsgExec); ok {
msgs, err := msgExec.GetMessages()
if err != nil {
return err
}
err = validateNestedSmartAccountMsgs(
ctx,
saKeeper,
msgs,
msgExec.Grantee,
isAnte,
)
if err != nil {
return err
}
}
}
return nil
}