-
Notifications
You must be signed in to change notification settings - Fork 136
/
backend.go
428 lines (365 loc) · 13.2 KB
/
backend.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
package builder
import (
"bytes"
"encoding/json"
"html/template"
"math/big"
"net/http"
_ "os"
"strconv"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/beacon"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/log"
"github.com/gorilla/mux"
"github.com/flashbots/go-boost-utils/bls"
boostTypes "github.com/flashbots/go-boost-utils/types"
)
type PubkeyHex string
type ValidatorData struct {
FeeRecipient boostTypes.Address `json:"feeRecipient"`
GasLimit uint64 `json:"gasLimit"`
Timestamp uint64 `json:"timestamp"`
}
type IBeaconClient interface {
isValidator(pubkey PubkeyHex) bool
getProposerForNextSlot(requestedSlot uint64) (PubkeyHex, error)
onForkchoiceUpdate() (PubkeyHex, error)
}
type Backend struct {
beaconClient IBeaconClient
builderSecretKey *bls.SecretKey
builderPublicKey boostTypes.PublicKey
serializedBuilderPoolPubkey hexutil.Bytes
builderSigningDomain boostTypes.Domain
proposerSigningDomain boostTypes.Domain
enableBeaconChecks bool
validatorsLock sync.RWMutex
validators map[PubkeyHex]ValidatorData
bestDataLock sync.Mutex
bestHeader *boostTypes.ExecutionPayloadHeader
bestPayload *boostTypes.ExecutionPayload
profit *big.Int
indexTemplate *template.Template
}
func NewBackend(sk *bls.SecretKey, bc IBeaconClient, builderSigningDomain boostTypes.Domain, proposerSigningDomain boostTypes.Domain, enableBeaconChecks bool) *Backend {
pkBytes := bls.PublicKeyFromSecretKey(sk).Compress()
pk := boostTypes.PublicKey{}
pk.FromSlice(pkBytes)
_, err := bc.onForkchoiceUpdate()
if err != nil {
log.Error("could not initialize beacon client", "err", err)
}
indexTemplate, err := parseIndexTemplate()
if err != nil {
log.Error("could not parse index template", "err", err)
indexTemplate = nil
}
return &Backend{
beaconClient: bc,
builderSecretKey: sk,
builderPublicKey: pk,
serializedBuilderPoolPubkey: pkBytes,
builderSigningDomain: builderSigningDomain,
proposerSigningDomain: proposerSigningDomain,
enableBeaconChecks: enableBeaconChecks,
validators: make(map[PubkeyHex]ValidatorData),
indexTemplate: indexTemplate,
}
}
func (b *Backend) handleIndex(w http.ResponseWriter, req *http.Request) {
if b.indexTemplate == nil {
http.Error(w, "not available", http.StatusInternalServerError)
}
b.validatorsLock.RLock()
noValidators := len(b.validators)
b.validatorsLock.RUnlock()
header := b.bestHeader
headerData, err := json.MarshalIndent(header, "", " ")
if err != nil {
headerData = []byte{}
}
payload := b.bestPayload
payloadData, err := json.MarshalIndent(payload, "", " ")
if err != nil {
payloadData = []byte{}
}
statusData := struct {
NoValidators int
Header string
Blocks string
}{noValidators, string(headerData), string(payloadData)}
if err := b.indexTemplate.Execute(w, statusData); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (b *Backend) handleStatus(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
}
type httpErrorResp struct {
Code int `json:"code"`
Message string `json:"message"`
}
func respondError(w http.ResponseWriter, code int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(httpErrorResp{code, message}); err != nil {
http.Error(w, message, code)
}
}
func (b *Backend) handleRegisterValidator(w http.ResponseWriter, req *http.Request) {
payload := []boostTypes.SignedValidatorRegistration{}
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
log.Error("could not decode payload", "err", err)
respondError(w, http.StatusBadRequest, "invalid payload")
return
}
for _, registerRequest := range payload {
if len(registerRequest.Message.Pubkey) != 48 {
respondError(w, http.StatusBadRequest, "invalid pubkey")
return
}
if len(registerRequest.Signature) != 96 {
respondError(w, http.StatusBadRequest, "invalid signature")
return
}
ok, err := boostTypes.VerifySignature(registerRequest.Message, b.builderSigningDomain, registerRequest.Message.Pubkey[:], registerRequest.Signature[:])
if !ok || err != nil {
log.Error("error verifying signature", "err", err)
respondError(w, http.StatusBadRequest, "invalid signature")
return
}
// Do not check timestamp before signature, as it would leak validator data
if registerRequest.Message.Timestamp > uint64(time.Now().Add(10*time.Second).Unix()) {
respondError(w, http.StatusBadRequest, "invalid payload")
return
}
}
for _, registerRequest := range payload {
pubkeyHex := PubkeyHex(registerRequest.Message.Pubkey.String())
if !b.beaconClient.isValidator(pubkeyHex) {
respondError(w, http.StatusBadRequest, "not a validator")
return
}
}
b.validatorsLock.Lock()
defer b.validatorsLock.Unlock()
for _, registerRequest := range payload {
pubkeyHex := PubkeyHex(registerRequest.Message.Pubkey.String())
if previousValidatorData, ok := b.validators[pubkeyHex]; ok {
if registerRequest.Message.Timestamp < previousValidatorData.Timestamp {
respondError(w, http.StatusBadRequest, "invalid timestamp")
return
}
if registerRequest.Message.Timestamp == previousValidatorData.Timestamp && (registerRequest.Message.FeeRecipient != previousValidatorData.FeeRecipient || registerRequest.Message.GasLimit != previousValidatorData.GasLimit) {
respondError(w, http.StatusBadRequest, "invalid timestamp")
return
}
}
}
for _, registerRequest := range payload {
pubkeyHex := PubkeyHex(registerRequest.Message.Pubkey.String())
b.validators[pubkeyHex] = ValidatorData{
FeeRecipient: registerRequest.Message.FeeRecipient,
GasLimit: registerRequest.Message.GasLimit,
Timestamp: registerRequest.Message.Timestamp,
}
log.Info("registered validator", "pubkey", pubkeyHex, "data", b.validators[pubkeyHex])
}
w.WriteHeader(http.StatusOK)
}
func (b *Backend) handleGetHeader(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
slot, err := strconv.Atoi(vars["slot"])
if err != nil {
respondError(w, http.StatusBadRequest, "incorrect slot")
return
}
parentHashHex := vars["parent_hash"]
pubkeyHex := PubkeyHex(vars["pubkey"])
b.validatorsLock.RLock()
if _, ok := b.validators[pubkeyHex]; !ok {
log.Error("missing validator", "validators", b.validators, "provided", pubkeyHex)
b.validatorsLock.RUnlock()
respondError(w, http.StatusBadRequest, "unknown validator")
return
}
b.validatorsLock.RUnlock()
// Do not validate slot separately, it will create a race between slot update and proposer key
if nextSlotProposer, err := b.beaconClient.getProposerForNextSlot(uint64(slot)); err != nil || nextSlotProposer != pubkeyHex {
log.Error("getHeader requested for public key other than next slots proposer", "requested", pubkeyHex, "expected", nextSlotProposer)
if b.enableBeaconChecks {
respondError(w, http.StatusBadRequest, "unknown validator")
return
}
}
b.bestDataLock.Lock()
bestHeader := b.bestHeader
profit := b.profit
b.bestDataLock.Unlock()
if bestHeader == nil || bestHeader.ParentHash.String() != parentHashHex {
respondError(w, http.StatusBadRequest, "unknown payload")
return
}
bid := boostTypes.BuilderBid{
Header: bestHeader,
Value: [32]byte(common.BytesToHash(profit.Bytes())),
Pubkey: b.builderPublicKey,
}
signature, err := boostTypes.SignMessage(&bid, b.builderSigningDomain, b.builderSecretKey)
if err != nil {
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
response := &boostTypes.GetHeaderResponse{
Version: "bellatrix",
Data: &boostTypes.SignedBuilderBid{Message: &bid, Signature: signature},
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
}
func (b *Backend) handleGetPayload(w http.ResponseWriter, req *http.Request) {
payload := new(boostTypes.SignedBlindedBeaconBlock)
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
respondError(w, http.StatusBadRequest, "invalid payload")
return
}
if len(payload.Signature) != 96 {
respondError(w, http.StatusBadRequest, "invalid signature")
return
}
nextSlotProposerPubkeyHex, err := b.beaconClient.getProposerForNextSlot(payload.Message.Slot)
if err != nil {
if b.enableBeaconChecks {
respondError(w, http.StatusBadRequest, "unknown validator")
return
}
}
nextSlotProposerPubkeyBytes, err := hexutil.Decode(string(nextSlotProposerPubkeyHex))
if err != nil {
if b.enableBeaconChecks {
respondError(w, http.StatusBadRequest, "unknown validator")
return
}
}
ok, err := boostTypes.VerifySignature(payload.Message, b.proposerSigningDomain, nextSlotProposerPubkeyBytes[:], payload.Signature[:])
if !ok || err != nil {
if b.enableBeaconChecks {
respondError(w, http.StatusBadRequest, "invalid signature")
return
}
}
b.bestDataLock.Lock()
bestHeader := b.bestHeader
bestPayload := b.bestPayload
b.bestDataLock.Unlock()
if bestHeader == nil || bestPayload == nil {
respondError(w, http.StatusInternalServerError, "no payloads")
return
}
if !ExecutionPayloadHeaderEqual(bestHeader, payload.Message.Body.ExecutionPayloadHeader) {
respondError(w, http.StatusBadRequest, "unknown payload")
return
}
response := boostTypes.GetPayloadResponse{
Version: "bellatrix",
Data: bestPayload,
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
}
func (b *Backend) onForkchoice(payloadAttributes *beacon.PayloadAttributesV1) {
dataJson, err := json.Marshal(payloadAttributes)
if err == nil {
log.Info("FCU", "data", string(dataJson))
}
// if payloadAttributes.SuggestedFeeRecipient == common.Address{}
pubkeyHex, err := b.beaconClient.onForkchoiceUpdate()
if err != nil {
return
}
if payloadAttributes != nil {
b.validatorsLock.RLock()
vd, found := b.validators[pubkeyHex]
if found {
payloadAttributes.SuggestedFeeRecipient = [20]byte(vd.FeeRecipient)
payloadAttributes.GasLimit = vd.GasLimit
}
b.validatorsLock.RUnlock()
}
}
func (b *Backend) newSealedBlock(data *beacon.ExecutableDataV1, block *types.Block) {
dataJson, err := json.Marshal(data)
if err == nil {
log.Info("newSealedBlock", "data", string(dataJson))
}
payload := executableDataToExecutionPayload(data)
payloadHeader, err := payloadToPayloadHeader(payload, data)
if err != nil {
log.Error("could not convert payload to header", "err", err)
return
}
b.bestDataLock.Lock()
b.bestHeader = payloadHeader
b.bestPayload = payload
b.profit = new(big.Int).Set(block.Profit)
b.bestDataLock.Unlock()
}
func payloadToPayloadHeader(p *boostTypes.ExecutionPayload, data *beacon.ExecutableDataV1) (*boostTypes.ExecutionPayloadHeader, error) {
txs := boostTypes.Transactions{data.Transactions}
txroot, err := txs.HashTreeRoot()
if err != nil {
return nil, err
}
return &boostTypes.ExecutionPayloadHeader{
ParentHash: p.ParentHash,
FeeRecipient: p.FeeRecipient,
StateRoot: p.StateRoot,
ReceiptsRoot: p.ReceiptsRoot,
LogsBloom: p.LogsBloom,
Random: p.Random,
BlockNumber: p.BlockNumber,
GasLimit: p.GasLimit,
GasUsed: p.GasUsed,
Timestamp: p.Timestamp,
ExtraData: data.ExtraData,
BaseFeePerGas: p.BaseFeePerGas,
BlockHash: p.BlockHash,
TransactionsRoot: [32]byte(txroot),
}, nil
}
func executableDataToExecutionPayload(data *beacon.ExecutableDataV1) *boostTypes.ExecutionPayload {
transactionData := make([]hexutil.Bytes, len(data.Transactions))
for i, tx := range data.Transactions {
transactionData[i] = hexutil.Bytes(tx)
}
return &boostTypes.ExecutionPayload{
ParentHash: [32]byte(data.ParentHash),
FeeRecipient: [20]byte(data.FeeRecipient),
StateRoot: [32]byte(data.StateRoot),
ReceiptsRoot: [32]byte(data.ReceiptsRoot),
LogsBloom: boostTypes.Bloom(types.BytesToBloom(data.LogsBloom)),
Random: [32]byte(data.Random),
BlockNumber: data.Number,
GasLimit: data.GasLimit,
GasUsed: data.GasUsed,
Timestamp: data.Timestamp,
ExtraData: data.ExtraData,
BaseFeePerGas: *new(boostTypes.U256Str).FromBig(data.BaseFeePerGas),
BlockHash: [32]byte(data.BlockHash),
Transactions: transactionData,
}
}
func ExecutionPayloadHeaderEqual(l *boostTypes.ExecutionPayloadHeader, r *boostTypes.ExecutionPayloadHeader) bool {
return l.ParentHash == r.ParentHash && l.FeeRecipient == r.FeeRecipient && l.StateRoot == r.StateRoot && l.ReceiptsRoot == r.ReceiptsRoot && l.LogsBloom == r.LogsBloom && l.Random == r.Random && l.BlockNumber == r.BlockNumber && l.GasLimit == r.GasLimit && l.GasUsed == r.GasUsed && l.Timestamp == r.Timestamp && l.BaseFeePerGas == r.BaseFeePerGas && bytes.Equal(l.ExtraData, r.ExtraData) && l.BlockHash == r.BlockHash && l.TransactionsRoot == r.TransactionsRoot
}