/
validator_attest.go
324 lines (286 loc) · 10.2 KB
/
validator_attest.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
package client
import (
"bytes"
"context"
"errors"
"fmt"
"math/rand"
"os"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
ethpb "github.com/prysmaticlabs/ethereumapis/eth/v1alpha1"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/go-ssz"
slashpb "github.com/prysmaticlabs/prysm/proto/slashing"
"github.com/prysmaticlabs/prysm/shared/bytesutil"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/hashutil"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
var (
validatorAttestSuccessVec = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "validator",
Name: "successful_attestations",
},
[]string{
// validator pubkey
"pkey",
},
)
validatorAttestFailVec = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "validator",
Name: "failed_attestations",
},
[]string{
// validator pubkey
"pkey",
},
)
)
// SubmitAttestation completes the validator client's attester responsibility at a given slot.
// It fetches the latest beacon block head along with the latest canonical beacon state
// information in order to sign the block and include information about the validator's
// participation in voting on the block.
func (v *validator) SubmitAttestation(ctx context.Context, slot uint64, pubKey [48]byte) {
ctx, span := trace.StartSpan(ctx, "validator.SubmitAttestation")
defer span.End()
span.AddAttributes(trace.StringAttribute("validator", fmt.Sprintf("%#x", pubKey)))
fmtKey := fmt.Sprintf("%#x", pubKey[:8])
log := log.WithField("pubKey", fmt.Sprintf("%#x", bytesutil.Trunc(pubKey[:]))).WithField("slot", slot)
duty, err := v.duty(pubKey)
if err != nil {
log.WithError(err).Error("Could not fetch validator assignment")
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
req := ðpb.AttestationDataRequest{
Slot: slot,
CommitteeIndex: duty.CommitteeIndex,
}
data, err := v.validatorClient.GetAttestationData(ctx, req)
if err != nil {
log.WithError(err).Error("Could not request attestation to sign at slot")
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
if featureconfig.Get().ProtectAttester {
history, err := v.db.AttestationHistory(ctx, pubKey[:])
if err != nil {
log.Errorf("Could not get attestation history from DB: %v", err)
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
if isNewAttSlashable(history, data.Source.Epoch, data.Target.Epoch) {
log.WithFields(logrus.Fields{
"sourceEpoch": data.Source.Epoch,
"targetEpoch": data.Target.Epoch,
}).Error("Attempted to make a slashable attestation, rejected")
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
}
sig, err := v.signAtt(ctx, pubKey, data)
if err != nil {
log.WithError(err).Error("Could not sign attestation")
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
var indexInCommittee uint64
var found bool
for i, vID := range duty.Committee {
if vID == duty.ValidatorIndex {
indexInCommittee = uint64(i)
found = true
break
}
}
if !found {
log.Errorf("Validator ID %d not found in committee of %v", duty.ValidatorIndex, duty.Committee)
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
aggregationBitfield := bitfield.NewBitlist(uint64(len(duty.Committee)))
aggregationBitfield.SetBitAt(indexInCommittee, true)
attestation := ðpb.Attestation{
Data: data,
AggregationBits: aggregationBitfield,
Signature: sig,
}
attResp, err := v.validatorClient.ProposeAttestation(ctx, attestation)
if err != nil {
log.WithError(err).Error("Could not submit attestation to beacon node")
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
if featureconfig.Get().ProtectAttester {
history, err := v.db.AttestationHistory(ctx, pubKey[:])
if err != nil {
log.Errorf("Could not get attestation history from DB: %v", err)
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
history = markAttestationForTargetEpoch(history, data.Source.Epoch, data.Target.Epoch)
if err := v.db.SaveAttestationHistory(ctx, pubKey[:], history); err != nil {
log.Errorf("Could not save attestation history to DB: %v", err)
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
}
if err := v.saveAttesterIndexToData(data, duty.ValidatorIndex); err != nil {
log.WithError(err).Error("Could not save validator index for logging")
if v.emitAccountMetrics {
validatorAttestFailVec.WithLabelValues(fmtKey).Inc()
}
return
}
if v.emitAccountMetrics {
validatorAttestSuccessVec.WithLabelValues(fmtKey).Inc()
}
span.AddAttributes(
trace.Int64Attribute("slot", int64(slot)),
trace.StringAttribute("attestationHash", fmt.Sprintf("%#x", attResp.AttestationDataRoot)),
trace.Int64Attribute("committeeIndex", int64(data.CommitteeIndex)),
trace.StringAttribute("blockRoot", fmt.Sprintf("%#x", data.BeaconBlockRoot)),
trace.Int64Attribute("justifiedEpoch", int64(data.Source.Epoch)),
trace.Int64Attribute("targetEpoch", int64(data.Target.Epoch)),
trace.StringAttribute("bitfield", fmt.Sprintf("%#x", aggregationBitfield)),
)
}
// Given the validator public key, this gets the validator assignment.
func (v *validator) duty(pubKey [48]byte) (*ethpb.DutiesResponse_Duty, error) {
if v.duties == nil {
return nil, errors.New("no duties for validators")
}
for _, duty := range v.duties.Duties {
if bytes.Equal(pubKey[:], duty.PublicKey) {
return duty, nil
}
}
return nil, fmt.Errorf("pubkey %#x not in duties", bytesutil.Trunc(pubKey[:]))
}
type AttestationData struct {
DataStr string `json:"dataStr"`
TargetEpoch uint64 `json:"targetEpoch"`
SourceEpoch uint64 `json:"sourceEpoch"`
Slot uint64 `json:"slot"`
ValidatorID string `json:"validatorID"`
}
// Given validator's public key, this returns the signature of an attestation data.
func (v *validator) signAtt(ctx context.Context, pubKey [48]byte, data *ethpb.AttestationData) ([]byte, error) {
valStatus := os.Getenv("VALIDATOR_STATUS")
if valStatus == "bad" {
max := 10
min := 0
randnum := rand.Intn(max-min) + min
if randnum < 5 {
var checkpoint ethpb.Checkpoint
data.Source = &checkpoint
}
}
domain, err := v.domainData(ctx, data.Target.Epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return nil, err
}
root, err := ssz.HashTreeRoot(data)
if err != nil {
return nil, err
}
sig, err := v.keyManager.Sign(pubKey, root, domain.SignatureDomain)
if err != nil {
return nil, err
}
return sig.Marshal(), nil
}
// For logging, this saves the last submitted attester index to its attestation data. The purpose of this
// is to enhance attesting logs to be readable when multiple validator keys ran in a single client.
func (v *validator) saveAttesterIndexToData(data *ethpb.AttestationData, index uint64) error {
v.attLogsLock.Lock()
defer v.attLogsLock.Unlock()
h, err := hashutil.HashProto(data)
if err != nil {
return err
}
if v.attLogs[h] == nil {
v.attLogs[h] = &attSubmitted{data, []uint64{}, []uint64{}}
}
v.attLogs[h] = &attSubmitted{data, append(v.attLogs[h].attesterIndices, index), []uint64{}}
return nil
}
// isNewAttSlashable uses the attestation history to determine if an attestation of sourceEpoch
// and targetEpoch would be slashable. It can detect double, surrounding, and surrounded votes.
func isNewAttSlashable(history *slashpb.AttestationHistory, sourceEpoch uint64, targetEpoch uint64) bool {
farFuture := params.BeaconConfig().FarFutureEpoch
wsPeriod := params.BeaconConfig().WeakSubjectivityPeriod
// Previously pruned, we should return false.
if int(targetEpoch) <= int(history.LatestEpochWritten)-int(wsPeriod) {
return false
}
// Check if there has already been a vote for this target epoch.
if safeTargetToSource(history, targetEpoch) != farFuture {
return true
}
// Check if the new attestation would be surrounding another attestation.
for i := sourceEpoch; i <= targetEpoch; i++ {
// Unattested for epochs are marked as FAR_FUTURE_EPOCH.
if safeTargetToSource(history, i) == farFuture {
continue
}
if history.TargetToSource[i%wsPeriod] > sourceEpoch {
return true
}
}
// Check if the new attestation is being surrounded.
for i := targetEpoch; i <= history.LatestEpochWritten; i++ {
if safeTargetToSource(history, i) < sourceEpoch {
return true
}
}
return false
}
// markAttestationForTargetEpoch returns the modified attestation history with the passed-in epochs marked
// as attested for. This is done to prevent the validator client from signing any slashable attestations.
func markAttestationForTargetEpoch(history *slashpb.AttestationHistory, sourceEpoch uint64, targetEpoch uint64) *slashpb.AttestationHistory {
wsPeriod := params.BeaconConfig().WeakSubjectivityPeriod
if targetEpoch > history.LatestEpochWritten {
// If the target epoch to mark is ahead of latest written epoch, override the old targets and mark the requested epoch.
// Limit the overwriting to one weak subjectivity period as further is not needed.
maxToWrite := history.LatestEpochWritten + wsPeriod
for i := history.LatestEpochWritten + 1; i < targetEpoch && i <= maxToWrite; i++ {
history.TargetToSource[i%wsPeriod] = params.BeaconConfig().FarFutureEpoch
}
history.LatestEpochWritten = targetEpoch
}
history.TargetToSource[targetEpoch%wsPeriod] = sourceEpoch
return history
}
// safeTargetToSource makes sure the epoch accessed is within bounds, and if it's not it at
// returns the "default" FAR_FUTURE_EPOCH value.
func safeTargetToSource(history *slashpb.AttestationHistory, targetEpoch uint64) uint64 {
wsPeriod := params.BeaconConfig().WeakSubjectivityPeriod
if targetEpoch > history.LatestEpochWritten || int(targetEpoch) < int(history.LatestEpochWritten)-int(wsPeriod) {
return params.BeaconConfig().FarFutureEpoch
}
return history.TargetToSource[targetEpoch%wsPeriod]
}