-
Notifications
You must be signed in to change notification settings - Fork 12
/
keeper.go
682 lines (591 loc) · 24.1 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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
package keeper
import (
"fmt"
"math"
"sort"
ibcchannelkeeper "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/keeper"
"github.com/functionx/fx-core/x/ibc/applications/transfer/keeper"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/functionx/fx-core/x/gravity/types"
)
// Keeper maintains the link to storage and exposes getter/setter methods for the various parts of the state machine
type Keeper struct {
StakingKeeper types.StakingKeeper
storeKey sdk.StoreKey // Unexposed key to access store from sdk.Context
paramSpace paramtypes.Subspace
cdc codec.BinaryMarshaler // The wire codec for binary encoding/decoding.
bankKeeper types.BankKeeper
ak types.AccountKeeper
SlashingKeeper types.SlashingKeeper
ibcTransferKeeper keeper.Keeper
ibcChannelKeeper ibcchannelkeeper.Keeper
AttestationHandler interface {
Handle(sdk.Context, types.Attestation, types.EthereumClaim) error
}
}
// NewKeeper returns a new instance of the gravity keeper
func NewKeeper(cdc codec.BinaryMarshaler, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, stakingKeeper types.StakingKeeper,
bankKeeper types.BankKeeper, ak types.AccountKeeper, slashingKeeper types.SlashingKeeper, ibcTransferKeeper keeper.Keeper, channelKeeper ibcchannelkeeper.Keeper) Keeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}
k := Keeper{
cdc: cdc,
paramSpace: paramSpace,
storeKey: storeKey,
StakingKeeper: stakingKeeper,
ak: ak,
bankKeeper: bankKeeper,
SlashingKeeper: slashingKeeper,
ibcTransferKeeper: ibcTransferKeeper,
ibcChannelKeeper: channelKeeper,
}
k.AttestationHandler = AttestationHandler{
keeper: k,
bankKeeper: bankKeeper,
}
return k
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
/////////////////////////////
// VALSET REQUESTS //
/////////////////////////////
// SetValsetRequest returns a new instance of the Gravity BridgeValidatorSet
// i.e. {"nonce": 1, "memebers": [{"eth_addr": "foo", "power": 11223}]}
func (k Keeper) SetValsetRequest(ctx sdk.Context, valset *types.Valset) *types.Valset {
// if valset member is empty, not store valset.
if len(valset.Members) <= 0 {
return valset
}
k.StoreValset(ctx, valset)
k.GetBridgeChainID(ctx)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeValsetUpdate,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
sdk.NewAttribute(types.AttributeKeyValsetNonce, fmt.Sprint(valset.Nonce)),
sdk.NewAttribute(types.AttributeKeyValsetLen, fmt.Sprint(len(valset.Members))),
))
return valset
}
// StoreValset is for storing a valiator set at a given height
func (k Keeper) StoreValset(ctx sdk.Context, valset *types.Valset) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetValsetKey(valset.Nonce), k.cdc.MustMarshalBinaryBare(valset))
k.SetLatestValsetNonce(ctx, valset.Nonce)
}
// SetLatestValsetNonce sets the latest valset nonce
func (k Keeper) SetLatestValsetNonce(ctx sdk.Context, nonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.LatestValsetNonce, types.UInt64Bytes(nonce))
}
// HasValsetRequest returns true if a valset defined by a nonce exists
func (k Keeper) HasValsetRequest(ctx sdk.Context, nonce uint64) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.GetValsetKey(nonce))
}
// DeleteValset deletes the valset at a given nonce from state
func (k Keeper) DeleteValset(ctx sdk.Context, nonce uint64) {
ctx.KVStore(k.storeKey).Delete(types.GetValsetKey(nonce))
}
// GetLatestValsetNonce returns the latest valset nonce
func (k Keeper) GetLatestValsetNonce(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.LatestValsetNonce)
if len(bytes) == 0 {
return 0
}
return types.UInt64FromBytes(bytes)
}
// GetValset returns a valset by nonce
func (k Keeper) GetValset(ctx sdk.Context, nonce uint64) *types.Valset {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetValsetKey(nonce))
if bz == nil {
return nil
}
var valset types.Valset
k.cdc.MustUnmarshalBinaryBare(bz, &valset)
return &valset
}
// IterateValsets retruns all valsetRequests
func (k Keeper) IterateValsets(ctx sdk.Context, cb func(key []byte, val *types.Valset) bool) {
prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ValsetRequestKey)
iter := prefixStore.ReverseIterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var valset types.Valset
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &valset)
// cb returns true to stop early
if cb(iter.Key(), &valset) {
break
}
}
}
// GetValsets returns all the validator sets in state
func (k Keeper) GetValsets(ctx sdk.Context) (out []*types.Valset) {
k.IterateValsets(ctx, func(_ []byte, val *types.Valset) bool {
out = append(out, val)
return false
})
sort.Sort(types.Valsets(out))
return
}
// GetLatestValset returns the latest validator set in state
func (k Keeper) GetLatestValset(ctx sdk.Context) (out *types.Valset) {
latestValsetNonce := k.GetLatestValsetNonce(ctx)
out = k.GetValset(ctx, latestValsetNonce)
return
}
// SetLastSlashedValsetNonce sets the latest slashed valset nonce
func (k Keeper) SetLastSlashedValsetNonce(ctx sdk.Context, nonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.LastSlashedValsetNonce, types.UInt64Bytes(nonce))
}
// GetLastSlashedValsetNonce returns the latest slashed valset nonce
func (k Keeper) GetLastSlashedValsetNonce(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.LastSlashedValsetNonce)
if len(bytes) == 0 {
return 0
}
return types.UInt64FromBytes(bytes)
}
// SetLastProposalBlockHeight sets the last unbonding block height
func (k Keeper) SetLastUnBondingBlockHeight(ctx sdk.Context, unbondingBlockHeight uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.LastUnBondingBlockHeight, types.UInt64Bytes(unbondingBlockHeight))
}
// GetLastProposalBlockHeight returns the last unbonding block height
func (k Keeper) GetLastUnBondingBlockHeight(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.LastUnBondingBlockHeight)
if len(bytes) == 0 {
return 0
}
return types.UInt64FromBytes(bytes)
}
// GetUnSlashedValsets returns all the unslashed validator sets in state
func (k Keeper) GetUnSlashedValsets(ctx sdk.Context, maxHeight uint64) (out []*types.Valset) {
lastSlashedValsetNonce := k.GetLastSlashedValsetNonce(ctx)
k.IterateValsetBySlashedValsetNonce(ctx, lastSlashedValsetNonce, maxHeight, func(_ []byte, valset *types.Valset) bool {
if valset.Nonce > lastSlashedValsetNonce {
out = append(out, valset)
}
return false
})
return
}
// IterateValsetBySlashedValsetNonce iterates through all valset by last slashed valset nonce in ASC order
func (k Keeper) IterateValsetBySlashedValsetNonce(ctx sdk.Context, lastSlashedValsetNonce uint64, maxHeight uint64, cb func([]byte, *types.Valset) bool) {
prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ValsetRequestKey)
iter := prefixStore.Iterator(types.UInt64Bytes(lastSlashedValsetNonce), types.UInt64Bytes(maxHeight))
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var valset types.Valset
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &valset)
// cb returns true to stop early
if cb(iter.Key(), &valset) {
break
}
}
}
/////////////////////////////
// VALSET CONFIRMS //
/////////////////////////////
// GetValsetConfirm returns a valset confirmation by a nonce and validator address
func (k Keeper) GetValsetConfirm(ctx sdk.Context, nonce uint64, validator sdk.AccAddress) *types.MsgValsetConfirm {
store := ctx.KVStore(k.storeKey)
entity := store.Get(types.GetValsetConfirmKey(nonce, validator))
if entity == nil {
return nil
}
confirm := types.MsgValsetConfirm{}
k.cdc.MustUnmarshalBinaryBare(entity, &confirm)
return &confirm
}
// SetValsetConfirm sets a valset confirmation
func (k Keeper) SetValsetConfirm(ctx sdk.Context, valsetConf types.MsgValsetConfirm) []byte {
store := ctx.KVStore(k.storeKey)
addr, err := sdk.AccAddressFromBech32(valsetConf.Orchestrator)
if err != nil {
panic(err)
}
key := types.GetValsetConfirmKey(valsetConf.Nonce, addr)
store.Set(key, k.cdc.MustMarshalBinaryBare(&valsetConf))
return key
}
// GetValsetConfirms returns all validator set confirmations by nonce
func (k Keeper) GetValsetConfirms(ctx sdk.Context, nonce uint64) (confirms []*types.MsgValsetConfirm) {
prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ValsetConfirmKey)
start, end := prefixRange(types.UInt64Bytes(nonce))
iterator := prefixStore.Iterator(start, end)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
confirm := types.MsgValsetConfirm{}
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &confirm)
confirms = append(confirms, &confirm)
}
return confirms
}
// IterateValsetConfirmByNonce iterates through all valset confirms by nonce in ASC order
// MARK finish-batches: this is where the key is iterated in the old (presumed working) code
func (k Keeper) IterateValsetConfirmByNonce(ctx sdk.Context, nonce uint64, cb func([]byte, types.MsgValsetConfirm) bool) {
prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ValsetConfirmKey)
iter := prefixStore.Iterator(prefixRange(types.UInt64Bytes(nonce)))
defer iter.Close()
for ; iter.Valid(); iter.Next() {
confirm := types.MsgValsetConfirm{}
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &confirm)
// cb returns true to stop early
if cb(iter.Key(), confirm) {
break
}
}
}
/////////////////////////////
// BATCH CONFIRMS //
/////////////////////////////
// GetBatchConfirm returns a batch confirmation given its nonce, the token contract, and a validator address
func (k Keeper) GetBatchConfirm(ctx sdk.Context, nonce uint64, tokenContract string, validator sdk.AccAddress) *types.MsgConfirmBatch {
store := ctx.KVStore(k.storeKey)
entity := store.Get(types.GetBatchConfirmKey(tokenContract, nonce, validator))
if entity == nil {
return nil
}
confirm := types.MsgConfirmBatch{}
k.cdc.MustUnmarshalBinaryBare(entity, &confirm)
return &confirm
}
// SetBatchConfirm sets a batch confirmation by a validator
func (k Keeper) SetBatchConfirm(ctx sdk.Context, batch *types.MsgConfirmBatch) []byte {
store := ctx.KVStore(k.storeKey)
acc, err := sdk.AccAddressFromBech32(batch.Orchestrator)
if err != nil {
panic(err)
}
key := types.GetBatchConfirmKey(batch.TokenContract, batch.Nonce, acc)
store.Set(key, k.cdc.MustMarshalBinaryBare(batch))
return key
}
// IterateBatchConfirmByNonceAndTokenContract iterates through all batch confirmations
// MARK finish-batches: this is where the key is iterated in the old (presumed working) code
func (k Keeper) IterateBatchConfirmByNonceAndTokenContract(ctx sdk.Context, nonce uint64, tokenContract string, cb func([]byte, types.MsgConfirmBatch) bool) {
prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.BatchConfirmKey)
prefixKey := append([]byte(tokenContract), types.UInt64Bytes(nonce)...)
iter := prefixStore.Iterator(prefixRange(prefixKey))
defer iter.Close()
for ; iter.Valid(); iter.Next() {
confirm := types.MsgConfirmBatch{}
k.cdc.MustUnmarshalBinaryBare(iter.Value(), &confirm)
// cb returns true to stop early
if cb(iter.Key(), confirm) {
break
}
}
}
// GetBatchConfirmByNonceAndTokenContract returns the batch confirms
func (k Keeper) GetBatchConfirmByNonceAndTokenContract(ctx sdk.Context, nonce uint64, tokenContract string) (out []types.MsgConfirmBatch) {
k.IterateBatchConfirmByNonceAndTokenContract(ctx, nonce, tokenContract, func(_ []byte, msg types.MsgConfirmBatch) bool {
out = append(out, msg)
return false
})
return
}
/////////////////////////////
// ADDRESS DELEGATION //
/////////////////////////////
// SetOrchestratorOracle sets the Orchestrator key for a given validator
func (k Keeper) SetOrchestratorValidator(ctx sdk.Context, val sdk.ValAddress, orch sdk.AccAddress) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetOrchestratorAddressKey(orch), val.Bytes())
}
// GetOrchestratorOracle returns the validator key associated with an orchestrator key
func (k Keeper) GetOrchestratorValidator(ctx sdk.Context, orch sdk.AccAddress) (valAddr sdk.ValAddress, found bool) {
store := ctx.KVStore(k.storeKey)
valAddr = store.Get(types.GetOrchestratorAddressKey(orch))
return valAddr, valAddr != nil
}
/////////////////////////////
// ETH ADDRESS //
/////////////////////////////
// SetEthAddressForValidator sets the ethereum address for a given validator
func (k Keeper) SetEthAddressForValidator(ctx sdk.Context, validator sdk.ValAddress, ethAddr string) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetEthAddressByValidatorKey(validator), []byte(ethAddr))
store.Set(types.GetValidatorByEthAddressKey(ethAddr), validator.Bytes())
}
// GetEthAddressByValidator returns the eth address for a given gravity validator
func (k Keeper) GetEthAddressByValidator(ctx sdk.Context, validator sdk.ValAddress) (ethAddress string, found bool) {
store := ctx.KVStore(k.storeKey)
ethAddr := store.Get(types.GetEthAddressByValidatorKey(validator))
if len(ethAddr) <= 0 || ethAddr == nil {
return "", false
} else {
return string(ethAddr), true
}
}
// GetValidatorByEthAddress returns the eth address for a given gravity validator
func (k Keeper) GetValidatorByEthAddress(ctx sdk.Context, ethAddr string) string {
store := ctx.KVStore(k.storeKey)
return string(store.Get(types.GetValidatorByEthAddressKey(ethAddr)))
}
// DelEthAddressForValidator delete the ethereum address for a give validator
func (k Keeper) DelEthAddressForValidator(ctk sdk.Context, validator sdk.ValAddress) {
store := ctk.KVStore(k.storeKey)
// Delete the ETH address of the verifier
ethAddrByValidatorKey := types.GetEthAddressByValidatorKey(validator)
if !store.Has(ethAddrByValidatorKey) {
return
}
store.Delete(ethAddrByValidatorKey)
// Delete the verifier address corresponding to the ETH address
ethAddress := store.Get(ethAddrByValidatorKey)
validatorByEthAddrKey := types.GetValidatorByEthAddressKey(string(ethAddress))
if store.Has(validatorByEthAddrKey) {
return
}
store.Delete(validatorByEthAddrKey)
}
// GetCurrentValset gets powers from the store and normalizes them
// into an integer percentage with a resolution of uint32 Max meaning
// a given validators 'gravity power' is computed as
// Cosmos power / total cosmos power = x / uint32 Max
// where x is the voting power on the gravity contract. This allows us
// to only use integer division which produces a known rounding error
// from truncation equal to the ratio of the validators
// Cosmos power / total cosmos power ratio, leaving us at uint32 Max - 1
// total voting power. This is an acceptable rounding error since floating
// point may cause consensus problems if different floating point unit
// implementations are involved.
func (k Keeper) GetCurrentValset(ctx sdk.Context) *types.Valset {
validators := k.StakingKeeper.GetBondedValidatorsByPower(ctx)
var bridgeValidators []*types.BridgeValidator
var totalPower uint64
for _, validator := range validators {
val := validator.GetOperator()
ethAddr, found := k.GetEthAddressByValidator(ctx, val)
if !found {
continue
}
power := uint64(k.StakingKeeper.GetLastValidatorPower(ctx, val))
totalPower += power
bridgeValidators = append(bridgeValidators, &types.BridgeValidator{
Power: power,
EthAddress: ethAddr,
})
}
// normalize power values
for i := range bridgeValidators {
bridgeValidators[i].Power = sdk.NewUint(bridgeValidators[i].Power).MulUint64(math.MaxUint32).QuoUint64(totalPower).Uint64()
}
return types.NewValset(uint64(ctx.BlockHeight()), uint64(ctx.BlockHeight()), bridgeValidators)
}
/////////////////////////////
// PARAMETERS //
/////////////////////////////
// GetParams returns the parameters from the store
func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) {
k.paramSpace.GetParamSet(ctx, ¶ms)
return
}
// SetParams sets the parameters in the store
func (k Keeper) SetParams(ctx sdk.Context, ps types.Params) {
k.paramSpace.SetParamSet(ctx, &ps)
}
// GetBridgeContractAddress returns the bridge contract address on ETH
func (k Keeper) GetBridgeContractAddress(ctx sdk.Context) string {
var a string
k.paramSpace.Get(ctx, types.ParamsStoreKeyBridgeContractAddress, &a)
return a
}
// GetBridgeChainID returns the chain id of the ETH chain we are running against
func (k Keeper) GetBridgeChainID(ctx sdk.Context) uint64 {
var a uint64
k.paramSpace.Get(ctx, types.ParamsStoreKeyBridgeContractChainID, &a)
return a
}
// GetGravityID returns the GravityID the GravityID is essentially a salt value
// for bridge signatures, provided each chain running Gravity has a unique ID
// it won't be possible to play back signatures from one bridge onto another
// even if they share a validator set.
//
// The lifecycle of the GravityID is that it is set in the Genesis file
// read from the live chain for the contract deployment, once a Gravity contract
// is deployed the GravityID CAN NOT BE CHANGED. Meaning that it can't just be the
// same as the chain id since the chain id may be changed many times with each
// successive chain in charge of the same bridge
func (k Keeper) GetGravityID(ctx sdk.Context) string {
var a string
k.paramSpace.Get(ctx, types.ParamsStoreKeyGravityID, &a)
return a
}
// SetGravityID Set GravityID sets the GravityID the GravityID is essentially a salt value
// for bridge signatures, provided each chain running Gravity has a unique ID
// it won't be possible to play back signatures from one bridge onto another
// even if they share a validator set.
//
// The lifecycle of the GravityID is that it is set in the Genesis file
// read from the live chain for the contract deployment, once a Gravity contract
// is deployed the GravityID CAN NOT BE CHANGED. Meaning that it can't just be the
// same as the chain id since the chain id may be changed many times with each
// successive chain in charge of the same bridge
func (k Keeper) SetGravityID(ctx sdk.Context, v string) {
k.paramSpace.Set(ctx, types.ParamsStoreKeyGravityID, v)
}
func (k Keeper) UnpackAttestationClaim(att *types.Attestation) (types.EthereumClaim, error) {
var msg types.EthereumClaim
err := k.cdc.UnpackAny(att.Claim, &msg)
if err != nil {
return nil, err
} else {
return msg, nil
}
}
// GetDelegateKeys iterates both the EthAddress and Orchestrator address indexes to produce
// a vector of MsgSetOrchestratorAddress entires containing all the delgate keys for state
// export / import. This may seem at first glance to be excessively complicated, why not combine
// the EthAddress and Orchestrator address indexes and simply iterate one thing? The answer is that
// even though we set the Eth and Orchestrator address in the same place we use them differently we
// always go from Orchestrator address to Validator address and from validator address to Ethereum address
// we want to keep looking up the validator address for various reasons, so a direct Orchestrator to Ethereum
// address mapping will mean having to keep two of the same data around just to provide lookups.
//
// For the time being this will serve
func (k Keeper) GetDelegateKeys(ctx sdk.Context) []*types.MsgSetOrchestratorAddress {
store := ctx.KVStore(k.storeKey)
iter := store.Iterator(prefixRange(types.EthAddressByValidatorKey))
defer iter.Close()
ethAddresses := make(map[string]string)
for ; iter.Valid(); iter.Next() {
// the 'key' contains both the prefix and the value, so we need
// to cut off the starting bytes, if you don't do this a valid
// cosmos key will be made out of EthAddressKey + the startin bytes
// of the actual key
key := iter.Key()[len(types.EthAddressByValidatorKey):]
value := iter.Value()
ethAddress := string(value)
valAddress := sdk.ValAddress(key)
ethAddresses[valAddress.String()] = ethAddress
}
store = ctx.KVStore(k.storeKey)
iter = store.Iterator(prefixRange(types.KeyOrchestratorAddress))
defer iter.Close()
orchAddresses := make(map[string]string)
for ; iter.Valid(); iter.Next() {
key := iter.Key()[len(types.KeyOrchestratorAddress):]
value := iter.Value()
orchAddress := sdk.AccAddress(key).String()
valAddress := sdk.ValAddress(value)
orchAddresses[valAddress.String()] = orchAddress
}
var result []*types.MsgSetOrchestratorAddress
for valAddr, ethAddr := range ethAddresses {
orch, ok := orchAddresses[valAddr]
if !ok {
// this should never happen unless the store
// is somehow inconsistent
panic("Can't find address")
}
result = append(result, &types.MsgSetOrchestratorAddress{
Orchestrator: orch,
Validator: valAddr,
EthAddress: ethAddr,
})
}
// we iterated over a map, so now we have to sort to ensure the
// output here is deterministic, eth address chosen for no particular
// reason
sort.Slice(result[:], func(i, j int) bool {
return result[i].EthAddress < result[j].EthAddress
})
return result
}
// GetUnbondingValidators returns UnbondingValidators.
// Adding here in gravity keeper as cdc is available inside endblocker.
func (k Keeper) GetUnbondingValidators(unbondingVals []byte) stakingtypes.ValAddresses {
unbondingValidators := stakingtypes.ValAddresses{}
k.cdc.MustUnmarshalBinaryBare(unbondingVals, &unbondingValidators)
return unbondingValidators
}
// prefixRange turns a prefix into a (start, end) range. The start is the given prefix value and
// the end is calculated by adding 1 bit to the start value. Nil is not allowed as prefix.
//
// Example: []byte{1, 3, 4} becomes []byte{1, 3, 5}
// []byte{15, 42, 255, 255} becomes []byte{15, 43, 0, 0}
//
// In case of an overflow the end is set to nil.
//
// Example: []byte{255, 255, 255, 255} becomes nil
//
// MARK finish-batches: this is where some crazy shit happens
func prefixRange(prefix []byte) ([]byte, []byte) {
if prefix == nil {
panic("nil key not allowed")
}
// special case: no prefix is whole range
if len(prefix) == 0 {
return nil, nil
}
// copy the prefix and update last byte
end := make([]byte, len(prefix))
copy(end, prefix)
l := len(end) - 1
end[l]++
// wait, what if that overflowed?....
for end[l] == 0 && l > 0 {
l--
end[l]++
}
// okay, funny guy, you gave us FFF, no end to this range...
if l == 0 && end[0] == 0 {
end = nil
}
return prefix, end
}
func (k Keeper) HandlerIbcTransactionAfter(ctx sdk.Context, sender, receive string, coin, fee sdk.Coin) error {
sendAddress, err := sdk.AccAddressFromBech32(sender)
if err != nil {
return err
}
_, err = k.AddToOutgoingPool(ctx, sendAddress, receive, coin, fee)
return err
}
// SetIbcSequenceHeight set gravity -> ibc sequence block height.
func (k Keeper) SetIbcSequenceHeight(ctx sdk.Context, sourcePort, sourceChannel string, sequence, height uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetIbcSequenceHeightKey(sourcePort, sourceChannel, sequence), types.UInt64Bytes(height))
}
// GetIbcSequenceHeight get gravity -> ibc sequence block height.
func (k Keeper) GetIbcSequenceHeight(ctx sdk.Context, sourcePort, sourceChannel string, sequence uint64) (uint64, bool) {
store := ctx.KVStore(k.storeKey)
key := types.GetIbcSequenceHeightKey(sourcePort, sourceChannel, sequence)
if !store.Has(key) {
return 0, false
}
value := store.Get(key)
return types.UInt64FromBytes(value), true
}
// setLastEventBlockHeightByValidator set the latest event blockHeight for a give validator
func (k Keeper) setLastEventBlockHeightByValidator(ctx sdk.Context, validator sdk.ValAddress, blockHeight uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetLastEventBlockHeightByValidatorKey(validator), types.UInt64Bytes(blockHeight))
}
// getLastEventBlockHeightByValidator get the latest event blockHeight for a give validator
func (k Keeper) getLastEventBlockHeightByValidator(ctx sdk.Context, validator sdk.ValAddress) uint64 {
store := ctx.KVStore(k.storeKey)
key := types.GetLastEventBlockHeightByValidatorKey(validator)
if !store.Has(key) {
return 0
}
data := store.Get(key)
return sdk.BigEndianToUint64(data)
}