-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient_beacon.go
457 lines (387 loc) · 11.7 KB
/
client_beacon.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"gopkg.in/inconshreveable/log15.v2"
)
var (
// Info Retrieval Global Timeout
InfoRetrievalTimeout = 61 * time.Second
)
type BeaconClient struct {
Type ClientType
ID int
BaseURL string
HTTPClient *http.Client
PreviousEpoch uint64
// Spec config
Spec Spec
// Genesis
GenesisTime *uint64
// Merge related
TTD TTD
TTDSlotNumber *uint64
// Merge Related
TTDTimestamp *uint64
// Lock
l sync.Mutex
// Context related
lastCtx context.Context
lastCancel context.CancelFunc
}
func NewBeaconClient(clientType ClientType, id int, baseUrl string) (*BeaconClient, error) {
client := &http.Client{}
if baseUrl[len(baseUrl)-1:] == "/" {
baseUrl = baseUrl[:len(baseUrl)-1]
}
cl := BeaconClient{
Type: clientType,
ID: id,
BaseURL: baseUrl,
HTTPClient: client,
}
var res Spec
if err := cl.sendRequest(GET_REQUEST, V1_CONFIG_SPEC_ENDPOINT, &res); err != nil {
return nil, err
}
cl.Spec = res
return &cl, nil
}
func (cl *BeaconClient) ClientLayer() ClientLayer {
return Beacon
}
func (cl *BeaconClient) ClientVersion() (string, error) {
type BeaconVersion struct {
Version string `json:"version"`
}
var resp BeaconVersion
err := cl.sendRequest(GET_REQUEST, V1_NODE_VERSION_ENDPOINT, &resp)
if err != nil {
return "", err
}
return resp.Version, nil
}
func (cl *BeaconClient) UpdateTTDTimestamp(newTimestamp uint64) {
timestamp := newTimestamp
cl.TTDTimestamp = ×tamp
}
func (cl *BeaconClient) GetGenesisTime() *uint64 {
if cl.GenesisTime == nil {
res := GenesisResponse{}
if err := cl.sendRequest(GET_REQUEST, V1_BEACON_GENESIS_ENDPOINT, &res); err == nil {
genesisTime := res.GenesisTime
cl.GenesisTime = &genesisTime
}
}
return cl.GenesisTime
}
func (cl *BeaconClient) SlotAtTime(t uint64) (uint64, error) {
genesisTime := cl.GetGenesisTime()
if genesisTime == nil {
return 0, fmt.Errorf("no genesis yet")
}
if (*genesisTime) > t {
return 0, fmt.Errorf("time before genesis")
}
return (t - (*genesisTime)) / cl.Spec.SecondsPerSlot, nil
}
func (cl *BeaconClient) EpochForSlot(slot uint64) uint64 {
return slot / cl.Spec.SlotsPerEpoch
}
func (cl *BeaconClient) GetOngoingSlotNumber() (uint64, error) {
return cl.SlotAtTime(uint64(time.Now().Unix()))
}
func (cl *BeaconClient) GetOngoingEpochNumber() (uint64, error) {
slot, err := cl.GetOngoingSlotNumber()
if err != nil {
return 0, err
}
return cl.EpochForSlot(slot), nil
}
func (cl *BeaconClient) GetLatestBlockSlotNumber() (uint64, error) {
return cl.GetOngoingSlotNumber()
}
func (cl *BeaconClient) UpdateGetTTDBlockSlot() (*uint64, error) {
// We need to have the TTD block timestamp from the Execution Clients
if cl.TTDSlotNumber != nil {
return cl.TTDSlotNumber, nil
}
if cl.TTDTimestamp != nil {
slotAtTTD, err := cl.SlotAtTime(*cl.TTDTimestamp)
if err != nil {
return nil, err
}
cl.TTDSlotNumber = &slotAtTTD
return cl.TTDSlotNumber, nil
}
return nil, nil
}
func (cl *BeaconClient) GetBeaconHeader(slotNumber uint64) (*BeaconHeaderResponse, error) {
var resp BeaconHeaderResponse
err := cl.sendRequest(GET_REQUEST, fmt.Sprintf(V1_BEACON_HEADERS_ENDPOINT, slotNumber), &resp)
return &resp, err
}
func (cl *BeaconClient) GetFinalityCheckpoints(slotNumber uint64) (*StateFinalityCheckpoints, error) {
var resp StateFinalityCheckpoints
err := cl.sendRequest(GET_REQUEST, fmt.Sprintf(V1_BEACON_STATE_FINALITY_CHECKPOINTS_ENDPOINT, slotNumber), &resp)
return &resp, err
}
func (cl *BeaconClient) GetSlotCommittees(slotNumber uint64) (*[]Committee, error) {
committees := make([]Committee, 0)
var allCommittees []Committee
if err := cl.sendRequest(GET_REQUEST, fmt.Sprintf(V1_BEACON_STATE_COMMITTEES_ENDPOINT, slotNumber), &allCommittees); err != nil {
return nil, err
}
for _, c := range allCommittees {
if c.Slot == slotNumber {
committees = append(committees, c)
}
}
return &committees, nil
}
func (cl *BeaconClient) GetSlotCommitteeSize(slotNumber uint64) (uint64, error) {
slotCommittees, err := cl.GetSlotCommittees(slotNumber)
if err != nil {
return 0, err
}
var committeeCount uint64
for _, sc := range *slotCommittees {
committeeCount += uint64(len(sc.Validators))
}
return committeeCount, nil
}
func (cl *BeaconClient) GetSyncParticipationCountAtSlot(blockNumber uint64) (uint64, error) {
var block BeaconBlock
if err := cl.sendRequest(GET_REQUEST, fmt.Sprintf(V2_BEACON_BLOCKS_ENDPOINT, blockNumber), &block); err != nil {
return 0, err
}
return block.BlockMessage.Body.SyncAggregate.SyncCommitteeBits.CountSetBits(), nil
}
func (cl *BeaconClient) GetSyncParticipationPercentageAtSlot(blockNumber uint64) (uint64, error) {
syncParticipationCount, err := cl.GetSyncParticipationCountAtSlot(blockNumber)
if err != nil {
return 0, err
}
return (syncParticipationCount * 100) / cl.Spec.SyncCommitteeSize, nil
}
func (cl *BeaconClient) GetAttestationsAtBlock(blockNumber uint64) (*[]Attestation, error) {
var allAttestations []Attestation
if err := cl.sendRequest(GET_REQUEST, fmt.Sprintf(V1_BEACON_BLOCKS_ATTESTATIONS_ENDPOINT, blockNumber), &allAttestations); err != nil {
return nil, err
}
return &allAttestations, nil
}
func (cl *BeaconClient) GetAttestationCountForSlot(slotNumber uint64) (uint64, error) {
timeout := time.After(InfoRetrievalTimeout)
lastVerifiedBlock := slotNumber
for {
latestSlot, _ := cl.GetLatestBlockSlotNumber()
for latestSlot > lastVerifiedBlock {
attBlock, err := cl.GetAttestationsAtBlock(lastVerifiedBlock + 1)
if err != nil {
break
}
for _, att := range *attBlock {
if att.Data.Slot == slotNumber {
// we got the attestations
attCount := att.AggregationBits.CountSetBits()
if attCount > 0 {
attCount -= 1
}
return attCount, nil
}
}
lastVerifiedBlock++
}
select {
case <-time.After(time.Second):
case <-timeout:
return 0, fmt.Errorf("timeout waiting for attestation count")
}
}
}
func (cl *BeaconClient) GetDataPoint(dataName MetricName, slotNumber uint64) (interface{}, error) {
for {
// We fetch information only for previous slots, not current ongoing slot
ongoingSlot, _ := cl.GetOngoingSlotNumber()
if cl.EpochForSlot(ongoingSlot) > cl.PreviousEpoch {
log15.Info("New epoch reached", "client", cl.ClientType(), "clientID", cl.ClientID(), "epoch", cl.EpochForSlot(ongoingSlot))
cl.PreviousEpoch = cl.EpochForSlot(ongoingSlot)
}
if slotNumber < ongoingSlot {
break
}
time.Sleep(time.Second)
}
switch dataName {
case BeaconBlockCount:
if _, err := cl.GetBeaconHeader(slotNumber); err == nil {
return uint64(1), nil
}
return uint64(0), nil
case FinalizedEpoch:
// Return `1` for each Finalized root change
if slotNumber == 0 || (slotNumber%cl.Spec.SlotsPerEpoch) != 0 {
return uint64(0), nil
}
currentSlotFinalityCheckpoint, err := cl.GetFinalityCheckpoints(slotNumber)
if err != nil {
return nil, err
}
if currentSlotFinalityCheckpoint.Finalized.Root == (common.Hash{}) {
return uint64(0), nil
}
prevSlotFinalityCheckpoint, err := cl.GetFinalityCheckpoints(slotNumber - 1)
if err != nil {
return nil, err
}
if prevSlotFinalityCheckpoint.Finalized.Root != currentSlotFinalityCheckpoint.Finalized.Root {
return uint64(1), nil
}
return uint64(0), nil
case JustifiedEpoch:
// Return `1` for each Justified root change
if slotNumber == 0 || (slotNumber%cl.Spec.SlotsPerEpoch) != 0 {
return uint64(0), nil
}
currentSlotFinalityCheckpoint, err := cl.GetFinalityCheckpoints(slotNumber)
if err != nil {
return nil, err
}
if currentSlotFinalityCheckpoint.Justified.Root == (common.Hash{}) {
return uint64(0), nil
}
prevSlotFinalityCheckpoint, err := cl.GetFinalityCheckpoints(slotNumber - 1)
if err != nil {
return nil, err
}
if prevSlotFinalityCheckpoint.Justified.Root != currentSlotFinalityCheckpoint.Justified.Root {
return uint64(1), nil
}
return uint64(0), nil
case SlotAttestations:
return cl.GetAttestationCountForSlot(slotNumber)
case SlotAttestationsPercentage:
committeeSize, err := cl.GetSlotCommitteeSize(slotNumber)
if err != nil {
return uint64(0), err
}
if committeeSize == 0 {
return committeeSize, fmt.Errorf("empty committee for slot %d", slotNumber)
}
slotAttestations, err := cl.GetAttestationCountForSlot(slotNumber)
if err != nil {
return uint64(0), err
}
return (slotAttestations * 100) / committeeSize, nil
case EpochAttestationPerformance:
switch cl.ClientType() {
case Lighthouse:
currentEpoch, err := cl.GetOngoingEpochNumber()
if err != nil {
return nil, err
}
if cl.EpochForSlot(slotNumber) >= currentEpoch {
// We can only get accurate information for previous epoch
return nil, fmt.Errorf("No information available yet")
}
var resp ValidatorInclusionGlobal
err = cl.sendRequest(GET_REQUEST, fmt.Sprintf(LIGHTHOUSE_GLOBAL_VALIDATOR_INCLUSION, cl.EpochForSlot(slotNumber)), &resp)
if err != nil {
return nil, err
}
return (resp.PreviousEpochHeadAttestingGwei * 100) / resp.PreviousEpochActiveGwei, nil
default:
return nil, fmt.Errorf("Invalid client for metric")
}
case EpochTargetAttestationPerformance:
switch cl.ClientType() {
case Lighthouse:
currentEpoch, err := cl.GetOngoingEpochNumber()
if err != nil {
return nil, err
}
if cl.EpochForSlot(slotNumber) >= currentEpoch {
// We can only get accurate information for previous epoch
return nil, fmt.Errorf("No information available yet")
}
var resp ValidatorInclusionGlobal
err = cl.sendRequest(GET_REQUEST, fmt.Sprintf(LIGHTHOUSE_GLOBAL_VALIDATOR_INCLUSION, cl.EpochForSlot(slotNumber)), &resp)
if err != nil {
return nil, err
}
return (resp.PreviousEpochTargetAttestingGwei * 100) / resp.PreviousEpochActiveGwei, nil
default:
return nil, fmt.Errorf("Invalid client for metric")
}
case SyncParticipationCount:
return cl.GetSyncParticipationCountAtSlot(slotNumber)
case SyncParticipationPercentage:
return cl.GetSyncParticipationPercentageAtSlot(slotNumber)
}
return nil, fmt.Errorf("invalid data name: %s", dataName)
}
func (cl *BeaconClient) Ctx() context.Context {
if cl.lastCtx != nil {
cl.lastCancel()
}
cl.lastCtx, cl.lastCancel = context.WithTimeout(context.Background(), 10*time.Second)
return cl.lastCtx
}
type errorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
type successResponse struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
func (cl *BeaconClient) sendRequest(requestType string, requestEndPoint string, v interface{}) error {
cl.l.Lock()
defer cl.l.Unlock()
req, err := http.NewRequest(requestType, fmt.Sprintf("%s%s", cl.BaseURL, requestEndPoint), nil)
if err != nil {
return err
}
req = req.WithContext(cl.Ctx())
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json")
res, err := cl.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Message)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
fullResponse := successResponse{
Data: v,
}
if err = json.NewDecoder(res.Body).Decode(&fullResponse); err != nil {
return err
}
return nil
}
func (cl *BeaconClient) String() string {
return cl.BaseURL
}
func (cl *BeaconClient) ClientType() ClientType {
return cl.Type
}
func (cl *BeaconClient) ClientID() int {
return cl.ID
}
func (cl *BeaconClient) Close() error {
cl.HTTPClient.CloseIdleConnections()
return nil
}