-
Notifications
You must be signed in to change notification settings - Fork 39
/
keeper.go
422 lines (341 loc) · 12.8 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
package keeper
import (
"bytes"
"encoding/binary"
"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"
"github.com/ethereum/go-ethereum/common"
"github.com/peggyjv/sommelier/v6/x/cork/types"
"github.com/tendermint/tendermint/libs/log"
)
// Keeper of the oracle store
type Keeper struct {
storeKey sdk.StoreKey
cdc codec.BinaryCodec
paramSpace paramtypes.Subspace
stakingKeeper types.StakingKeeper
gravityKeeper types.GravityKeeper
}
// NewKeeper creates a new distribution Keeper instance
func NewKeeper(
cdc codec.BinaryCodec, key sdk.StoreKey, paramSpace paramtypes.Subspace,
stakingKeeper types.StakingKeeper, gravityKeeper types.GravityKeeper,
) Keeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}
return Keeper{
storeKey: key,
cdc: cdc,
paramSpace: paramSpace,
stakingKeeper: stakingKeeper,
gravityKeeper: gravityKeeper,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
///////////////////////
// MsgSubmitCork //
///////////////////////
// SetCork sets the prevote for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) SetCork(ctx sdk.Context, val sdk.ValAddress, cork types.Cork) {
bz := k.cdc.MustMarshal(&cork)
ctx.KVStore(k.storeKey).Set(types.GetCorkForValidatorAddressKey(val, common.HexToAddress(cork.TargetContractAddress)), bz)
}
// GetCork gets the prevote for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) GetCork(ctx sdk.Context, val sdk.ValAddress, contract common.Address) (types.Cork, bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetCorkForValidatorAddressKey(val, contract))
if len(bz) == 0 {
return types.Cork{}, false
}
var cork types.Cork
k.cdc.MustUnmarshal(bz, &cork)
return cork, true
}
// DeleteCork deletes the prevote for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) DeleteCork(ctx sdk.Context, val sdk.ValAddress, contract common.Address) {
ctx.KVStore(k.storeKey).Delete(types.GetCorkForValidatorAddressKey(val, contract))
}
// HasCorkForContract gets the prevote for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) HasCorkForContract(ctx sdk.Context, val sdk.ValAddress, contract common.Address) bool {
return ctx.KVStore(k.storeKey).Has(types.GetCorkForValidatorAddressKey(val, contract))
}
// HasCork gets the existence of any commit for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) HasCork(ctx sdk.Context, val sdk.ValAddress) bool {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetCorkValidatorKeyPrefix(val))
iter := store.Iterator(nil, nil)
defer iter.Close()
return iter.Valid()
}
// IterateCorks iterates over all votes in the store
func (k Keeper) IterateCorks(ctx sdk.Context, handler func(val sdk.ValAddress, contract common.Address, cork types.Cork) (stop bool)) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, []byte{types.CorkForAddressKeyPrefix})
defer iter.Close()
for ; iter.Valid(); iter.Next() {
keyPair := bytes.NewBuffer(bytes.TrimPrefix(iter.Key(), []byte{types.CorkForAddressKeyPrefix}))
val := sdk.ValAddress(keyPair.Next(20))
contract := common.BytesToAddress(keyPair.Bytes())
var cork types.Cork
k.cdc.MustUnmarshal(iter.Value(), &cork)
if handler(val, contract, cork) {
break
}
}
}
func (k Keeper) GetValidatorCorks(ctx sdk.Context) []*types.ValidatorCork {
var validatorCorks []*types.ValidatorCork
k.IterateCorks(ctx, func(val sdk.ValAddress, _ common.Address, cork types.Cork) (stop bool) {
validatorCorks = append(validatorCorks, &types.ValidatorCork{
Validator: val.String(),
Cork: &cork,
})
return false
})
return validatorCorks
}
/////////////////////
// Scheduled Corks //
/////////////////////
func (k Keeper) SetScheduledCork(ctx sdk.Context, blockHeight uint64, val sdk.ValAddress, cork types.Cork) {
bz := k.cdc.MustMarshal(&cork)
ctx.KVStore(k.storeKey).Set(types.GetScheduledCorkKey(blockHeight, val, common.HexToAddress(cork.TargetContractAddress)), bz)
}
// GetScheduledCork gets the scheduled cork for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) GetScheduledCork(ctx sdk.Context, val sdk.ValAddress, blockHeight uint64, contract common.Address) (types.Cork, bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetScheduledCorkKey(blockHeight, val, contract))
if len(bz) == 0 {
return types.Cork{}, false
}
var cork types.Cork
k.cdc.MustUnmarshal(bz, &cork)
return cork, true
}
// DeleteScheduledCork deletes the scheduled cork for a given validator
// CONTRACT: must provide the validator address here not the delegate address
func (k Keeper) DeleteScheduledCork(ctx sdk.Context, val sdk.ValAddress, blockHeight uint64, contract common.Address) {
ctx.KVStore(k.storeKey).Delete(types.GetScheduledCorkKey(blockHeight, val, contract))
}
// IterateScheduledCorks iterates over all scheduled corks in the store
func (k Keeper) IterateScheduledCorks(ctx sdk.Context, cb func(val sdk.ValAddress, blockHeight uint64, cel common.Address, cork types.Cork) (stop bool)) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, []byte{types.ScheduledCorkKeyPrefix})
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var cork types.Cork
keyPair := bytes.NewBuffer(bytes.TrimPrefix(iter.Key(), []byte{types.ScheduledCorkKeyPrefix}))
blockHeight := binary.BigEndian.Uint64(keyPair.Next(8))
val := sdk.ValAddress(keyPair.Next(20))
cel := common.BytesToAddress(keyPair.Bytes())
k.cdc.MustUnmarshal(iter.Value(), &cork)
if cb(val, blockHeight, cel, cork) {
break
}
}
}
func (k Keeper) GetScheduledCorks(ctx sdk.Context) []*types.ScheduledCork {
var scheduledCorks []*types.ScheduledCork
k.IterateScheduledCorks(ctx, func(val sdk.ValAddress, blockHeight uint64, _ common.Address, cork types.Cork) (stop bool) {
scheduledCorks = append(scheduledCorks, &types.ScheduledCork{
Validator: val.String(),
Cork: &cork,
BlockHeight: blockHeight,
})
return false
})
return scheduledCorks
}
func (k Keeper) GetScheduledCorksByBlockHeight(ctx sdk.Context, height uint64) []*types.ScheduledCork {
var scheduledCorks []*types.ScheduledCork
k.IterateScheduledCorks(ctx, func(val sdk.ValAddress, blockHeight uint64, _ common.Address, cork types.Cork) (stop bool) {
if blockHeight == height {
scheduledCorks = append(scheduledCorks, &types.ScheduledCork{
Validator: val.String(),
Cork: &cork,
BlockHeight: blockHeight,
})
}
if blockHeight > height {
return true
}
return false
})
return scheduledCorks
}
///////////////////////////
// ScheduledBlockHeights //
///////////////////////////
func (k Keeper) GetScheduledBlockHeights(ctx sdk.Context) []uint64 {
var heights []uint64
latestHeight := uint64(0)
k.IterateScheduledCorks(ctx, func(_ sdk.ValAddress, blockHeight uint64, _ common.Address, _ types.Cork) (stop bool) {
if blockHeight > latestHeight {
heights = append(heights, blockHeight)
}
latestHeight = blockHeight
return false
})
return heights
}
//////////////////
// CommitPeriod //
//////////////////
// SetCommitPeriodStart sets the current vote period start height
func (k Keeper) SetCommitPeriodStart(ctx sdk.Context, height int64) {
store := ctx.KVStore(k.storeKey)
store.Set([]byte{types.CommitPeriodStartKey}, sdk.Uint64ToBigEndian(uint64(height)))
}
// GetCommitPeriodStart returns the vote period start height
func (k Keeper) GetCommitPeriodStart(ctx sdk.Context) (int64, bool) {
store := ctx.KVStore(k.storeKey)
bz := store.Get([]byte{types.CommitPeriodStartKey})
if len(bz) == 0 {
return 0, false
}
return int64(sdk.BigEndianToUint64(bz)), true
}
// HasCommitPeriodStart returns true if the vote period start has been set
func (k Keeper) HasCommitPeriodStart(ctx sdk.Context) bool {
return ctx.KVStore(k.storeKey).Has([]byte{types.CommitPeriodStartKey})
}
////////////
// Params //
////////////
// GetParamSet returns the vote period from the parameters
func (k Keeper) GetParamSet(ctx sdk.Context) types.Params {
var p types.Params
k.paramSpace.GetParamSet(ctx, &p)
return p
}
// setParams sets the parameters in the store
func (k Keeper) setParams(ctx sdk.Context, params types.Params) {
k.paramSpace.SetParamSet(ctx, ¶ms)
}
/////////////////////////
// Invalidation Nonces //
/////////////////////////
func (k Keeper) GetLatestInvalidationNonce(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bz := store.Get([]byte{types.LatestInvalidationNonceKey})
return sdk.BigEndianToUint64(bz)
}
func (k Keeper) SetLatestInvalidationNonce(ctx sdk.Context, invalidationNonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set([]byte{types.LatestInvalidationNonceKey}, sdk.Uint64ToBigEndian(invalidationNonce))
}
func (k Keeper) IncrementInvalidationNonce(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
nextNonce := k.GetLatestInvalidationNonce(ctx) + 1
store.Set([]byte{types.LatestInvalidationNonceKey}, sdk.Uint64ToBigEndian(nextNonce))
return nextNonce
}
///////////
// Votes //
///////////
func (k Keeper) GetApprovedCorks(ctx sdk.Context, threshold sdk.Dec) (approvedCorks []types.Cork) {
var corks []types.Cork
var corkPowers []int64
totalPower := k.stakingKeeper.GetLastTotalPower(ctx)
k.IterateCorks(ctx, func(val sdk.ValAddress, addr common.Address, cork types.Cork) (stop bool) {
validator := k.stakingKeeper.Validator(ctx, val)
validatorPower := validator.GetConsensusPower(k.stakingKeeper.PowerReduction(ctx))
found := false
for i, c := range corks {
if c.Equals(cork) {
corkPowers[i] += validatorPower
found = true
break
}
}
if !found {
corks = append(corks, cork)
corkPowers = append(corkPowers, validatorPower)
}
k.DeleteCork(ctx, val, addr)
return false
})
var winningCorks []types.Cork
for i, power := range corkPowers {
quorumReached := sdk.NewDec(power).Quo(totalPower.ToDec()).GT(threshold)
if quorumReached {
winningCorks = append(winningCorks, corks[i])
}
}
return winningCorks
}
func (k Keeper) GetApprovedScheduledCorks(ctx sdk.Context, currentBlockHeight uint64, threshold sdk.Dec) (approvedCorks []types.Cork) {
corksForBlockHeight := make(map[uint64][]types.Cork)
corkPowersForBlockHeight := make(map[uint64][]uint64)
totalPower := k.stakingKeeper.GetLastTotalPower(ctx)
k.IterateScheduledCorks(ctx, func(val sdk.ValAddress, scheduledBlockHeight uint64, addr common.Address, cork types.Cork) (stop bool) {
if currentBlockHeight != scheduledBlockHeight {
// only operate on scheduled corksForBlockHeight that are valid, quit early when a further one is found
return true
}
validator := k.stakingKeeper.Validator(ctx, val)
validatorPower := uint64(validator.GetConsensusPower(k.stakingKeeper.PowerReduction(ctx)))
found := false
for i, c := range corksForBlockHeight[scheduledBlockHeight] {
if c.Equals(cork) {
corkPowersForBlockHeight[scheduledBlockHeight][i] += validatorPower
found = true
break
}
}
if !found {
corksForBlockHeight[scheduledBlockHeight] = append(corksForBlockHeight[scheduledBlockHeight], cork)
corkPowersForBlockHeight[scheduledBlockHeight] = append(corkPowersForBlockHeight[scheduledBlockHeight], validatorPower)
}
k.DeleteScheduledCork(ctx, val, scheduledBlockHeight, addr)
return false
})
for blockHeight := range corkPowersForBlockHeight {
for i, power := range corkPowersForBlockHeight[blockHeight] {
quorumReached := sdk.NewIntFromUint64(power).ToDec().Quo(totalPower.ToDec()).GT(threshold)
if quorumReached {
approvedCorks = append(approvedCorks, corksForBlockHeight[blockHeight][i])
}
}
}
return approvedCorks
}
/////////////
// Cellars //
/////////////
func (k Keeper) SetCellarIDs(ctx sdk.Context, c types.CellarIDSet) {
bz := k.cdc.MustMarshal(&c)
ctx.KVStore(k.storeKey).Set(types.MakeCellarIDsKey(), bz)
}
func (k Keeper) GetCellarIDs(ctx sdk.Context) (cellars []common.Address) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.MakeCellarIDsKey())
var cids types.CellarIDSet
k.cdc.MustUnmarshal(bz, &cids)
for _, cid := range cids.Ids {
cellars = append(cellars, common.HexToAddress(cid))
}
return cellars
}
func (k Keeper) HasCellarID(ctx sdk.Context, address common.Address) (found bool) {
found = false
for _, id := range k.GetCellarIDs(ctx) {
if id == address {
found = true
break
}
}
return found
}