-
Notifications
You must be signed in to change notification settings - Fork 108
/
keeper.go
500 lines (432 loc) · 18.9 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
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
package keeper
import (
"encoding/binary"
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types"
conntypes "github.com/cosmos/ibc-go/v4/modules/core/03-connection/types"
channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types"
host "github.com/cosmos/ibc-go/v4/modules/core/24-host"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/interchain-security/x/ccv/consumer/types"
consumertypes "github.com/cosmos/interchain-security/x/ccv/consumer/types"
ccv "github.com/cosmos/interchain-security/x/ccv/types"
"github.com/tendermint/tendermint/libs/log"
)
// Keeper defines the Cross-Chain Validation Consumer Keeper
type Keeper struct {
storeKey sdk.StoreKey
cdc codec.BinaryCodec
paramStore paramtypes.Subspace
scopedKeeper ccv.ScopedKeeper
channelKeeper ccv.ChannelKeeper
portKeeper ccv.PortKeeper
connectionKeeper ccv.ConnectionKeeper
clientKeeper ccv.ClientKeeper
slashingKeeper ccv.SlashingKeeper
hooks ccv.ConsumerHooks
bankKeeper ccv.BankKeeper
authKeeper ccv.AccountKeeper
ibcTransferKeeper ccv.IBCTransferKeeper
ibcCoreKeeper ccv.IBCCoreKeeper
feeCollectorName string
}
// NewKeeper creates a new Consumer Keeper instance
// NOTE: the feeCollectorName is in reference to the consumer-chain fee
// collector (and not the provider chain)
func NewKeeper(
cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace,
scopedKeeper ccv.ScopedKeeper,
channelKeeper ccv.ChannelKeeper, portKeeper ccv.PortKeeper,
connectionKeeper ccv.ConnectionKeeper, clientKeeper ccv.ClientKeeper,
slashingKeeper ccv.SlashingKeeper, bankKeeper ccv.BankKeeper, accountKeeper ccv.AccountKeeper,
ibcTransferKeeper ccv.IBCTransferKeeper, ibcCoreKeeper ccv.IBCCoreKeeper,
feeCollectorName string,
) Keeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}
return Keeper{
storeKey: key,
cdc: cdc,
paramStore: paramSpace,
scopedKeeper: scopedKeeper,
channelKeeper: channelKeeper,
portKeeper: portKeeper,
connectionKeeper: connectionKeeper,
clientKeeper: clientKeeper,
slashingKeeper: slashingKeeper,
bankKeeper: bankKeeper,
authKeeper: accountKeeper,
ibcTransferKeeper: ibcTransferKeeper,
ibcCoreKeeper: ibcCoreKeeper,
feeCollectorName: feeCollectorName,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+host.ModuleName+"-"+types.ModuleName)
}
func (k *Keeper) SetHooks(sh ccv.ConsumerHooks) *Keeper {
if k.hooks != nil {
// This should never happen as SetHooks is expected
// to be called only once in app.go
panic("cannot set validator hooks twice")
}
k.hooks = sh
return k
}
// ChanCloseInit defines a wrapper function for the channel Keeper's function
// Following ICS 004: https://github.com/cosmos/ibc/tree/main/spec/core/ics-004-channel-and-packet-semantics#closing-handshake
func (k Keeper) ChanCloseInit(ctx sdk.Context, portID, channelID string) error {
capName := host.ChannelCapabilityPath(portID, channelID)
chanCap, ok := k.scopedKeeper.GetCapability(ctx, capName)
if !ok {
return sdkerrors.Wrapf(channeltypes.ErrChannelCapabilityNotFound, "could not retrieve channel capability at: %s", capName)
}
return k.channelKeeper.ChanCloseInit(ctx, portID, channelID, chanCap)
}
// IsBound checks if the transfer module is already bound to the desired port
func (k Keeper) IsBound(ctx sdk.Context, portID string) bool {
_, ok := k.scopedKeeper.GetCapability(ctx, host.PortPath(portID))
return ok
}
// BindPort defines a wrapper function for the ort Keeper's function in
// order to expose it to module's InitGenesis function
func (k Keeper) BindPort(ctx sdk.Context, portID string) error {
cap := k.portKeeper.BindPort(ctx, portID)
return k.ClaimCapability(ctx, cap, host.PortPath(portID))
}
// GetPort returns the portID for the transfer module. Used in ExportGenesis
func (k Keeper) GetPort(ctx sdk.Context) string {
store := ctx.KVStore(k.storeKey)
return string(store.Get(types.PortKey()))
}
// SetPort sets the portID for the CCV module. Used in InitGenesis
func (k Keeper) SetPort(ctx sdk.Context, portID string) {
store := ctx.KVStore(k.storeKey)
store.Set(types.PortKey(), []byte(portID))
}
// AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function
func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool {
return k.scopedKeeper.AuthenticateCapability(ctx, cap, name)
}
// ClaimCapability claims a capability that the IBC module passes to it
func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error {
return k.scopedKeeper.ClaimCapability(ctx, cap, name)
}
// SetProviderClientID sets the clientID for the client to the provider.
// Set in InitGenesis
func (k Keeper) SetProviderClientID(ctx sdk.Context, clientID string) {
store := ctx.KVStore(k.storeKey)
store.Set(types.ProviderClientIDKey(), []byte(clientID))
}
// GetProviderClientID gets the clientID for the client to the provider.
func (k Keeper) GetProviderClientID(ctx sdk.Context) (string, bool) {
store := ctx.KVStore(k.storeKey)
clientIdBytes := store.Get(types.ProviderClientIDKey())
if clientIdBytes == nil {
return "", false
}
return string(clientIdBytes), true
}
// SetProviderChannel sets the channelID for the channel to the provider.
func (k Keeper) SetProviderChannel(ctx sdk.Context, channelID string) {
store := ctx.KVStore(k.storeKey)
store.Set(types.ProviderChannelKey(), []byte(channelID))
}
// GetProviderChannel gets the channelID for the channel to the provider.
func (k Keeper) GetProviderChannel(ctx sdk.Context) (string, bool) {
store := ctx.KVStore(k.storeKey)
channelIdBytes := store.Get(types.ProviderChannelKey())
if len(channelIdBytes) == 0 {
return "", false
}
return string(channelIdBytes), true
}
// DeleteProviderChannel deletes the channelID for the channel to the provider.
func (k Keeper) DeleteProviderChannel(ctx sdk.Context) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.ProviderChannelKey())
}
// SetPendingChanges sets the pending validator set change packet that haven't been flushed to ABCI
func (k Keeper) SetPendingChanges(ctx sdk.Context, updates ccv.ValidatorSetChangePacketData) {
store := ctx.KVStore(k.storeKey)
bz, err := updates.Marshal()
if err != nil {
// This should never happen
panic(fmt.Errorf("failed to marshal PendingChanges: %w", err))
}
store.Set(types.PendingChangesKey(), bz)
}
// GetPendingChanges gets the pending changes that haven't been flushed over ABCI
func (k Keeper) GetPendingChanges(ctx sdk.Context) (*ccv.ValidatorSetChangePacketData, bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.PendingChangesKey())
if bz == nil {
return nil, false
}
var data ccv.ValidatorSetChangePacketData
if err := data.Unmarshal(bz); err != nil {
// This should never happen as PendingChanges is expected
// to be correctly serialized in SetPendingChanges
panic(fmt.Errorf("failed to unmarshal PendingChanges: %w", err))
}
return &data, true
}
// DeletePendingChanges deletes the pending changes after they've been flushed to ABCI
func (k Keeper) DeletePendingChanges(ctx sdk.Context) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.PendingChangesKey())
}
// GetElapsedPacketMaturityTimes returns a slice of already elapsed PacketMaturityTimes, sorted by maturity times,
// i.e., the slice contains the IDs of the matured VSCPackets.
func (k Keeper) GetElapsedPacketMaturityTimes(ctx sdk.Context) (maturingVSCPackets []consumertypes.MaturingVSCPacket) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte{types.PacketMaturityTimeBytePrefix})
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var maturingVSCPacket consumertypes.MaturingVSCPacket
if err := maturingVSCPacket.Unmarshal(iterator.Value()); err != nil {
// An error here would indicate something is very wrong,
// the MaturingVSCPackets are assumed to be correctly serialized in SetPacketMaturityTime.
panic(fmt.Errorf("failed to unmarshal MaturingVSCPacket: %w", err))
}
// If the current block time is before maturity time then stop the iteration.
// This is possible since the iteration over PacketMaturityTimes is in order
// of maturity times
if ctx.BlockTime().Before(maturingVSCPacket.MaturityTime) {
break
}
maturingVSCPackets = append(maturingVSCPackets, maturingVSCPacket)
}
return maturingVSCPackets
}
// GetAllPacketMaturityTimes returns a slice of all PacketMaturityTimes, sorted by maturity times.
//
// Note that PacketMaturityTimes are stored under keys with the following format:
// PacketMaturityTimeBytePrefix | maturityTime.UnixNano() | vscID
// Thus, the returned array is in ascending order of maturityTimes.
// If two entries have the same maturityTime, then they are ordered by vscID.
func (k Keeper) GetAllPacketMaturityTimes(ctx sdk.Context) (maturingVSCPackets []consumertypes.MaturingVSCPacket) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte{types.PacketMaturityTimeBytePrefix})
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var maturingVSCPacket consumertypes.MaturingVSCPacket
if err := maturingVSCPacket.Unmarshal(iterator.Value()); err != nil {
// An error here would indicate something is very wrong,
// the MaturingVSCPackets are assumed to be correctly serialized in SetPacketMaturityTime.
panic(fmt.Errorf("failed to unmarshal MaturingVSCPacket: %w", err))
}
maturingVSCPackets = append(maturingVSCPackets, maturingVSCPacket)
}
return maturingVSCPackets
}
// SetPacketMaturityTime sets the maturity time for a given received VSC packet id
func (k Keeper) SetPacketMaturityTime(ctx sdk.Context, vscId uint64, maturityTime time.Time) {
store := ctx.KVStore(k.storeKey)
maturingVSCPacket := consumertypes.MaturingVSCPacket{
VscId: vscId,
MaturityTime: maturityTime,
}
bz, err := maturingVSCPacket.Marshal()
if err != nil {
// An error here would indicate something is very wrong,
// maturingVSCPacket is instantiated in this method and should be able to be marshaled.
panic(fmt.Errorf("failed to marshal MaturingVSCPacket: %w", err))
}
store.Set(types.PacketMaturityTimeKey(vscId, maturityTime), bz)
}
// PacketMaturityExists checks whether the packet maturity time for a given vscId and maturityTime exists.
//
// Note: this method is only used in testing.
func (k Keeper) PacketMaturityTimeExists(ctx sdk.Context, vscId uint64, maturityTime time.Time) bool {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.PacketMaturityTimeKey(vscId, maturityTime))
return bz != nil
}
// DeletePacketMaturityTimes deletes the packet maturity time for a given vscId and maturityTime
func (k Keeper) DeletePacketMaturityTimes(ctx sdk.Context, vscId uint64, maturityTime time.Time) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.PacketMaturityTimeKey(vscId, maturityTime))
}
// VerifyProviderChain verifies that the chain trying to connect on the channel handshake
// is the expected provider chain.
func (k Keeper) VerifyProviderChain(ctx sdk.Context, connectionHops []string) error {
if len(connectionHops) != 1 {
return sdkerrors.Wrap(channeltypes.ErrTooManyConnectionHops, "must have direct connection to provider chain")
}
connectionID := connectionHops[0]
conn, ok := k.connectionKeeper.GetConnection(ctx, connectionID)
if !ok {
return sdkerrors.Wrapf(conntypes.ErrConnectionNotFound, "connection not found for connection ID: %s", connectionID)
}
// Verify that client id is expected clientID
expectedClientId, ok := k.GetProviderClientID(ctx)
if !ok {
return sdkerrors.Wrapf(clienttypes.ErrInvalidClient, "could not find provider client id")
}
if expectedClientId != conn.ClientId {
return sdkerrors.Wrapf(clienttypes.ErrInvalidClient, "invalid client: %s, channel must be built on top of client: %s", conn.ClientId, expectedClientId)
}
return nil
}
// SetHeightValsetUpdateID sets the valset update id for a given block height
func (k Keeper) SetHeightValsetUpdateID(ctx sdk.Context, height, valsetUpdateId uint64) {
store := ctx.KVStore(k.storeKey)
valBytes := make([]byte, 8)
binary.BigEndian.PutUint64(valBytes, valsetUpdateId)
store.Set(types.HeightValsetUpdateIDKey(height), valBytes)
}
// GetHeightValsetUpdateID gets the valset update id recorded for a given block height
func (k Keeper) GetHeightValsetUpdateID(ctx sdk.Context, height uint64) uint64 {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.HeightValsetUpdateIDKey(height))
if bz == nil {
return 0
}
return binary.BigEndian.Uint64(bz)
}
// DeleteHeightValsetUpdateID deletes the valset update id for a given block height
func (k Keeper) DeleteHeightValsetUpdateID(ctx sdk.Context, height uint64) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.HeightValsetUpdateIDKey(height))
}
// GetAllHeightToValsetUpdateIDs returns a list of all the block heights to valset update IDs in the store
//
// Note that the block height to vscID mapping is stored under keys with the following format:
// HeightValsetUpdateIDBytePrefix | height
// Thus, the returned array is in ascending order of heights.
func (k Keeper) GetAllHeightToValsetUpdateIDs(ctx sdk.Context) (heightToValsetUpdateIDs []types.HeightToValsetUpdateID) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte{types.HeightValsetUpdateIDBytePrefix})
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
height := binary.BigEndian.Uint64(iterator.Key()[1:])
vscID := binary.BigEndian.Uint64(iterator.Value())
heightToValsetUpdateIDs = append(heightToValsetUpdateIDs, types.HeightToValsetUpdateID{
Height: height,
ValsetUpdateId: vscID,
})
}
return heightToValsetUpdateIDs
}
// OutstandingDowntime returns the outstanding downtime flag for a given validator
func (k Keeper) OutstandingDowntime(ctx sdk.Context, address sdk.ConsAddress) bool {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.OutstandingDowntimeKey(address))
return bz != nil
}
// SetOutstandingDowntime sets the outstanding downtime flag for a given validator
func (k Keeper) SetOutstandingDowntime(ctx sdk.Context, address sdk.ConsAddress) {
store := ctx.KVStore(k.storeKey)
store.Set(types.OutstandingDowntimeKey(address), []byte{})
}
// DeleteOutstandingDowntime deletes the outstanding downtime flag for the given validator consensus address
func (k Keeper) DeleteOutstandingDowntime(ctx sdk.Context, consAddress string) {
consAddr, err := sdk.ConsAddressFromBech32(consAddress)
if err != nil {
return // TODO: this should panic with appropriate tests to validate the panic wont happen in normal cases.
}
store := ctx.KVStore(k.storeKey)
store.Delete(types.OutstandingDowntimeKey(consAddr))
}
// GetAllOutstandingDowntimes gets an array of the validator addresses of outstanding downtime flags
//
// Note that the outstanding downtime flags are stored under keys with the following format:
// OutstandingDowntimeBytePrefix | consAddress
// Thus, the returned array is in ascending order of consAddresses.
func (k Keeper) GetAllOutstandingDowntimes(ctx sdk.Context) (downtimes []consumertypes.OutstandingDowntime) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte{types.OutstandingDowntimeBytePrefix})
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
addrBytes := iterator.Key()[1:]
addr := sdk.ConsAddress(addrBytes).String()
downtimes = append(downtimes, consumertypes.OutstandingDowntime{
ValidatorConsensusAddress: addr,
})
}
return downtimes
}
// SetCCValidator sets a cross-chain validator under its validator address
func (k Keeper) SetCCValidator(ctx sdk.Context, v types.CrossChainValidator) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&v)
store.Set(types.CrossChainValidatorKey(v.Address), bz)
}
// GetCCValidator returns a cross-chain validator for a given address
func (k Keeper) GetCCValidator(ctx sdk.Context, addr []byte) (validator types.CrossChainValidator, found bool) {
store := ctx.KVStore(k.storeKey)
v := store.Get(types.CrossChainValidatorKey(addr))
if v == nil {
return
}
k.cdc.MustUnmarshal(v, &validator)
found = true
return
}
// DeleteCCValidator deletes a cross-chain validator for a given address
func (k Keeper) DeleteCCValidator(ctx sdk.Context, addr []byte) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.CrossChainValidatorKey(addr))
}
// GetAllCCValidator returns all cross-chain validators
//
// Note that the cross-chain validators are stored under keys with the following format:
// CrossChainValidatorBytePrefix | address
// Thus, the returned array is in ascending order of addresses.
func (k Keeper) GetAllCCValidator(ctx sdk.Context) (validators []types.CrossChainValidator) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, []byte{types.CrossChainValidatorBytePrefix})
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
val := types.CrossChainValidator{}
k.cdc.MustUnmarshal(iterator.Value(), &val)
validators = append(validators, val)
}
return validators
}
// SetPendingPackets sets the pending CCV packets
func (k Keeper) SetPendingPackets(ctx sdk.Context, packets ccv.ConsumerPacketDataList) {
store := ctx.KVStore(k.storeKey)
bz, err := packets.Marshal()
if err != nil {
// This should never happen
panic(fmt.Errorf("failed to marshal ConsumerPacketDataList: %w", err))
}
store.Set([]byte{types.PendingDataPacketsBytePrefix}, bz)
}
// GetPendingPackets returns the pending CCV packets from the store
func (k Keeper) GetPendingPackets(ctx sdk.Context) ccv.ConsumerPacketDataList {
var packets ccv.ConsumerPacketDataList
store := ctx.KVStore(k.storeKey)
bz := store.Get([]byte{types.PendingDataPacketsBytePrefix})
if bz == nil {
return packets
}
err := packets.Unmarshal(bz)
if err != nil {
// An error here would indicate something is very wrong,
// the PendingPackets are assumed to be correctly serialized in SetPendingPackets.
panic(fmt.Errorf("failed to unmarshal pending data packets: %w", err))
}
return packets
}
// DeletePendingDataPackets clears the pending data packets in store
func (k Keeper) DeletePendingDataPackets(ctx sdk.Context) {
store := ctx.KVStore(k.storeKey)
store.Delete([]byte{types.PendingDataPacketsBytePrefix})
}
// AppendPendingDataPacket appends the given data packet to the pending data packets in store
func (k Keeper) AppendPendingPacket(ctx sdk.Context, packet ...ccv.ConsumerPacketData) {
pending := k.GetPendingPackets(ctx)
list := append(pending.GetList(), packet...)
k.SetPendingPackets(ctx, ccv.ConsumerPacketDataList{List: list})
}