-
Notifications
You must be signed in to change notification settings - Fork 968
/
detect_attestations.go
578 lines (479 loc) · 19.3 KB
/
detect_attestations.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
package slasher
import (
"bytes"
"context"
"fmt"
"time"
"github.com/pkg/errors"
slashertypes "github.com/prysmaticlabs/prysm/v5/beacon-chain/slasher/types"
fieldparams "github.com/prysmaticlabs/prysm/v5/config/fieldparams"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
ethpb "github.com/prysmaticlabs/prysm/v5/proto/prysm/v1alpha1"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
// Takes in a list of indexed attestation wrappers and returns any
// found attester slashings to the caller.
func (s *Service) checkSlashableAttestations(
ctx context.Context, currentEpoch primitives.Epoch, atts []*slashertypes.IndexedAttestationWrapper,
) (map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing, error) {
start := time.Now()
slashings := map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing{}
// Double votes
doubleVoteSlashings, err := s.checkDoubleVotes(ctx, atts)
if err != nil {
return nil, errors.Wrap(err, "could not check slashable double votes")
}
log.WithField("elapsed", time.Since(start)).Debug("Done checking double votes")
for root, slashing := range doubleVoteSlashings {
slashings[root] = slashing
}
// Save the attestation records to our database.
// If multiple attestations are provided for the same validator index + target epoch combination,
// then the first (validator index + target epoch) => signing root) link is kept into the database.
if err := s.serviceCfg.Database.SaveAttestationRecordsForValidators(ctx, atts); err != nil {
return nil, errors.Wrap(err, couldNotSaveAttRecord)
}
// Surrounding / surrounded votes
surroundSlashings, err := s.checkSurroundVotes(ctx, atts, currentEpoch)
if err != nil {
return nil, errors.Wrap(err, "could not check slashable surround votes")
}
for root, slashing := range surroundSlashings {
slashings[root] = slashing
}
elapsed := time.Since(start)
fields := logrus.Fields{
"numAttestations": len(atts),
"elapsed": elapsed,
}
log.WithFields(fields).Info("Done checking slashable attestations")
if len(slashings) > 0 {
log.WithField("numSlashings", len(slashings)).Warn("Slashable attestation offenses found")
}
return slashings, nil
}
// Check for surrounding and surrounded votes in our database given a list of incoming attestations.
func (s *Service) checkSurroundVotes(
ctx context.Context,
attWrappers []*slashertypes.IndexedAttestationWrapper,
currentEpoch primitives.Epoch,
) (map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing, error) {
slashings := map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing{}
// Group attestation wrappers by validator chunk index.
attWrappersByValidatorChunkIndex := s.groupByValidatorChunkIndex(attWrappers)
for validatorChunkIndex, attWrappers := range attWrappersByValidatorChunkIndex {
minChunkByChunkIndex, err := s.updatedChunkByChunkIndex(ctx, slashertypes.MinSpan, currentEpoch, validatorChunkIndex)
if err != nil {
return nil, errors.Wrap(err, "could not update updatedMinChunks")
}
maxChunkByChunkIndex, err := s.updatedChunkByChunkIndex(ctx, slashertypes.MaxSpan, currentEpoch, validatorChunkIndex)
if err != nil {
return nil, errors.Wrap(err, "could not update updatedMaxChunks")
}
// Group (already grouped by validator chunk index) attestation wrappers by chunk index.
attWrappersByChunkIndex := s.groupByChunkIndex(attWrappers)
// Check for surrounding votes.
surroundingSlashings, err := s.updateSpans(ctx, minChunkByChunkIndex, attWrappersByChunkIndex, slashertypes.MinSpan, validatorChunkIndex, currentEpoch)
if err != nil {
return nil, errors.Wrapf(err, "could not update min attestation spans for validator chunk index %d", validatorChunkIndex)
}
for root, slashing := range surroundingSlashings {
slashings[root] = slashing
}
// Check for surrounded votes.
surroundedSlashings, err := s.updateSpans(ctx, maxChunkByChunkIndex, attWrappersByChunkIndex, slashertypes.MaxSpan, validatorChunkIndex, currentEpoch)
if err != nil {
return nil, errors.Wrapf(err, "could not update max attestation spans for validator chunk index %d", validatorChunkIndex)
}
for root, slashing := range surroundedSlashings {
slashings[root] = slashing
}
// Save updated chunks into the database.
if err := s.saveUpdatedChunks(ctx, minChunkByChunkIndex, slashertypes.MinSpan, validatorChunkIndex); err != nil {
return nil, errors.Wrap(err, "could not save chunks for min spans")
}
if err := s.saveUpdatedChunks(ctx, maxChunkByChunkIndex, slashertypes.MaxSpan, validatorChunkIndex); err != nil {
return nil, errors.Wrap(err, "could not save chunks for max spans")
}
// Update the latest written epoch for all validators involved to the current chunk.
indices := s.params.validatorIndexesInChunk(validatorChunkIndex)
for _, idx := range indices {
s.latestEpochWrittenForValidator[idx] = currentEpoch
}
}
return slashings, nil
}
// Check for double votes in our database given a list of incoming attestations.
func (s *Service) checkDoubleVotes(
ctx context.Context, incomingAttWrappers []*slashertypes.IndexedAttestationWrapper,
) (map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing, error) {
ctx, span := trace.StartSpan(ctx, "Slasher.checkDoubleVotesOnDisk")
defer span.End()
type attestationInfo struct {
validatorIndex uint64
epoch primitives.Epoch
}
slashings := map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing{}
// Check each incoming attestation for double votes against other incoming attestations.
existingAttWrappers := make(map[attestationInfo]*slashertypes.IndexedAttestationWrapper)
for _, incomingAttWrapper := range incomingAttWrappers {
targetEpoch := incomingAttWrapper.IndexedAttestation.Data.Target.Epoch
for _, validatorIndex := range incomingAttWrapper.IndexedAttestation.AttestingIndices {
info := attestationInfo{
validatorIndex: validatorIndex,
epoch: targetEpoch,
}
existingAttWrapper, ok := existingAttWrappers[info]
if !ok {
// This is the first attestation for this `validator index x epoch` combination.
// There is no double vote. This attestation is memoized for future checks.
existingAttWrappers[info] = incomingAttWrapper
continue
}
if existingAttWrapper.DataRoot == incomingAttWrapper.DataRoot {
// Both attestations are the same, this is not a double vote.
continue
}
// There is two different attestations for the same `validator index x epoch` combination.
// This is a double vote.
doubleVotesTotal.Inc()
slashing := ðpb.AttesterSlashing{
Attestation_1: existingAttWrapper.IndexedAttestation,
Attestation_2: incomingAttWrapper.IndexedAttestation,
}
// Ensure the attestation with the lower data root is the first attestation.
// It will be useful for comparing with other double votes.
if bytes.Compare(existingAttWrapper.DataRoot[:], incomingAttWrapper.DataRoot[:]) > 0 {
slashing = ðpb.AttesterSlashing{
Attestation_1: incomingAttWrapper.IndexedAttestation,
Attestation_2: existingAttWrapper.IndexedAttestation,
}
}
root, err := slashing.HashTreeRoot()
if err != nil {
return nil, errors.Wrap(err, "could not hash tree root for attester slashing")
}
slashings[root] = slashing
}
}
// Check each incoming attestation for double votes against the database.
doubleVotes, err := s.serviceCfg.Database.CheckAttesterDoubleVotes(ctx, incomingAttWrappers)
if err != nil {
return nil, errors.Wrap(err, "could not retrieve potential double votes from disk")
}
for _, doubleVote := range doubleVotes {
doubleVotesTotal.Inc()
wrapper_1 := doubleVote.Wrapper_1
wrapper_2 := doubleVote.Wrapper_2
slashing := ðpb.AttesterSlashing{
Attestation_1: wrapper_1.IndexedAttestation,
Attestation_2: wrapper_2.IndexedAttestation,
}
// Ensure the attestation with the lower data root is the first attestation.
if bytes.Compare(wrapper_1.DataRoot[:], wrapper_2.DataRoot[:]) > 0 {
slashing = ðpb.AttesterSlashing{
Attestation_1: wrapper_2.IndexedAttestation,
Attestation_2: wrapper_1.IndexedAttestation,
}
}
root, err := slashing.HashTreeRoot()
if err != nil {
return nil, errors.Wrap(err, "could not hash tree root for attester slashing")
}
slashings[root] = slashing
}
return slashings, nil
}
// updatedChunkByChunkIndex loads the chunks from the database for validators corresponding to
// the `validatorChunkIndex`.
// It then updates the chunks with the neutral element for corresponding validators from
// the epoch just after the latest epoch written to the current epoch.
// A mapping between chunk index and chunk is returned to the caller.
func (s *Service) updatedChunkByChunkIndex(
ctx context.Context,
chunkKind slashertypes.ChunkKind,
currentEpoch primitives.Epoch,
validatorChunkIndex uint64,
) (map[uint64]Chunker, error) {
chunkByChunkIndex := map[uint64]Chunker{}
validatorIndexes := s.params.validatorIndexesInChunk(validatorChunkIndex)
for _, validatorIndex := range validatorIndexes {
// Retrieve the latest epoch written for the validator.
latestEpochWritten, ok := s.latestEpochWrittenForValidator[validatorIndex]
// Start from the epoch just after the latest epoch written.
epochToWrite, err := latestEpochWritten.SafeAdd(1)
if err != nil {
return nil, errors.Wrap(err, "could not add 1 to latest epoch written")
}
if !ok {
epochToWrite = 0
}
// It is useless to update more than `historyLength` epochs, since
// the chunks are circular and we will be overwritten at least one.
if currentEpoch-epochToWrite >= s.params.historyLength {
epochToWrite = currentEpoch + 1 - s.params.historyLength
}
for epochToWrite <= currentEpoch {
// Get the chunk index for the latest epoch written.
chunkIndex := s.params.chunkIndex(epochToWrite)
// Get the chunk corresponding to the chunk index from the `chunkByChunkIndex` map.
currentChunk, ok := chunkByChunkIndex[chunkIndex]
if !ok {
// If the chunk is not in the map, retrieve it from the database.
currentChunk, err = s.getChunkFromDatabase(ctx, chunkKind, validatorChunkIndex, chunkIndex)
if err != nil {
return nil, errors.Wrap(err, "could not get chunk")
}
}
// Update the current chunk with the neutral element for the validator index for the latest epoch written.
for s.params.chunkIndex(epochToWrite) == chunkIndex && epochToWrite <= currentEpoch {
if err := setChunkRawDistance(
s.params,
currentChunk.Chunk(),
validatorIndex,
epochToWrite,
currentChunk.NeutralElement(),
); err != nil {
return nil, err
}
epochToWrite++
}
chunkByChunkIndex[chunkIndex] = currentChunk
}
}
return chunkByChunkIndex, nil
}
// Updates spans and detects any slashable attester offenses along the way.
// 1. Determine the chunks we need to use for updating for the validator indices
// in a validator chunk index, then retrieve those chunks from the database.
// 2. Using the chunks from step (1):
// for every attestation by chunk index:
// for each validator in the attestation's attesting indices:
// - Check if the attestation is slashable, if so return a slashing object.
// 3. Save the updated chunks to disk.
func (s *Service) updateSpans(
ctx context.Context,
updatedChunks map[uint64]Chunker,
attWrapperByChunkIdx map[uint64][]*slashertypes.IndexedAttestationWrapper,
kind slashertypes.ChunkKind,
validatorChunkIndex uint64,
currentEpoch primitives.Epoch,
) (map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing, error) {
ctx, span := trace.StartSpan(ctx, "Slasher.updateSpans")
defer span.End()
// Apply the attestations to the related chunks and find any
// slashings along the way.
slashings := map[[fieldparams.RootLength]byte]*ethpb.AttesterSlashing{}
for _, attWrappers := range attWrapperByChunkIdx {
for _, attWrapper := range attWrappers {
for _, validatorIdx := range attWrapper.IndexedAttestation.AttestingIndices {
validatorIndex := primitives.ValidatorIndex(validatorIdx)
computedValidatorChunkIdx := s.params.validatorChunkIndex(validatorIndex)
// Every validator chunk index represents a range of validators.
// It is possible that the validator index in this loop iteration is
// not part of the validator chunk index we are updating chunks for.
//
// For example, if there are 4 validators per validator chunk index,
// then validator chunk index 0 contains validator indices [0, 1, 2, 3]
// If we see an attestation with attesting indices [3, 4, 5] and we are updating
// chunks for validator chunk index 0, only validator index 3 should make
// it past this line.
if validatorChunkIndex != computedValidatorChunkIdx {
continue
}
slashing, err := s.applyAttestationForValidator(
ctx, updatedChunks, attWrapper, kind, validatorChunkIndex, validatorIndex, currentEpoch,
)
if err != nil {
return nil, errors.Wrapf(err, "could not apply attestation for validator index %d", validatorIndex)
}
if slashing == nil {
continue
}
root, err := slashing.HashTreeRoot()
if err != nil {
return nil, errors.Wrap(err, "could not hash tree root for attester slashing")
}
slashings[root] = slashing
}
}
}
// Write the updated chunks to disk.
return slashings, nil
}
// Checks if an incoming attestation is slashable based on the validator chunk it
// corresponds to. If a slashable offense is found, we return it to the caller.
// If not, then update every single chunk the attestation covers, starting from its
// source epoch up to its target.
func (s *Service) applyAttestationForValidator(
ctx context.Context,
chunksByChunkIdx map[uint64]Chunker,
attestation *slashertypes.IndexedAttestationWrapper,
chunkKind slashertypes.ChunkKind,
validatorChunkIndex uint64,
validatorIndex primitives.ValidatorIndex,
currentEpoch primitives.Epoch,
) (*ethpb.AttesterSlashing, error) {
ctx, span := trace.StartSpan(ctx, "Slasher.applyAttestationForValidator")
defer span.End()
var err error
sourceEpoch := attestation.IndexedAttestation.Data.Source.Epoch
targetEpoch := attestation.IndexedAttestation.Data.Target.Epoch
attestationDistance.Observe(float64(targetEpoch) - float64(sourceEpoch))
chunkIndex := s.params.chunkIndex(sourceEpoch)
chunk, ok := chunksByChunkIdx[chunkIndex]
if !ok {
chunk, err = s.getChunkFromDatabase(ctx, chunkKind, validatorChunkIndex, chunkIndex)
if err != nil {
return nil, errors.Wrapf(err, "could not get chunk at index %d", chunkIndex)
}
}
// Check slashable, if so, return the slashing.
slashing, err := chunk.CheckSlashable(
ctx,
s.serviceCfg.Database,
validatorIndex,
attestation,
)
if err != nil {
return nil, errors.Wrapf(
err,
"could not check if attestation for validator index %d is slashable",
validatorIndex,
)
}
if slashing != nil {
return slashing, nil
}
// Get the first start epoch for the chunk. If it does not exist or
// is not possible based on the input arguments, do not continue with the update.
startEpoch, exists := chunk.StartEpoch(sourceEpoch, currentEpoch)
if !exists {
return nil, nil
}
// Given a single attestation could span across multiple chunks
// for a validator min or max span, we attempt to update the current chunk
// for the source epoch of the attestation. If the update function tells
// us we need to proceed to the next chunk, we continue by determining
// the start epoch of the next chunk. We exit once no longer need to
// keep updating chunks.
for {
chunkIndex = s.params.chunkIndex(startEpoch)
chunk, ok := chunksByChunkIdx[chunkIndex]
if !ok {
chunk, err = s.getChunkFromDatabase(ctx, chunkKind, validatorChunkIndex, chunkIndex)
if err != nil {
return nil, errors.Wrapf(err, "could not get chunk at index %d", chunkIndex)
}
}
keepGoing, err := chunk.Update(
chunkIndex,
currentEpoch,
validatorIndex,
startEpoch,
targetEpoch,
)
if err != nil {
return nil, errors.Wrapf(
err,
"could not update chunk at chunk index %d for validator index %d and current epoch %d",
chunkIndex,
validatorIndex,
currentEpoch,
)
}
// We update the chunksByChunkIdx map with the chunk we just updated.
chunksByChunkIdx[chunkIndex] = chunk
if !keepGoing {
break
}
// Move to first epoch of next chunk if needed.
startEpoch = chunk.NextChunkStartEpoch(startEpoch)
}
return nil, nil
}
// Retrieve a chunk from database.
func (s *Service) getChunkFromDatabase(
ctx context.Context,
chunkKind slashertypes.ChunkKind,
validatorChunkIndex uint64,
chunkIndex uint64,
) (Chunker, error) {
// We can ensure we load the appropriate chunk we need by fetching from the DB.
diskChunks, err := s.loadChunks(ctx, validatorChunkIndex, chunkKind, []uint64{chunkIndex})
if err != nil {
return nil, errors.Wrapf(err, "could not load chunk at index %d", chunkIndex)
}
if chunk, ok := diskChunks[chunkIndex]; ok {
return chunk, nil
}
return nil, fmt.Errorf("could not retrieve chunk at chunk index %d from disk", chunkIndex)
}
// Load chunks for a specified list of chunk indices. We attempt to load it from the database.
// If the data exists, then we initialize a chunk of a specified kind. Otherwise, we create
// an empty chunk, add it to our map, and then return it to the caller.
func (s *Service) loadChunks(
ctx context.Context,
validatorChunkIndex uint64,
chunkKind slashertypes.ChunkKind,
chunkIndexes []uint64,
) (map[uint64]Chunker, error) {
ctx, span := trace.StartSpan(ctx, "Slasher.loadChunks")
defer span.End()
chunkKeys := make([][]byte, 0, len(chunkIndexes))
for _, chunkIndex := range chunkIndexes {
chunkKeys = append(chunkKeys, s.params.flatSliceID(validatorChunkIndex, chunkIndex))
}
rawChunks, chunksExist, err := s.serviceCfg.Database.LoadSlasherChunks(ctx, chunkKind, chunkKeys)
if err != nil {
return nil, errors.Wrapf(err, "could not load slasher chunk index")
}
chunksByChunkIdx := make(map[uint64]Chunker, len(rawChunks))
for i := 0; i < len(rawChunks); i++ {
// If the chunk exists in the database, we initialize it from the raw bytes data.
// If it does not exist, we initialize an empty chunk.
var (
chunk Chunker
err error
)
chunkExists := chunksExist[i]
switch chunkKind {
case slashertypes.MinSpan:
if chunkExists {
chunk, err = MinChunkSpansSliceFrom(s.params, rawChunks[i])
break
}
chunk = EmptyMinSpanChunksSlice(s.params)
case slashertypes.MaxSpan:
if chunkExists {
chunk, err = MaxChunkSpansSliceFrom(s.params, rawChunks[i])
break
}
chunk = EmptyMaxSpanChunksSlice(s.params)
}
if err != nil {
return nil, errors.Wrap(err, "could not initialize chunk")
}
chunksByChunkIdx[chunkIndexes[i]] = chunk
}
return chunksByChunkIdx, nil
}
// Saves updated chunks to disk given the required database schema.
func (s *Service) saveUpdatedChunks(
ctx context.Context,
updatedChunksByChunkIdx map[uint64]Chunker,
chunkKind slashertypes.ChunkKind,
validatorChunkIndex uint64,
) error {
ctx, span := trace.StartSpan(ctx, "Slasher.saveUpdatedChunks")
defer span.End()
chunkKeys := make([][]byte, 0, len(updatedChunksByChunkIdx))
chunks := make([][]uint16, 0, len(updatedChunksByChunkIdx))
for chunkIdx, chunk := range updatedChunksByChunkIdx {
chunkKeys = append(chunkKeys, s.params.flatSliceID(validatorChunkIndex, chunkIdx))
chunks = append(chunks, chunk.Chunk())
}
chunksSavedTotal.Add(float64(len(chunks)))
return s.serviceCfg.Database.SaveSlasherChunks(ctx, chunkKind, chunkKeys, chunks)
}