-
Notifications
You must be signed in to change notification settings - Fork 1
/
apis.go
78 lines (62 loc) · 1.92 KB
/
apis.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
package beacon
import (
"fmt"
"context"
"encoding/json"
"errors"
"time"
"github.com/sirupsen/logrus"
"github.com/r3labs/sse/v2"
"github.com/attestantio/go-eth2-client/spec/phase0"
)
func (b *BeaconService) Status() (res *SyncStatusData, err error) {
return b.syncProgress(context.Background())
}
func (b *BeaconService) FinalizedValidatorEffectiveBalance(blsKeys []phase0.BLSPubKey) (res map[phase0.BLSPubKey]uint64, err error) {
res = make(map[phase0.BLSPubKey]uint64)
if len(blsKeys) == 0 {
return res, nil
}
validatorInfo, err := b.getValidatorsFinalizedInfo(context.Background(), blsKeys)
if err != nil {
return res, err
}
for _, v := range validatorInfo {
res[v.Validator.Pubkey] = v.Validator.EffectiveBalance
}
return res, nil
}
func (b *BeaconService) SubscribeToHeadEvents(ctx context.Context, headEvent chan<- HeadEventData) error {
/*
Subscribe to head events from the beacon chain
Events are sent to the headChannel
*/
logger := logrus.WithField("moduleExecution", "k2")
logger.Debugf("Starting head events subscription to node:%s", b.cfg.BeaconNodeUrl.String())
defer logger.Debugf("Head events subscription ended")
for {
client := sse.NewClient(fmt.Sprintf("%s/eth/v1/events?topics=head", b.cfg.BeaconNodeUrl.String()))
// Use sse client to subscribe to events
err := client.SubscribeRawWithContext(ctx, func(msg *sse.Event) {
var event HeadEventData
if err := json.Unmarshal(msg.Data, &event); err != nil {
logger.Warn("Head event subscription failed", "error", err)
return
}
b.mu.Lock()
if b.currentSlot < event.Slot {
b.currentSlot = event.Slot
}
b.mu.Unlock()
headEvent <- event
})
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil
}
if err != nil {
logger.Error("Failed to subscribe to head events")
time.Sleep(1 * time.Second)
}
logger.Warn("Head event SubscribeRaw ended, reconnecting")
}
}