-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
keeper.go
372 lines (312 loc) · 11.2 KB
/
keeper.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
package keeper
import (
"fmt"
"time"
"github.com/gogo/protobuf/proto"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
"github.com/cosmos/cosmos-sdk/x/authz"
)
// TODO: Revisit this once we have propoer gas fee framework.
// Tracking issues https://github.com/cosmos/cosmos-sdk/issues/9054,
// https://github.com/cosmos/cosmos-sdk/discussions/9072
const gasCostPerIteration = uint64(20)
type Keeper struct {
storeKey storetypes.StoreKey
cdc codec.BinaryCodec
router *baseapp.MsgServiceRouter
authKeeper authkeeper.AccountKeeper
}
// NewKeeper constructs a message authorization Keeper
func NewKeeper(storeKey storetypes.StoreKey, cdc codec.BinaryCodec, router *baseapp.MsgServiceRouter, ak authkeeper.AccountKeeper) Keeper {
return Keeper{
storeKey: storeKey,
cdc: cdc,
router: router,
authKeeper: ak,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", authz.ModuleName))
}
// getGrant returns grant stored at skey.
func (k Keeper) getGrant(ctx sdk.Context, skey []byte) (grant authz.Grant, found bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(skey)
if bz == nil {
return grant, false
}
k.cdc.MustUnmarshal(bz, &grant)
return grant, true
}
func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, updated authz.Authorization) error {
skey := grantStoreKey(grantee, granter, updated.MsgTypeURL())
grant, found := k.getGrant(ctx, skey)
if !found {
return authz.ErrNoAuthorizationFound
}
msg, ok := updated.(proto.Message)
if !ok {
return sdkerrors.ErrPackAny.Wrapf("cannot proto marshal %T", updated)
}
any, err := codectypes.NewAnyWithValue(msg)
if err != nil {
return err
}
grant.Authorization = any
store := ctx.KVStore(k.storeKey)
store.Set(skey, k.cdc.MustMarshal(&grant))
return nil
}
// DispatchActions attempts to execute the provided messages via authorization
// grants from the message signer to the grantee.
func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, msgs []sdk.Msg) ([][]byte, error) {
results := make([][]byte, len(msgs))
now := ctx.BlockTime()
for i, msg := range msgs {
signers := msg.GetSigners()
if len(signers) != 1 {
return nil, authz.ErrAuthorizationNumOfSigners
}
granter := signers[0]
// if granter != grantee then check authorization.Accept, otherwise we implicitly accept.
if !granter.Equals(grantee) {
skey := grantStoreKey(grantee, granter, sdk.MsgTypeURL(msg))
grant, found := k.getGrant(ctx, skey)
if !found {
return nil, sdkerrors.Wrapf(authz.ErrNoAuthorizationFound, "failed to update grant with key %s", string(skey))
}
if grant.Expiration != nil && grant.Expiration.Before(now) {
return nil, authz.ErrAuthorizationExpired
}
authorization, err := grant.GetAuthorization()
if err != nil {
return nil, err
}
resp, err := authorization.Accept(ctx, msg)
if err != nil {
return nil, err
}
if resp.Delete {
err = k.DeleteGrant(ctx, grantee, granter, sdk.MsgTypeURL(msg))
} else if resp.Updated != nil {
err = k.update(ctx, grantee, granter, resp.Updated)
}
if err != nil {
return nil, err
}
if !resp.Accept {
return nil, sdkerrors.ErrUnauthorized
}
}
handler := k.router.Handler(msg)
if handler == nil {
return nil, sdkerrors.ErrUnknownRequest.Wrapf("unrecognized message route: %s", sdk.MsgTypeURL(msg))
}
msgResp, err := handler(ctx, msg)
if err != nil {
return nil, sdkerrors.Wrapf(err, "failed to execute message; message %v", msg)
}
results[i] = msgResp.Data
// emit the events from the dispatched actions
events := msgResp.Events
sdkEvents := make([]sdk.Event, 0, len(events))
for i := 0; i < len(events); i++ {
sdkEvents = append(sdkEvents, sdk.Event(events[i]))
}
ctx.EventManager().EmitEvents(sdkEvents)
}
return results, nil
}
// SaveGrant method grants the provided authorization to the grantee on the granter's account
// with the provided expiration time and insert authorization key into the grants queue. If there is an existing authorization grant for the
// same `sdk.Msg` type, this grant overwrites that.
func (k Keeper) SaveGrant(ctx sdk.Context, grantee, granter sdk.AccAddress, authorization authz.Authorization, expiration *time.Time) error {
store := ctx.KVStore(k.storeKey)
msgType := authorization.MsgTypeURL()
skey := grantStoreKey(grantee, granter, msgType)
grant, err := authz.NewGrant(ctx.BlockTime(), authorization, expiration)
if err != nil {
return err
}
var oldExp *time.Time
if oldGrant, found := k.getGrant(ctx, skey); found {
oldExp = oldGrant.Expiration
}
if oldExp != nil && (expiration == nil || !oldExp.Equal(*expiration)) {
if err = k.removeFromGrantQueue(ctx, skey, granter, grantee, *oldExp); err != nil {
return err
}
}
// If the expiration didn't change, then we don't remove it and we should not insert again
if expiration != nil && (oldExp == nil || !oldExp.Equal(*expiration)) {
if err = k.insertIntoGrantQueue(ctx, granter, grantee, msgType, *expiration); err != nil {
return err
}
}
bz := k.cdc.MustMarshal(&grant)
store.Set(skey, bz)
return ctx.EventManager().EmitTypedEvent(&authz.EventGrant{
MsgTypeUrl: authorization.MsgTypeURL(),
Granter: granter.String(),
Grantee: grantee.String(),
})
}
// DeleteGrant revokes any authorization for the provided message type granted to the grantee
// by the granter.
func (k Keeper) DeleteGrant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) error {
store := ctx.KVStore(k.storeKey)
skey := grantStoreKey(grantee, granter, msgType)
grant, found := k.getGrant(ctx, skey)
if !found {
return sdkerrors.Wrapf(authz.ErrNoAuthorizationFound, "failed to delete grant with key %s", string(skey))
}
if grant.Expiration != nil {
err := k.removeFromGrantQueue(ctx, skey, granter, grantee, *grant.Expiration)
if err != nil {
return err
}
}
store.Delete(skey)
return ctx.EventManager().EmitTypedEvent(&authz.EventRevoke{
MsgTypeUrl: msgType,
Granter: granter.String(),
Grantee: grantee.String(),
})
}
// GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter.
func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress) ([]authz.Authorization, error) {
store := ctx.KVStore(k.storeKey)
key := grantStoreKey(grantee, granter, "")
iter := sdk.KVStorePrefixIterator(store, key)
defer iter.Close()
var authorization authz.Grant
var authorizations []authz.Authorization
for ; iter.Valid(); iter.Next() {
if err := k.cdc.Unmarshal(iter.Value(), &authorization); err != nil {
return nil, err
}
a, err := authorization.GetAuthorization()
if err != nil {
return nil, err
}
authorizations = append(authorizations, a)
}
return authorizations, nil
}
// IterateGrants iterates over all authorization grants
// This function should be used with caution because it can involve significant IO operations.
// It should not be used in query or msg services without charging additional gas.
// The iteration stops when the handler function returns true or the iterator exhaust.
func (k Keeper) IterateGrants(ctx sdk.Context,
handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant authz.Grant) bool,
) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, GrantKey)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var grant authz.Grant
granterAddr, granteeAddr, _ := parseGrantStoreKey(iter.Key())
k.cdc.MustUnmarshal(iter.Value(), &grant)
if handler(granterAddr, granteeAddr, grant) {
break
}
}
}
func (keeper Keeper) getGrantQueueItem(ctx sdk.Context, expiration time.Time, granter, grantee sdk.AccAddress) (*authz.GrantQueueItem, error) {
store := ctx.KVStore(keeper.storeKey)
bz := store.Get(GrantQueueKey(expiration, granter, grantee))
if bz == nil {
return &authz.GrantQueueItem{}, nil
}
var queueItems authz.GrantQueueItem
if err := keeper.cdc.Unmarshal(bz, &queueItems); err != nil {
return nil, err
}
return &queueItems, nil
}
func (k Keeper) setGrantQueueItem(ctx sdk.Context, expiration time.Time,
granter sdk.AccAddress, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem,
) error {
store := ctx.KVStore(k.storeKey)
bz, err := k.cdc.Marshal(queueItems)
if err != nil {
return err
}
store.Set(GrantQueueKey(expiration, granter, grantee), bz)
return nil
}
// insertIntoGrantQueue inserts a grant key into the grant queue
func (keeper Keeper) insertIntoGrantQueue(ctx sdk.Context, granter, grantee sdk.AccAddress, msgType string, expiration time.Time) error {
queueItems, err := keeper.getGrantQueueItem(ctx, expiration, granter, grantee)
if err != nil {
return err
}
if len(queueItems.MsgTypeUrls) == 0 {
keeper.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{
MsgTypeUrls: []string{msgType},
})
} else {
queueItems.MsgTypeUrls = append(queueItems.MsgTypeUrls, msgType)
keeper.setGrantQueueItem(ctx, expiration, granter, grantee, queueItems)
}
return nil
}
// removeFromGrantQueue removes a grant key from the grant queue
func (keeper Keeper) removeFromGrantQueue(ctx sdk.Context, grantKey []byte, granter, grantee sdk.AccAddress, expiration time.Time) error {
store := ctx.KVStore(keeper.storeKey)
key := GrantQueueKey(expiration, granter, grantee)
bz := store.Get(key)
if bz == nil {
return sdkerrors.Wrap(authz.ErrNoGrantKeyFound, "can't remove grant from the expire queue, grant key not found")
}
var queueItem authz.GrantQueueItem
if err := keeper.cdc.Unmarshal(bz, &queueItem); err != nil {
return err
}
_, _, msgType := parseGrantStoreKey(grantKey)
queueItems := queueItem.MsgTypeUrls
for index, typeUrl := range queueItems {
ctx.GasMeter().ConsumeGas(gasCostPerIteration, "grant queue")
if typeUrl == msgType {
end := len(queueItem.MsgTypeUrls) - 1
queueItems[index] = queueItems[end]
queueItems = queueItems[:end]
if err := keeper.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{
MsgTypeUrls: queueItems,
}); err != nil {
return err
}
break
}
}
return nil
}
// DequeueAndDeleteExpiredGrants deletes expired grants from the state and grant queue.
func (k Keeper) DequeueAndDeleteExpiredGrants(ctx sdk.Context) error {
store := ctx.KVStore(k.storeKey)
iterator := store.Iterator(GrantQueuePrefix, sdk.InclusiveEndBytes(GrantQueueTimePrefix(ctx.BlockTime())))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var queueItem authz.GrantQueueItem
if err := k.cdc.Unmarshal(iterator.Value(), &queueItem); err != nil {
return err
}
_, granter, grantee, err := parseGrantQueueKey(iterator.Key())
if err != nil {
return err
}
store.Delete(iterator.Key())
for _, typeUrl := range queueItem.MsgTypeUrls {
store.Delete(grantStoreKey(grantee, granter, typeUrl))
}
}
return nil
}