-
Notifications
You must be signed in to change notification settings - Fork 637
/
Copy pathkeeper.go
482 lines (402 loc) · 17.7 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
package keeper
import (
"context"
"errors"
"fmt"
"strings"
"cosmossdk.io/core/appmodule"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
upgradetypes "cosmossdk.io/x/upgrade/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/runtime"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ibc-go/v9/modules/core/02-client/types"
host "github.com/cosmos/ibc-go/v9/modules/core/24-host"
"github.com/cosmos/ibc-go/v9/modules/core/exported"
coretypes "github.com/cosmos/ibc-go/v9/modules/core/types"
ibctm "github.com/cosmos/ibc-go/v9/modules/light-clients/07-tendermint"
localhost "github.com/cosmos/ibc-go/v9/modules/light-clients/09-localhost"
)
// Keeper represents a type that grants read and write permissions to any client
// state information
type Keeper struct {
appmodule.Environment
cdc codec.BinaryCodec
router *types.Router
legacySubspace types.ParamSubspace
upgradeKeeper types.UpgradeKeeper
}
// NewKeeper creates a new NewKeeper instance
func NewKeeper(cdc codec.BinaryCodec, env appmodule.Environment, legacySubspace types.ParamSubspace, uk types.UpgradeKeeper) *Keeper {
router := types.NewRouter()
localhostModule := localhost.NewLightClientModule(cdc, env)
router.AddRoute(exported.Localhost, localhostModule)
return &Keeper{
Environment: env,
cdc: cdc,
router: router,
legacySubspace: legacySubspace,
upgradeKeeper: uk,
}
}
// Codec returns the IBC Client module codec.
func (k *Keeper) Codec() codec.BinaryCodec {
return k.cdc
}
// AddRoute adds a new route to the underlying router.
func (k *Keeper) AddRoute(clientType string, module exported.LightClientModule) {
k.router.AddRoute(clientType, module)
}
// GetStoreProvider returns the light client store provider.
func (k *Keeper) GetStoreProvider() types.StoreProvider {
return types.NewStoreProvider(k.KVStoreService)
}
// Route returns the light client module for the given client identifier.
func (k *Keeper) Route(ctx context.Context, clientID string) (exported.LightClientModule, error) {
clientType, _, err := types.ParseClientIdentifier(clientID)
if err != nil {
return nil, errorsmod.Wrapf(err, "unable to parse client identifier %s", clientID)
}
if !k.GetParams(ctx).IsAllowedClient(clientType) {
return nil, errorsmod.Wrapf(
types.ErrInvalidClientType,
"client (%s) type %s is not in the allowed client list", clientID, clientType,
)
}
clientModule, found := k.router.GetRoute(clientType)
if !found {
return nil, errorsmod.Wrap(types.ErrRouteNotFound, clientID)
}
return clientModule, nil
}
// GenerateClientIdentifier returns the next client identifier.
func (k *Keeper) GenerateClientIdentifier(ctx context.Context, clientType string) string {
nextClientSeq := k.GetNextClientSequence(ctx)
clientID := types.FormatClientIdentifier(clientType, nextClientSeq)
nextClientSeq++
k.SetNextClientSequence(ctx, nextClientSeq)
return clientID
}
// GetClientState gets a particular client from the store
func (k *Keeper) GetClientState(ctx context.Context, clientID string) (exported.ClientState, bool) {
store := k.ClientStore(ctx, clientID)
bz := store.Get(host.ClientStateKey())
if len(bz) == 0 {
return nil, false
}
clientState := types.MustUnmarshalClientState(k.cdc, bz)
return clientState, true
}
// SetClientState sets a particular Client to the store
func (k *Keeper) SetClientState(ctx context.Context, clientID string, clientState exported.ClientState) {
store := k.ClientStore(ctx, clientID)
store.Set(host.ClientStateKey(), types.MustMarshalClientState(k.cdc, clientState))
}
// GetClientConsensusState gets the stored consensus state from a client at a given height.
func (k *Keeper) GetClientConsensusState(ctx context.Context, clientID string, height exported.Height) (exported.ConsensusState, bool) {
store := k.ClientStore(ctx, clientID)
bz := store.Get(host.ConsensusStateKey(height))
if len(bz) == 0 {
return nil, false
}
consensusState := types.MustUnmarshalConsensusState(k.cdc, bz)
return consensusState, true
}
// SetClientConsensusState sets a ConsensusState to a particular client at the given
// height
func (k *Keeper) SetClientConsensusState(ctx context.Context, clientID string, height exported.Height, consensusState exported.ConsensusState) {
store := k.ClientStore(ctx, clientID)
store.Set(host.ConsensusStateKey(height), types.MustMarshalConsensusState(k.cdc, consensusState))
}
// GetNextClientSequence gets the next client sequence from the store.
func (k *Keeper) GetNextClientSequence(ctx context.Context) uint64 {
store := k.KVStoreService.OpenKVStore(ctx)
bz, err := store.Get([]byte(types.KeyNextClientSequence))
if err != nil {
panic(err)
}
if len(bz) == 0 {
panic(errors.New("next client sequence is nil"))
}
return sdk.BigEndianToUint64(bz)
}
// SetNextClientSequence sets the next client sequence to the store.
func (k *Keeper) SetNextClientSequence(ctx context.Context, sequence uint64) {
store := k.KVStoreService.OpenKVStore(ctx)
bz := sdk.Uint64ToBigEndian(sequence)
if err := store.Set([]byte(types.KeyNextClientSequence), bz); err != nil {
panic(err)
}
}
// IterateConsensusStates provides an iterator over all stored consensus states.
// objects. For each State object, cb will be called. If the cb returns true,
// the iterator will close and stop.
func (k *Keeper) IterateConsensusStates(ctx context.Context, cb func(clientID string, cs types.ConsensusStateWithHeight) bool) {
store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx))
iterator := storetypes.KVStorePrefixIterator(store, host.KeyClientStorePrefix)
defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() })
for ; iterator.Valid(); iterator.Next() {
keySplit := strings.Split(string(iterator.Key()), "/")
// consensus key is in the format "clients/<clientID>/consensusStates/<height>"
if len(keySplit) != 4 || keySplit[2] != string(host.KeyConsensusStatePrefix) {
continue
}
clientID := keySplit[1]
height := types.MustParseHeight(keySplit[3])
consensusState := types.MustUnmarshalConsensusState(k.cdc, iterator.Value())
consensusStateWithHeight := types.NewConsensusStateWithHeight(height, consensusState)
if cb(clientID, consensusStateWithHeight) {
break
}
}
}
// iterateMetadata provides an iterator over all stored metadata keys in the client store.
// For each metadata object, it will perform a callback.
func (k *Keeper) iterateMetadata(ctx context.Context, cb func(clientID string, key, value []byte) bool) {
store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx))
iterator := storetypes.KVStorePrefixIterator(store, host.KeyClientStorePrefix)
defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() })
for ; iterator.Valid(); iterator.Next() {
split := strings.Split(string(iterator.Key()), "/")
if len(split) == 3 && split[2] == string(host.KeyClientState) {
// skip client state keys
continue
}
if len(split) == 4 && split[2] == string(host.KeyConsensusStatePrefix) {
// skip consensus state keys
continue
}
if split[0] != string(host.KeyClientStorePrefix) {
panic(errorsmod.Wrapf(host.ErrInvalidPath, "path does not begin with client store prefix: expected %s, got %s", host.KeyClientStorePrefix, split[0]))
}
if strings.TrimSpace(split[1]) == "" {
panic(errorsmod.Wrap(host.ErrInvalidPath, "clientID is empty"))
}
clientID := split[1]
key := []byte(strings.Join(split[2:], "/"))
if cb(clientID, key, iterator.Value()) {
break
}
}
}
// GetAllGenesisClients returns all the clients in state with their client ids returned as IdentifiedClientState
func (k *Keeper) GetAllGenesisClients(ctx context.Context) types.IdentifiedClientStates {
var genClients types.IdentifiedClientStates
k.IterateClientStates(ctx, nil, func(clientID string, cs exported.ClientState) bool {
genClients = append(genClients, types.NewIdentifiedClientState(clientID, cs))
return false
})
return genClients.Sort()
}
// GetAllClientMetadata will take a list of IdentifiedClientState and return a list
// of IdentifiedGenesisMetadata necessary for exporting and importing client metadata
// into the client store.
func (k *Keeper) GetAllClientMetadata(ctx context.Context, genClients []types.IdentifiedClientState) ([]types.IdentifiedGenesisMetadata, error) {
metadataMap := make(map[string][]types.GenesisMetadata)
k.iterateMetadata(ctx, func(clientID string, key, value []byte) bool {
metadataMap[clientID] = append(metadataMap[clientID], types.NewGenesisMetadata(key, value))
return false
})
genMetadata := make([]types.IdentifiedGenesisMetadata, 0)
for _, ic := range genClients {
metadata := metadataMap[ic.ClientId]
if len(metadata) != 0 {
genMetadata = append(genMetadata, types.NewIdentifiedGenesisMetadata(
ic.ClientId,
metadata,
))
}
}
return genMetadata, nil
}
// SetAllClientMetadata takes a list of IdentifiedGenesisMetadata and stores all of the metadata in the client store at the appropriate paths.
func (k *Keeper) SetAllClientMetadata(ctx context.Context, genMetadata []types.IdentifiedGenesisMetadata) {
for _, igm := range genMetadata {
// create client store
store := k.ClientStore(ctx, igm.ClientId)
// set all metadata kv pairs in client store
for _, md := range igm.ClientMetadata {
store.Set(md.GetKey(), md.GetValue())
}
}
}
// GetAllConsensusStates returns all stored client consensus states.
func (k *Keeper) GetAllConsensusStates(ctx context.Context) types.ClientsConsensusStates {
clientConsStates := make(types.ClientsConsensusStates, 0)
mapClientIDToConsStateIdx := make(map[string]int)
k.IterateConsensusStates(ctx, func(clientID string, cs types.ConsensusStateWithHeight) bool {
idx, ok := mapClientIDToConsStateIdx[clientID]
if ok {
clientConsStates[idx].ConsensusStates = append(clientConsStates[idx].ConsensusStates, cs)
return false
}
clientConsState := types.ClientConsensusStates{
ClientId: clientID,
ConsensusStates: []types.ConsensusStateWithHeight{cs},
}
clientConsStates = append(clientConsStates, clientConsState)
mapClientIDToConsStateIdx[clientID] = len(clientConsStates) - 1
return false
})
return clientConsStates.Sort()
}
// HasClientConsensusState returns if keeper has a ConsensusState for a particular
// client at the given height
func (k *Keeper) HasClientConsensusState(ctx context.Context, clientID string, height exported.Height) bool {
store := k.ClientStore(ctx, clientID)
return store.Has(host.ConsensusStateKey(height))
}
// GetLatestClientConsensusState gets the latest ConsensusState stored for a given client
func (k *Keeper) GetLatestClientConsensusState(ctx context.Context, clientID string) (exported.ConsensusState, bool) {
clientModule, err := k.Route(ctx, clientID)
if err != nil {
return nil, false
}
return k.GetClientConsensusState(ctx, clientID, clientModule.LatestHeight(ctx, clientID))
}
// VerifyMembership retrieves the light client module for the clientID and verifies the proof of the existence of a key-value pair at a specified height.
func (k *Keeper) VerifyMembership(ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path, value []byte) error {
clientModule, err := k.Route(ctx, clientID)
if err != nil {
return err
}
return clientModule.VerifyMembership(ctx, clientID, height, delayTimePeriod, delayBlockPeriod, proof, path, value)
}
// VerifyNonMembership retrieves the light client module for the clientID and verifies the absence of a given key at a specified height.
func (k *Keeper) VerifyNonMembership(ctx context.Context, clientID string, height exported.Height, delayTimePeriod uint64, delayBlockPeriod uint64, proof []byte, path exported.Path) error {
clientModule, err := k.Route(ctx, clientID)
if err != nil {
return err
}
return clientModule.VerifyNonMembership(ctx, clientID, height, delayTimePeriod, delayBlockPeriod, proof, path)
}
// GetUpgradePlan executes the upgrade keeper GetUpgradePlan function.
func (k *Keeper) GetUpgradePlan(ctx context.Context) (upgradetypes.Plan, error) {
return k.upgradeKeeper.GetUpgradePlan(ctx)
}
// GetUpgradedClient executes the upgrade keeper GetUpgradeClient function.
func (k *Keeper) GetUpgradedClient(ctx context.Context, planHeight int64) ([]byte, error) {
return k.upgradeKeeper.GetUpgradedClient(ctx, planHeight)
}
// GetUpgradedConsensusState returns the upgraded consensus state
func (k *Keeper) GetUpgradedConsensusState(ctx context.Context, planHeight int64) ([]byte, error) {
return k.upgradeKeeper.GetUpgradedConsensusState(ctx, planHeight)
}
// SetUpgradedConsensusState executes the upgrade keeper SetUpgradedConsensusState function.
func (k *Keeper) SetUpgradedConsensusState(ctx context.Context, planHeight int64, bz []byte) error {
return k.upgradeKeeper.SetUpgradedConsensusState(ctx, planHeight, bz)
}
// IterateClientStates provides an iterator over all stored ibc ClientState
// objects using the provided store prefix. For each ClientState object, cb will be called. If the cb returns true,
// the iterator will close and stop.
func (k *Keeper) IterateClientStates(ctx context.Context, storePrefix []byte, cb func(clientID string, cs exported.ClientState) bool) {
store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx))
iterator := storetypes.KVStorePrefixIterator(store, host.PrefixedClientStoreKey(storePrefix))
defer coretypes.LogDeferred(k.Logger, func() error { return iterator.Close() })
for ; iterator.Valid(); iterator.Next() {
path := string(iterator.Key())
if !strings.Contains(path, host.KeyClientState) {
// skip non client state keys
continue
}
clientID := host.MustParseClientStatePath(path)
clientState := types.MustUnmarshalClientState(k.cdc, iterator.Value())
if cb(clientID, clientState) {
break
}
}
}
// GetAllClients returns all stored light client State objects.
func (k *Keeper) GetAllClients(ctx context.Context) []exported.ClientState {
var states []exported.ClientState
k.IterateClientStates(ctx, nil, func(_ string, state exported.ClientState) bool {
states = append(states, state)
return false
})
return states
}
// ClientStore returns isolated prefix store for each client so they can read/write in separate
// namespace without being able to read/write other client's data
func (k *Keeper) ClientStore(ctx context.Context, clientID string) storetypes.KVStore {
clientPrefix := []byte(fmt.Sprintf("%s/%s/", host.KeyClientStorePrefix, clientID))
store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx))
return prefix.NewStore(store, clientPrefix)
}
// GetClientStatus returns the status for a client state given a client identifier. If the client type is not in the allowed
// clients param field, Unauthorized is returned, otherwise the client state status is returned.
func (k *Keeper) GetClientStatus(ctx context.Context, clientID string) exported.Status {
clientModule, err := k.Route(ctx, clientID)
if err != nil {
return exported.Unauthorized
}
return clientModule.Status(ctx, clientID)
}
// GetClientLatestHeight returns the latest height of a client state for a given client identifier. If the client type is not in the allowed
// clients param field, a zero value height is returned, otherwise the client state latest height is returned.
func (k *Keeper) GetClientLatestHeight(ctx context.Context, clientID string) types.Height {
clientModule, err := k.Route(ctx, clientID)
if err != nil {
return types.ZeroHeight()
}
var latestHeight types.Height
latestHeight, ok := clientModule.LatestHeight(ctx, clientID).(types.Height)
if !ok {
panic(fmt.Errorf("cannot convert %T to %T", clientModule.LatestHeight, latestHeight))
}
return latestHeight
}
// GetClientTimestampAtHeight returns the timestamp in nanoseconds of the consensus state at the given height.
func (k *Keeper) GetClientTimestampAtHeight(ctx context.Context, clientID string, height exported.Height) (uint64, error) {
clientModule, err := k.Route(ctx, clientID)
if err != nil {
return 0, err
}
return clientModule.TimestampAtHeight(ctx, clientID, height)
}
// GetParams returns the total set of ibc-client parameters.
func (k *Keeper) GetParams(ctx context.Context) types.Params {
store := k.KVStoreService.OpenKVStore(ctx)
bz, err := store.Get([]byte(types.ParamsKey))
if err != nil {
panic(err)
}
if bz == nil { // only panic on unset params and not on empty params
panic(errors.New("client params are not set in store"))
}
var params types.Params
k.cdc.MustUnmarshal(bz, ¶ms)
return params
}
// SetParams sets the total set of ibc-client parameters.
func (k *Keeper) SetParams(ctx context.Context, params types.Params) {
store := k.KVStoreService.OpenKVStore(ctx)
bz := k.cdc.MustMarshal(¶ms)
if err := store.Set([]byte(types.ParamsKey), bz); err != nil {
panic(err)
}
}
// ScheduleIBCSoftwareUpgrade schedules an upgrade for the IBC client.
func (k *Keeper) ScheduleIBCSoftwareUpgrade(ctx context.Context, plan upgradetypes.Plan, upgradedClientState exported.ClientState) error {
// zero out any custom fields before setting
cs, ok := upgradedClientState.(*ibctm.ClientState)
if !ok {
return errorsmod.Wrapf(types.ErrInvalidClientType, "expected: %T, got: %T", &ibctm.ClientState{}, upgradedClientState)
}
cs = cs.ZeroCustomFields()
bz, err := types.MarshalClientState(k.cdc, cs)
if err != nil {
return errorsmod.Wrap(err, "could not marshal UpgradedClientState")
}
if err := k.upgradeKeeper.ScheduleUpgrade(ctx, plan); err != nil {
return err
}
// sets the new upgraded client last height committed on this chain at plan.Height,
// since the chain will panic at plan.Height and new chain will resume at plan.Height
if err = k.upgradeKeeper.SetUpgradedClient(ctx, plan.Height, bz); err != nil {
return err
}
// emitting an event for scheduling an upgrade plan
return k.emitScheduleIBCSoftwareUpgradeEvent(ctx, plan.Name, plan.Height)
}