forked from yihuang/gravity-bridge
/
ethereum_event_vote.go
302 lines (268 loc) · 12.2 KB
/
ethereum_event_vote.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
package keeper
import (
"encoding/binary"
"fmt"
"strconv"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/peggyjv/gravity-bridge/module/v2/x/gravity/types"
)
func (k Keeper) recordEventVote(
ctx sdk.Context,
event types.EthereumEvent,
val sdk.ValAddress,
) (*types.EthereumEventVoteRecord, error) {
// Check that the nonce of this event is exactly one higher than the last nonce stored by this validator.
// We check the event nonce in processEthereumEvent as well,
// but checking it here gives individual eth signers a chance to retry,
// and prevents validators from submitting two claims with the same nonce
lastEventNonce := k.getLastEventNonceByValidator(ctx, val)
expectedNonce := lastEventNonce + 1
if event.GetEventNonce() != expectedNonce {
return nil, sdkerrors.Wrapf(types.ErrInvalid,
"non contiguous event nonce expected %v observed %v for validator %v",
expectedNonce,
event.GetEventNonce(),
val,
)
}
// Tries to get an EthereumEventVoteRecord with the same eventNonce and event as the event that was submitted.
eventVoteRecord := k.GetEthereumEventVoteRecord(ctx, event.GetEventNonce(), event.Hash())
// If it does not exist, create a new one.
if eventVoteRecord == nil {
any, err := types.PackEvent(event)
if err != nil {
return nil, err
}
eventVoteRecord = &types.EthereumEventVoteRecord{
Accepted: false,
Event: any,
}
}
// Add the validator's vote to this EthereumEventVoteRecord
eventVoteRecord.Votes = append(eventVoteRecord.Votes, val.String())
k.setEthereumEventVoteRecord(ctx, event.GetEventNonce(), event.Hash(), eventVoteRecord)
k.setLastEventNonceByValidator(ctx, val, event.GetEventNonce())
return eventVoteRecord, nil
}
// TryEventVoteRecord checks if an event vote record has enough votes to be applied to the consensus state
// and has not already been marked Observed, then calls processEthereumEvent to actually apply it to the state,
// and then marks it Observed and emits an event.
func (k Keeper) TryEventVoteRecord(ctx sdk.Context, eventVoteRecord *types.EthereumEventVoteRecord) {
// If the event vote record has not yet been Observed, sum up the votes and see if it is ready to apply to the state.
// This conditional stops the event vote record from accidentally being applied twice.
if !eventVoteRecord.Accepted {
var event types.EthereumEvent
if err := k.cdc.UnpackAny(eventVoteRecord.Event, &event); err != nil {
k.DisableBridge(ctx)
k.Logger(ctx).Error("TryEventVoteRecord: unpacking packed any")
return
}
// Sum the current powers of all validators who have voted and see if it passes the current threshold
// TODO: The different integer types and math here needs a careful review
requiredPower := types.EventVoteRecordPowerThreshold(k.StakingKeeper.GetLastTotalPower(ctx))
eventVotePower := sdk.NewInt(0)
for _, validator := range eventVoteRecord.Votes {
val, _ := sdk.ValAddressFromBech32(validator)
validatorPower := k.StakingKeeper.GetLastValidatorPower(ctx, val)
// Add it to the attestation power's sum
eventVotePower = eventVotePower.Add(sdk.NewInt(validatorPower))
// If the power of all the validators that have voted on the attestation is higher or equal to the threshold,
// process the attestation, set Observed to true, and break
if eventVotePower.GTE(requiredPower) {
lastEventNonce := k.GetLastObservedEventNonce(ctx)
// this check is performed at the next level up so this should never happen
// outside of programmer error.
if event.GetEventNonce() != lastEventNonce+1 {
k.DisableBridge(ctx)
k.Logger(ctx).Error(
"TryEventVoteRecord: attempting to apply events to state out of order")
return
}
k.setLastObservedEventNonce(ctx, event.GetEventNonce())
// check that the ethereum block height recorded is lower than the attestation height
ethWithCosmosHeight := k.GetLastObservedEthereumBlockHeight(ctx)
if ethWithCosmosHeight.EthereumHeight > event.GetEthereumHeight() {
// Log the error.
// While technically this should not happen with the new oracle msg ordering,
// it could happen that the UpdateHeight msg is ordered before the AttestationVote (if using
// a load balancer for example) and thus having a higher height recorded in the chain.
// This should not have critical impact unless the difference between the height recorded
// exceed TargetEthTxTimeout
k.Logger(ctx).Error(
"TryEventVoteRecord: attempting to process events that may have been expired")
} else {
k.SetLastObservedEthereumBlockHeight(ctx, event.GetEthereumHeight())
}
eventVoteRecord.Accepted = true
k.setEthereumEventVoteRecord(ctx, event.GetEventNonce(), event.Hash(), eventVoteRecord)
k.processEthereumEvent(ctx, event)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeObservation,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
sdk.NewAttribute(types.AttributeKeyEthereumEventType, fmt.Sprintf("%T", event)),
sdk.NewAttribute(types.AttributeKeyContract, k.getBridgeContractAddress(ctx)),
sdk.NewAttribute(types.AttributeKeyBridgeChainID, strconv.Itoa(int(k.getBridgeChainID(ctx)))),
sdk.NewAttribute(types.AttributeKeyEthereumEventVoteRecordID,
string(types.MakeEthereumEventVoteRecordKey(event.GetEventNonce(), event.Hash()))),
sdk.NewAttribute(types.AttributeKeyNonce, fmt.Sprint(event.GetEventNonce())),
))
break
}
}
} else {
// We disable the bridge here because this should never happen
k.DisableBridge(ctx)
k.Logger(ctx).Error(
"TryEventVoteRecord: attempting to process observed ethereum event")
return
}
}
// processEthereumEvent actually applies the attestation to the consensus state
func (k Keeper) processEthereumEvent(ctx sdk.Context, event types.EthereumEvent) {
// then execute in a new Tx so that we can store state on failure
xCtx, commit := ctx.CacheContext()
if err := k.Handle(xCtx, event); err != nil { // execute with a transient storage
// If the attestation fails, something has gone wrong and we can't recover it. Disable the bridge,
// log the error and move on
// The attestation will still be marked "Observed", and validators can still be slashed for not
// having voted for it.
k.DisableBridge(ctx)
k.Logger(ctx).Error(
"ethereum event vote record failed",
"cause", err.Error(),
"event type", fmt.Sprintf("%T", event),
"id", types.MakeEthereumEventVoteRecordKey(event.GetEventNonce(), event.Hash()),
"nonce", fmt.Sprint(event.GetEventNonce()),
)
} else {
ctx.EventManager().EmitEvents(xCtx.EventManager().Events()) // copy events to original context
commit() // persist transient storage
}
}
// setEthereumEventVoteRecord sets the attestation in the store
func (k Keeper) setEthereumEventVoteRecord(ctx sdk.Context, eventNonce uint64, claimHash []byte, eventVoteRecord *types.EthereumEventVoteRecord) {
ctx.KVStore(k.storeKey).Set(types.MakeEthereumEventVoteRecordKey(eventNonce, claimHash), k.cdc.MustMarshal(eventVoteRecord))
}
// GetEthereumEventVoteRecord return a vote record given a nonce
func (k Keeper) GetEthereumEventVoteRecord(ctx sdk.Context, eventNonce uint64, claimHash []byte) *types.EthereumEventVoteRecord {
if bz := ctx.KVStore(k.storeKey).Get(types.MakeEthereumEventVoteRecordKey(eventNonce, claimHash)); bz == nil {
return nil
} else {
var out types.EthereumEventVoteRecord
k.cdc.MustUnmarshal(bz, &out)
return &out
}
}
// DeleteEthereumEventVoteRecord deletes a vote record
func (k Keeper) DeleteEthereumEventVoteRecord(ctx sdk.Context, eventVoteRecord *types.EthereumEventVoteRecord) {
event, err := types.UnpackEvent(eventVoteRecord.Event)
if err != nil {
k.DisableBridge(ctx)
k.Logger(ctx).Error(
fmt.Sprintf("DeleteEthereumEventVoteRecord: couldn't cast to event: %s", err))
return
}
ctx.KVStore(k.storeKey).Delete(types.MakeEthereumEventVoteRecordKey(event.GetEventNonce(), event.Hash()))
}
// GetEthereumEventVoteRecordMapping returns a mapping of eventnonce -> attestations at that nonce
func (k Keeper) GetEthereumEventVoteRecordMapping(ctx sdk.Context) (out map[uint64][]*types.EthereumEventVoteRecord) {
out = make(map[uint64][]*types.EthereumEventVoteRecord)
k.iterateEthereumEventVoteRecords(ctx, func(key []byte, eventVoteRecord *types.EthereumEventVoteRecord) bool {
event, err := types.UnpackEvent(eventVoteRecord.Event)
if err != nil {
panic(err)
}
if val, ok := out[event.GetEventNonce()]; !ok {
out[event.GetEventNonce()] = []*types.EthereumEventVoteRecord{eventVoteRecord}
} else {
out[event.GetEventNonce()] = append(val, eventVoteRecord)
}
return false
})
return
}
// iterateEthereumEventVoteRecords iterates through all attestations
func (k Keeper) iterateEthereumEventVoteRecords(ctx sdk.Context, cb func([]byte, *types.EthereumEventVoteRecord) bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte{types.EthereumEventVoteRecordKey})
iter := store.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
att := &types.EthereumEventVoteRecord{}
k.cdc.MustUnmarshal(iter.Value(), att)
// cb returns true to stop early
if cb(iter.Key(), att) {
return
}
}
}
// GetLastObservedEventNonce returns the latest observed event nonce
func (k Keeper) GetLastObservedEventNonce(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get([]byte{types.LastObservedEventNonceKey})
if len(bytes) == 0 {
return 0
}
return binary.BigEndian.Uint64(bytes)
}
// GetLastObservedEthereumBlockHeight height gets the block height to of the last observed attestation from
// the store
func (k Keeper) GetLastObservedEthereumBlockHeight(ctx sdk.Context) types.LatestEthereumBlockHeight {
store := ctx.KVStore(k.storeKey)
bytes := store.Get([]byte{types.LastEthereumBlockHeightKey})
if len(bytes) == 0 {
return types.LatestEthereumBlockHeight{
CosmosHeight: 0,
EthereumHeight: 0,
}
}
height := types.LatestEthereumBlockHeight{}
k.cdc.MustUnmarshal(bytes, &height)
return height
}
// SetLastObservedEthereumBlockHeight sets the block height in the store.
func (k Keeper) SetLastObservedEthereumBlockHeight(ctx sdk.Context, ethereumHeight uint64) {
k.SetLastObservedEthereumBlockHeightWithCosmos(ctx, ethereumHeight, uint64(ctx.BlockHeight()))
}
// SetLastObservedEthereumBlockHeight sets the block height in the store, specifying the cosmos height
func (k Keeper) SetLastObservedEthereumBlockHeightWithCosmos(ctx sdk.Context, ethereumHeight uint64, cosmosHeight uint64) {
store := ctx.KVStore(k.storeKey)
height := types.LatestEthereumBlockHeight{
EthereumHeight: ethereumHeight,
CosmosHeight: cosmosHeight,
}
store.Set([]byte{types.LastEthereumBlockHeightKey}, k.cdc.MustMarshal(&height))
}
// setLastObservedEventNonce sets the latest observed event nonce
func (k Keeper) setLastObservedEventNonce(ctx sdk.Context, nonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set([]byte{types.LastObservedEventNonceKey}, sdk.Uint64ToBigEndian(nonce))
}
// getLastEventNonceByValidator returns the latest event nonce for a given validator
func (k Keeper) getLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValAddress) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.MakeLastEventNonceByValidatorKey(validator))
if len(bytes) == 0 {
// in the case that we have no existing value this is the first
// time a validator is submitting a claim. Since we don't want to force
// them to replay the entire history of all events ever we can't start
// at zero
//
// We return the LastObservedEventNonce
lowestObserved := k.GetLastObservedEventNonce(ctx)
// return the latest event minus one so that the validator
// can submit that event and avoid slashing. special case
// for zero
if lowestObserved > 0 {
return lowestObserved - 1
}
return 0
}
return binary.BigEndian.Uint64(bytes)
}
// setLastEventNonceByValidator sets the latest event nonce for a give validator
func (k Keeper) setLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValAddress, nonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.MakeLastEventNonceByValidatorKey(validator), sdk.Uint64ToBigEndian(nonce))
}