-
Notifications
You must be signed in to change notification settings - Fork 14
/
attestation.go
270 lines (240 loc) · 10.3 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
package keeper
import (
"encoding/hex"
"fmt"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/functionx/fx-core/v6/x/crosschain/types"
)
func (k Keeper) Attest(ctx sdk.Context, oracleAddr sdk.AccAddress, claim types.ExternalClaim) (*types.Attestation, error) {
anyClaim, err := codectypes.NewAnyWithValue(claim)
if err != nil {
return nil, errorsmod.Wrap(types.ErrUnknown, "msg to any")
}
// Check that the nonce of this event is exactly one higher than the last nonce stored by this oracle.
// 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.GetLastEventNonceByOracle(ctx, oracleAddr)
if claim.GetEventNonce() != lastEventNonce+1 {
return nil, errorsmod.Wrapf(types.ErrNonContiguousEventNonce, "got %v, expected %v", claim.GetEventNonce(), lastEventNonce+1)
}
gasMeter := ctx.GasMeter()
ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
// Tries to get an attestation with the same eventNonce and claim as the claim that was submitted.
att := k.GetAttestation(ctx, claim.GetEventNonce(), claim.ClaimHash())
// If it does not exist, create a new one.
if att == nil {
att = &types.Attestation{
Observed: false,
Height: uint64(ctx.BlockHeight()),
Claim: anyClaim,
}
}
// Add the oracle's vote to this attestation
att.Votes = append(att.Votes, oracleAddr.String())
k.SetAttestation(ctx, claim.GetEventNonce(), claim.ClaimHash(), att)
ctx = ctx.WithGasMeter(gasMeter)
k.SetLastEventNonceByOracle(ctx, oracleAddr, claim.GetEventNonce())
k.SetLastEventBlockHeightByOracle(ctx, oracleAddr, claim.GetBlockHeight())
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 types.ExternalClaim) {
if att.Observed {
// We panic here because this should never happen
panic("attempting to process observed attestation")
}
// 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.
// Sum the current powers of all validators who have voted and see if it passes the current threshold
totalPower := k.GetLastTotalPower(ctx)
requiredPower := types.AttestationVotesPowerThreshold.Mul(totalPower).Quo(sdkmath.NewInt(100))
attestationPower := sdkmath.NewInt(0)
for _, oracleStr := range att.Votes {
oracleAddr := sdk.MustAccAddressFromBech32(oracleStr)
oracle, found := k.GetOracle(ctx, oracleAddr)
if !found {
k.Logger(ctx).Error("TryAttestation", "not found oracle", oracleAddr.String(), "claimEventNonce",
claim.GetEventNonce(), "claimType", claim.GetType(), "claimHeight", claim.GetBlockHeight())
continue
}
oraclePower := oracle.GetPower()
// Add it to the attestation power's sum
attestationPower = attestationPower.Add(oraclePower)
if attestationPower.LT(requiredPower) {
continue
}
// 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
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.SetLastObservedBlockHeight(ctx, claim.GetBlockHeight(), uint64(ctx.BlockHeight()))
att.Observed = true
k.SetAttestation(ctx, claim.GetEventNonce(), claim.ClaimHash(), att)
err := k.processAttestation(ctx, claim)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeContractEvent,
sdk.NewAttribute(sdk.AttributeKeyModule, k.moduleName),
sdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType().String()),
sdk.NewAttribute(types.AttributeKeyEventNonce, fmt.Sprint(claim.GetEventNonce())),
sdk.NewAttribute(types.AttributeKeyClaimHash, fmt.Sprint(hex.EncodeToString(claim.ClaimHash()))),
sdk.NewAttribute(types.AttributeKeyBlockHeight, fmt.Sprint(claim.GetBlockHeight())),
sdk.NewAttribute(types.AttributeKeyStateSuccess, fmt.Sprint(err == nil)),
))
break
}
}
// processAttestation actually applies the attestation to the consensus state
func (k Keeper) processAttestation(ctx sdk.Context, claim types.ExternalClaim) error {
// then execute in a new Tx so that we can store state on failure
xCtx, commit := ctx.CacheContext()
if err := k.AttestationHandler(xCtx, 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", and validators can still be slashed for not
// having voted for it.
k.Logger(ctx).Error("attestation failed", "cause", err.Error(), "claim type", claim.GetType(),
"id", hex.EncodeToString(types.GetAttestationKey(claim.GetEventNonce(), claim.ClaimHash())),
"nonce", fmt.Sprint(claim.GetEventNonce()),
)
return err
}
commit() // persist transient storage
return nil
}
// 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 an attestation given an event nonce and claim
func (k Keeper) DeleteAttestation(ctx sdk.Context, claim types.ExternalClaim) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.GetAttestationKey(claim.GetEventNonce(), claim.ClaimHash()))
}
// IterateAttestationAndClaim iterates through all attestations
func (k Keeper) IterateAttestationAndClaim(ctx sdk.Context, cb func(*types.Attestation, types.ExternalClaim) bool) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, types.OracleAttestationKey)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
att := new(types.Attestation)
k.cdc.MustUnmarshal(iter.Value(), att)
claim, err := types.UnpackAttestationClaim(k.cdc, att)
if err != nil {
panic("couldn't cast to claim")
}
// cb returns true to stop early
if cb(att, claim) {
return
}
}
}
// IterateAttestations iterates through all attestations
func (k Keeper) IterateAttestations(ctx sdk.Context, cb func(*types.Attestation) bool) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, types.OracleAttestationKey)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
att := new(types.Attestation)
k.cdc.MustUnmarshal(iter.Value(), att)
// cb returns true to stop early
if cb(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(types.LastObservedEventNonceKey)
if len(bytes) == 0 {
return 0
}
return sdk.BigEndianToUint64(bytes)
}
// SetLastObservedEventNonce sets the latest observed event nonce
func (k Keeper) SetLastObservedEventNonce(ctx sdk.Context, eventNonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.LastObservedEventNonceKey, sdk.Uint64ToBigEndian(eventNonce))
}
// GetLastObservedBlockHeight height gets the block height to of the last observed attestation from
// the store
func (k Keeper) GetLastObservedBlockHeight(ctx sdk.Context) types.LastObservedBlockHeight {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.LastObservedBlockHeightKey)
if len(bytes) == 0 {
return types.LastObservedBlockHeight{
ExternalBlockHeight: 0,
BlockHeight: 0,
}
}
height := types.LastObservedBlockHeight{}
k.cdc.MustUnmarshal(bytes, &height)
return height
}
// SetLastObservedBlockHeight sets the block height in the store.
func (k Keeper) SetLastObservedBlockHeight(ctx sdk.Context, externalBlockHeight, blockHeight uint64) {
store := ctx.KVStore(k.storeKey)
height := types.LastObservedBlockHeight{
ExternalBlockHeight: externalBlockHeight,
BlockHeight: blockHeight,
}
store.Set(types.LastObservedBlockHeightKey, k.cdc.MustMarshal(&height))
}
// GetLastEventNonceByOracle returns the latest event nonce for a given oracle
func (k Keeper) GetLastEventNonceByOracle(ctx sdk.Context, oracleAddr sdk.AccAddress) uint64 {
store := ctx.KVStore(k.storeKey)
bytes := store.Get(types.GetLastEventNonceByOracleKey(oracleAddr))
if len(bytes) == 0 {
// in the case that we have no existing value this is the first
// time a oracleAddr 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 sdk.BigEndianToUint64(bytes)
}
// DelLastEventNonceByOracle delete the latest event nonce for a given oracle
func (k Keeper) DelLastEventNonceByOracle(ctx sdk.Context, oracleAddr sdk.AccAddress) {
store := ctx.KVStore(k.storeKey)
key := types.GetLastEventNonceByOracleKey(oracleAddr)
if !store.Has(key) {
return
}
store.Delete(key)
}
// SetLastEventNonceByOracle sets the latest event nonce for a give oracle
func (k Keeper) SetLastEventNonceByOracle(ctx sdk.Context, oracleAddr sdk.AccAddress, eventNonce uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetLastEventNonceByOracleKey(oracleAddr), sdk.Uint64ToBigEndian(eventNonce))
}