/
multi.go
300 lines (248 loc) · 7.66 KB
/
multi.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
//go:generate mockgen -destination=./mocks/mocks.go -package=mocks github.com/blocknative/dreamboat/beacon/client BeaconNode
package client
import (
"context"
"errors"
"strings"
"sync"
"github.com/blocknative/dreamboat/structs"
"github.com/lthibault/log"
uberatomic "go.uber.org/atomic"
)
var (
ErrBeaconNodeSyncing = errors.New("beacon node is syncing")
ErrWithdrawalsUnsupported = errors.New("withdrawals are not supported")
ErrFailedToPublish = errors.New("failed to publish")
)
type BeaconNode interface {
SubscribeToHeadEvents(ctx context.Context, slotC chan HeadEvent)
GetProposerDuties(structs.Epoch) (*RegisteredProposersResponse, error)
SyncStatus() (*SyncStatusPayloadData, error)
KnownValidators(structs.Slot) (AllValidatorsResponse, error)
Genesis() (structs.GenesisInfo, error)
GetForkSchedule() (*GetForkScheduleResponse, error)
PublishBlock(context.Context, structs.SignedBeaconBlock) error
PublishV2Block(context.Context, structs.SignedBeaconBlock) error
Randao(structs.Slot) (string, error)
Endpoint() string
GetWithdrawals(structs.Slot) (*GetWithdrawalsResponse, error)
SubscribeToPayloadAttributesEvents(payloadAttrC chan PayloadAttributesEvent)
}
type MultiBeaconClient struct {
Log log.Logger
Clients []BeaconNode
PublishV2Clients []BeaconNode
bestBeaconIndex uberatomic.Int64
}
func NewMultiBeaconClient(l log.Logger, clients []BeaconNode) *MultiBeaconClient {
if l == nil {
l = log.New()
}
return &MultiBeaconClient{Log: l.WithField("subService", "multi-beacon-client"), Clients: clients}
}
func (b *MultiBeaconClient) SubscribeToHeadEvents(ctx context.Context, slotC chan HeadEvent) {
for _, client := range b.Clients {
go client.SubscribeToHeadEvents(ctx, slotC)
}
}
func (b *MultiBeaconClient) GetProposerDuties(epoch structs.Epoch) (*RegisteredProposersResponse, error) {
// return the first successful beacon node response
clients := b.clientsByLastResponse()
for i, client := range clients {
log := b.Log.WithField("endpoint", client.Endpoint())
duties, err := client.GetProposerDuties(epoch)
if err != nil {
log.WithError(err).Error("failed to get proposer duties")
continue
}
b.bestBeaconIndex.Store(int64(i))
// Received successful response. Set this index as last successful beacon node
return duties, nil
}
return nil, ErrNodesUnavailable
}
func (b *MultiBeaconClient) SyncStatus() (*SyncStatusPayloadData, error) {
var bestSyncStatus *SyncStatusPayloadData
var foundSyncedNode bool
// Check each beacon-node sync status
var mu sync.Mutex
var wg sync.WaitGroup
for _, instance := range b.Clients {
wg.Add(1)
go func(client BeaconNode) {
defer wg.Done()
log := b.Log.WithField("endpoint", client.Endpoint())
syncStatus, err := client.SyncStatus()
if err != nil {
log.WithError(err).Error("failed to get sync status")
return
}
mu.Lock()
defer mu.Unlock()
if foundSyncedNode {
return
}
if bestSyncStatus == nil {
bestSyncStatus = syncStatus
}
if !syncStatus.IsSyncing {
bestSyncStatus = syncStatus
foundSyncedNode = true
}
}(instance)
}
// Wait for all requests to complete...
wg.Wait()
if !foundSyncedNode {
return nil, ErrBeaconNodeSyncing
}
if bestSyncStatus == nil {
return nil, ErrNodesUnavailable
}
return bestSyncStatus, nil
}
func (b *MultiBeaconClient) KnownValidators(headSlot structs.Slot) (AllValidatorsResponse, error) {
// return the first successful beacon node response
clients := b.clientsByLastResponse()
for i, client := range clients {
log := b.Log.WithField("endpoint", client.Endpoint())
validators, err := client.KnownValidators(headSlot)
if err != nil {
log.WithError(err).Error("failed to fetch validators")
continue
}
b.bestBeaconIndex.Store(int64(i))
// Received successful response. Set this index as last successful beacon node
return validators, nil
}
return AllValidatorsResponse{}, ErrNodesUnavailable
}
func (b *MultiBeaconClient) Genesis() (genesisInfo structs.GenesisInfo, err error) {
clients := b.clientsByLastResponse()
for _, client := range clients {
if genesisInfo, err = client.Genesis(); err != nil {
b.Log.WithError(err).
WithField("endpoint", client.Endpoint()).
Warn("failed to get genesis info")
continue
}
return genesisInfo, nil
}
return genesisInfo, err
}
func (b *MultiBeaconClient) GetWithdrawals(slot structs.Slot) (withdrawalsResp *GetWithdrawalsResponse, err error) {
for _, client := range b.clientsByLastResponse() {
if withdrawalsResp, err = client.GetWithdrawals(slot); err != nil {
if strings.Contains(err.Error(), "Withdrawals not enabled before capella") {
break
}
b.Log.WithError(err).
WithField("endpoint", client.Endpoint()).
Warn("failed to get withdrawals")
continue
}
return withdrawalsResp, nil
}
if strings.Contains(err.Error(), "Withdrawals not enabled before capella") {
return nil, ErrWithdrawalsUnsupported
}
return nil, err
}
func (b *MultiBeaconClient) Randao(slot structs.Slot) (randao string, err error) {
for _, client := range b.clientsByLastResponse() {
if randao, err = client.Randao(slot); err != nil {
b.Log.WithError(err).WithField("slot", slot).WithField("endpoint", client.Endpoint()).Warn("failed to get randao")
continue
}
return
}
return
}
func (b *MultiBeaconClient) GetForkSchedule() (spec *GetForkScheduleResponse, err error) {
for _, client := range b.clientsByLastResponse() {
if spec, err = client.GetForkSchedule(); err != nil {
b.Log.WithError(err).
WithField("endpoint", client.Endpoint()).
Warn("failed to get fork")
continue
}
return spec, nil
}
return spec, err
}
func (b *MultiBeaconClient) SubscribeToPayloadAttributesEvents(slotC chan PayloadAttributesEvent) {
for _, instance := range b.Clients {
go instance.SubscribeToPayloadAttributesEvents(slotC)
}
}
func (b *MultiBeaconClient) Endpoint() string {
if clients := b.clientsByLastResponse(); len(clients) > 0 {
return clients[0].Endpoint()
}
return ""
}
// beaconInstancesByLastResponse returns a list of beacon clients that has the client
// with the last successful response as the first element of the slice
func (b *MultiBeaconClient) clientsByLastResponse() []BeaconNode {
index := b.bestBeaconIndex.Load()
if index == 0 {
return b.Clients
}
instances := make([]BeaconNode, len(b.Clients))
copy(instances, b.Clients)
instances[0], instances[index] = instances[index], instances[0]
return instances
}
func (b *MultiBeaconClient) PublishBlock(ctx context.Context, block structs.SignedBeaconBlock) (err error) {
resp := make(chan error, 20)
var i int
for _, client := range b.clientsByLastResponse() {
i++
c := client
go publishAsync(ctx, c, b.Log, block, resp)
}
for _, client := range b.PublishV2Clients {
i++
c := client
go publishV2Async(ctx, c, b.Log, block, resp)
}
var (
defError error
r int
)
for {
select {
case <-ctx.Done():
return ctx.Err()
case e := <-resp:
r++
switch e {
case nil:
return nil
default:
defError = e
if r == i {
return defError
}
}
}
}
}
func publishAsync(ctx context.Context, client BeaconNode, l log.Logger, block structs.SignedBeaconBlock, resp chan<- error) {
err := client.PublishBlock(ctx, block)
if err != nil {
l.WithError(err).
WithField("endpoint", client.Endpoint()).
Warn("failed to publish block to beacon")
}
resp <- err
}
func publishV2Async(ctx context.Context, client BeaconNode, l log.Logger, block structs.SignedBeaconBlock, resp chan<- error) {
err := client.PublishV2Block(ctx, block)
if err != nil {
l.WithError(err).
WithField("endpoint", client.Endpoint()).
Warn("failed to publish block to beacon")
}
resp <- err
}