forked from Gravity-Bridge/Gravity-Bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attestation.go
390 lines (349 loc) · 13.7 KB
/
attestation.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
package keeper
import (
"fmt"
"sort"
"strconv"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/Gravity-Bridge/Gravity-Bridge/module/x/gravity/types"
)
// TODO-JT: carefully look at atomicity of this function
func (k Keeper) Attest(
ctx sdk.Context,
claim types.EthereumClaim,
anyClaim *codectypes.Any,
) (*types.Attestation, error) {
val, found := k.GetOrchestratorValidator(ctx, claim.GetClaimer())
if !found {
panic("Could not find ValAddr for delegate key, should be checked by now")
}
valAddr := val.GetOperator()
if err := sdk.VerifyAddressFormat(valAddr); err != nil {
return nil, sdkerrors.Wrap(err, "invalid orchestrator validator address")
}
// 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 processAttestation 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.
// This prevents there being two attestations with the same nonce that get 2/3s of the votes
// in the endBlocker.
lastEventNonce := k.GetLastEventNonceByValidator(ctx, valAddr)
if claim.GetEventNonce() != lastEventNonce+1 {
return nil, fmt.Errorf(types.ErrNonContiguousEventNonce.Error(), lastEventNonce+1, claim.GetEventNonce())
}
// Tries to get an attestation with the same eventNonce and claim as the claim that was submitted.
hash, err := claim.ClaimHash()
if err != nil {
return nil, sdkerrors.Wrap(err, "unable to compute claim hash")
}
att := k.GetAttestation(ctx, claim.GetEventNonce(), hash)
// If it does not exist, create a new one.
if att == nil {
att = &types.Attestation{
Observed: false,
Votes: []string{},
Height: uint64(ctx.BlockHeight()),
Claim: anyClaim,
}
}
// Add the validator's vote to this attestation
att.Votes = append(att.Votes, valAddr.String())
k.SetAttestation(ctx, claim.GetEventNonce(), hash, att)
k.SetLastEventNonceByValidator(ctx, valAddr, claim.GetEventNonce())
return att, nil
}
// TryAttestation checks if an attestation has enough votes to be applied to the consensus state
// and has not already been marked Observed, then calls processAttestation to actually apply it to the state,
// and then marks it Observed and emits an event.
func (k Keeper) TryAttestation(ctx sdk.Context, att *types.Attestation) {
claim, err := k.UnpackAttestationClaim(att)
if err != nil {
panic("could not cast to claim")
}
hash, err := claim.ClaimHash()
if err != nil {
panic("unable to compute claim hash")
}
// If the attestation has not yet been Observed, sum up the votes and see if it is ready to apply to the state.
// This conditional stops the attestation from accidentally being applied twice.
if !att.Observed {
// 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
totalPower := k.StakingKeeper.GetLastTotalPower(ctx)
requiredPower := types.AttestationVotesPowerThreshold.Mul(totalPower).Quo(sdk.NewInt(100))
attestationPower := sdk.NewInt(0)
for _, validator := range att.Votes {
val, err := sdk.ValAddressFromBech32(validator)
if err != nil {
panic(err)
}
validatorPower := k.StakingKeeper.GetLastValidatorPower(ctx, val)
// Add it to the attestation power's sum
attestationPower = attestationPower.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 attestationPower.GTE(requiredPower) {
lastEventNonce := k.GetLastObservedEventNonce(ctx)
// this check is performed at the next level up so this should never panic
// outside of programmer error.
if claim.GetEventNonce() != lastEventNonce+1 {
panic("attempting to apply events to state out of order")
}
k.setLastObservedEventNonce(ctx, claim.GetEventNonce())
k.SetLastObservedEthereumBlockHeight(ctx, claim.GetBlockHeight())
att.Observed = true
k.SetAttestation(ctx, claim.GetEventNonce(), hash, att)
k.processAttestation(ctx, att, claim)
k.emitObservedEvent(ctx, att, claim)
break
}
}
} else {
// We panic here because this should never happen
panic("attempting to process observed attestation")
}
}
// processAttestation actually applies the attestation to the consensus state
func (k Keeper) processAttestation(ctx sdk.Context, att *types.Attestation, claim types.EthereumClaim) {
hash, err := claim.ClaimHash()
if err != nil {
panic("unable to compute claim hash")
}
// then execute in a new Tx so that we can store state on failure
xCtx, commit := ctx.CacheContext()
if err := k.AttestationHandler.Handle(xCtx, *att, claim); err != nil { // execute with a transient storage
// If the attestation fails, something has gone wrong and we can't recover it. Log and move on
// The attestation will still be marked "Observed", allowing the oracle to progress properly
k.logger(ctx).Error("attestation failed",
"cause", err.Error(),
"claim type", claim.GetType(),
"id", types.GetAttestationKey(claim.GetEventNonce(), hash),
"nonce", fmt.Sprint(claim.GetEventNonce()),
)
} else {
commit() // persist transient storage
}
}
// emitObservedEvent emits an event with information about an attestation that has been applied to
// consensus state.
func (k Keeper) emitObservedEvent(ctx sdk.Context, att *types.Attestation, claim types.EthereumClaim) {
hash, err := claim.ClaimHash()
if err != nil {
panic(sdkerrors.Wrap(err, "unable to compute claim hash"))
}
ctx.EventManager().EmitTypedEvent(
&types.EventObservation{
AttestationType: string(claim.GetType()),
BridgeContract: k.GetBridgeContractAddress(ctx).GetAddress().Hex(),
BridgeChainId: strconv.Itoa(int(k.GetBridgeChainID(ctx))),
AttestationId: string(types.GetAttestationKey(claim.GetEventNonce(), hash)),
Nonce: fmt.Sprint(claim.GetEventNonce()),
},
)
}
// SetAttestation sets the attestation in the store
func (k Keeper) SetAttestation(ctx sdk.Context, eventNonce uint64, claimHash []byte, att *types.Attestation) {
store := ctx.KVStore(k.storeKey)
aKey := types.GetAttestationKey(eventNonce, claimHash)
store.Set(aKey, k.cdc.MustMarshal(att))
}
// GetAttestation return an attestation given a nonce
func (k Keeper) GetAttestation(ctx sdk.Context, eventNonce uint64, claimHash []byte) *types.Attestation {
store := ctx.KVStore(k.storeKey)
aKey := types.GetAttestationKey(eventNonce, claimHash)
bz := store.Get(aKey)
if len(bz) == 0 {
return nil
}
var att types.Attestation
k.cdc.MustUnmarshal(bz, &att)
return &att
}
// DeleteAttestation deletes the given attestation
func (k Keeper) DeleteAttestation(ctx sdk.Context, att types.Attestation) {
claim, err := k.UnpackAttestationClaim(&att)
if err != nil {
panic("Bad Attestation in DeleteAttestation")
}
hash, err := claim.ClaimHash()
if err != nil {
panic(sdkerrors.Wrap(err, "unable to compute claim hash"))
}
store := ctx.KVStore(k.storeKey)
store.Delete(types.GetAttestationKey(claim.GetEventNonce(), hash))
}
// GetAttestationMapping returns a mapping of eventnonce -> attestations at that nonce
// it also returns a pre-sorted array of the keys, this assists callers of this function
// by providing a deterministic iteration order. You should always iterate over ordered keys
// if you are iterating this map at all.
func (k Keeper) GetAttestationMapping(ctx sdk.Context) (attestationMapping map[uint64][]types.Attestation, orderedKeys []uint64) {
attestationMapping = make(map[uint64][]types.Attestation)
k.IterateAttestations(ctx, false, func(_ []byte, att types.Attestation) bool {
claim, err := k.UnpackAttestationClaim(&att)
if err != nil {
panic("couldn't cast to claim")
}
if val, ok := attestationMapping[claim.GetEventNonce()]; !ok {
attestationMapping[claim.GetEventNonce()] = []types.Attestation{att}
} else {
attestationMapping[claim.GetEventNonce()] = append(val, att)
}
return false
})
orderedKeys = make([]uint64, 0, len(attestationMapping))
for k := range attestationMapping {
orderedKeys = append(orderedKeys, k)
}
sort.Slice(orderedKeys, func(i, j int) bool { return orderedKeys[i] < orderedKeys[j] })
return
}
// IterateAttestations iterates through all attestations
func (k Keeper) IterateAttestations(ctx sdk.Context, reverse bool, cb func([]byte, types.Attestation) bool) {
store := ctx.KVStore(k.storeKey)
prefix := types.OracleAttestationKey
var iter storetypes.Iterator
if reverse {
iter = store.ReverseIterator(prefixRange(prefix))
} else {
iter = store.Iterator(prefixRange(prefix))
}
defer iter.Close()
for ; iter.Valid(); iter.Next() {
att := types.Attestation{
Observed: false,
Votes: []string{},
Height: 0,
Claim: &codectypes.Any{
TypeUrl: "",
Value: []byte{},
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: []byte{},
XXX_sizecache: 0,
},
}
k.cdc.MustUnmarshal(iter.Value(), &att)
// cb returns true to stop early
if cb(iter.Key(), att) {
return
}
}
}
// GetMostRecentAttestations returns sorted (by nonce) attestations up to a provided limit number of attestations
// Note: calls GetAttestationMapping in the hopes that there are potentially many attestations
// which are distributed between few nonces to minimize sorting time
func (k Keeper) GetMostRecentAttestations(ctx sdk.Context, limit uint64) []types.Attestation {
attestationMapping, keys := k.GetAttestationMapping(ctx)
attestations := make([]types.Attestation, 0, limit)
// Iterate the nonces and collect the attestations
count := 0
for _, nonce := range keys {
if count >= int(limit) {
break
}
for _, att := range attestationMapping[nonce] {
if count >= int(limit) {
break
}
attestations = append(attestations, att)
count++
}
}
return attestations
}
// GetLastObservedEventNonce returns the latest observed event nonce
func (k Keeper) GetLastObservedEventNonce(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.LastObservedEventNonceKey)
if len(bytes) == 0 {
return 0
}
return types.UInt64FromBytes(bytes)
}
// GetLastObservedEthereumBlockHeight height gets the block height to of the last observed attestation from
// the store
func (k Keeper) GetLastObservedEthereumBlockHeight(ctx sdk.Context) types.LastObservedEthereumBlockHeight {
store := ctx.KVStore(k.storeKey)
bytes := store.Get([]byte(types.LastObservedEthereumBlockHeightKey))
if len(bytes) == 0 {
return types.LastObservedEthereumBlockHeight{
CosmosBlockHeight: 0,
EthereumBlockHeight: 0,
}
}
height := types.LastObservedEthereumBlockHeight{
CosmosBlockHeight: 0,
EthereumBlockHeight: 0,
}
k.cdc.MustUnmarshal(bytes, &height)
return height
}
// SetLastObservedEthereumBlockHeight sets the block height in the store.
func (k Keeper) SetLastObservedEthereumBlockHeight(ctx sdk.Context, ethereumHeight uint64) {
store := ctx.KVStore(k.storeKey)
height := types.LastObservedEthereumBlockHeight{
EthereumBlockHeight: ethereumHeight,
CosmosBlockHeight: uint64(ctx.BlockHeight()),
}
store.Set(types.LastObservedEthereumBlockHeightKey, k.cdc.MustMarshal(&height))
}
// GetLastObservedValset retrieves the last observed validator set from the store
// WARNING: This value is not an up to date validator set on Ethereum, it is a validator set
// that AT ONE POINT was the one in the Gravity bridge on Ethereum. If you assume that it's up
// to date you may break the bridge
func (k Keeper) GetLastObservedValset(ctx sdk.Context) *types.Valset {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.LastObservedValsetKey)
if len(bytes) == 0 {
return nil
}
valset := types.Valset{
Nonce: 0,
Members: []types.BridgeValidator{},
Height: 0,
RewardAmount: sdk.Int{},
RewardToken: "",
}
k.cdc.MustUnmarshal(bytes, &valset)
return &valset
}
// SetLastObservedValset updates the last observed validator set in the store
func (k Keeper) SetLastObservedValset(ctx sdk.Context, valset types.Valset) {
store := ctx.KVStore(k.storeKey)
store.Set(types.LastObservedValsetKey, k.cdc.MustMarshal(&valset))
}
// setLastObservedEventNonce sets the latest observed event nonce
func (k Keeper) setLastObservedEventNonce(ctx sdk.Context, nonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.LastObservedEventNonceKey, types.UInt64Bytes(nonce))
}
// GetLastEventNonceByValidator returns the latest event nonce for a given validator
func (k Keeper) GetLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValAddress) uint64 {
if err := sdk.VerifyAddressFormat(validator); err != nil {
panic(sdkerrors.Wrap(err, "invalid validator address"))
}
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.GetLastEventNonceByValidatorKey(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
lastEventNonce := k.GetLastObservedEventNonce(ctx)
if lastEventNonce >= 1 {
return lastEventNonce - 1
} else {
return 0
}
}
return types.UInt64FromBytes(bytes)
}
// setLastEventNonceByValidator sets the latest event nonce for a give validator
func (k Keeper) SetLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValAddress, nonce uint64) {
if err := sdk.VerifyAddressFormat(validator); err != nil {
panic(sdkerrors.Wrap(err, "invalid validator address"))
}
store := ctx.KVStore(k.storeKey)
store.Set(types.GetLastEventNonceByValidatorKey(validator), types.UInt64Bytes(nonce))
}