forked from attestantio/go-eth2-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executionpayloadheader.go
386 lines (355 loc) · 12.5 KB
/
executionpayloadheader.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
// Copyright © 2022 Attestant Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package capella
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"strconv"
"strings"
"github.com/jefmcl/go-eth2-client/spec/bellatrix"
"github.com/jefmcl/go-eth2-client/spec/phase0"
"github.com/goccy/go-yaml"
"github.com/pkg/errors"
)
// ExecutionPayloadHeader represents an execution layer payload header.
type ExecutionPayloadHeader struct {
ParentHash phase0.Hash32 `ssz-size:"32"`
FeeRecipient bellatrix.ExecutionAddress `ssz-size:"20"`
StateRoot [32]byte `ssz-size:"32"`
ReceiptsRoot [32]byte `ssz-size:"32"`
LogsBloom [256]byte `ssz-size:"256"`
PrevRandao [32]byte `ssz-size:"32"`
BlockNumber uint64
GasLimit uint64
GasUsed uint64
Timestamp uint64
ExtraData []byte `ssz-max:"32"`
BaseFeePerGas [32]byte `ssz-size:"32"`
BlockHash phase0.Hash32 `ssz-size:"32"`
TransactionsRoot phase0.Root `ssz-size:"32"`
WithdrawalsRoot phase0.Root `ssz-size:"32"`
}
// executionPayloadHeaderJSON is the spec representation of the struct.
type executionPayloadHeaderJSON struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlockHash string `json:"block_hash"`
TransactionsRoot string `json:"transactions_root"`
WithdrawalsRoot string `json:"withdrawals_root"`
}
// executionPayloadHeaderYAML is the spec representation of the struct.
type executionPayloadHeaderYAML struct {
ParentHash string `yaml:"parent_hash"`
FeeRecipient string `yaml:"fee_recipient"`
StateRoot string `yaml:"state_root"`
ReceiptsRoot string `yaml:"receipts_root"`
LogsBloom string `yaml:"logs_bloom"`
PrevRandao string `yaml:"prev_randao"`
BlockNumber uint64 `yaml:"block_number"`
GasLimit uint64 `yaml:"gas_limit"`
GasUsed uint64 `yaml:"gas_used"`
Timestamp uint64 `yaml:"timestamp"`
ExtraData string `yaml:"extra_data"`
BaseFeePerGas string `yaml:"base_fee_per_gas"`
BlockHash string `yaml:"block_hash"`
TransactionsRoot string `yaml:"transactions_root"`
WithdrawalsRoot string `yaml:"withdrawals_root"`
}
// MarshalJSON implements json.Marshaler.
func (e *ExecutionPayloadHeader) MarshalJSON() ([]byte, error) {
extraData := "0x"
if len(e.ExtraData) > 0 {
extraData = fmt.Sprintf("%#x", e.ExtraData)
}
// base fee per gas is stored little-endian but we need it
// big-endian for big.Int.
var baseFeePerGasBEBytes [32]byte
for i := 0; i < 32; i++ {
baseFeePerGasBEBytes[i] = e.BaseFeePerGas[32-1-i]
}
baseFeePerGas := new(big.Int).SetBytes(baseFeePerGasBEBytes[:])
return json.Marshal(&executionPayloadHeaderJSON{
ParentHash: fmt.Sprintf("%#x", e.ParentHash),
FeeRecipient: e.FeeRecipient.String(),
StateRoot: fmt.Sprintf("%#x", e.StateRoot),
ReceiptsRoot: fmt.Sprintf("%#x", e.ReceiptsRoot),
LogsBloom: fmt.Sprintf("%#x", e.LogsBloom),
PrevRandao: fmt.Sprintf("%#x", e.PrevRandao),
BlockNumber: fmt.Sprintf("%d", e.BlockNumber),
GasLimit: fmt.Sprintf("%d", e.GasLimit),
GasUsed: fmt.Sprintf("%d", e.GasUsed),
Timestamp: fmt.Sprintf("%d", e.Timestamp),
ExtraData: extraData,
BaseFeePerGas: baseFeePerGas.String(),
BlockHash: fmt.Sprintf("%#x", e.BlockHash),
TransactionsRoot: fmt.Sprintf("%#x", e.TransactionsRoot),
WithdrawalsRoot: fmt.Sprintf("%#x", e.WithdrawalsRoot),
})
}
// UnmarshalJSON implements json.Unmarshaler.
func (e *ExecutionPayloadHeader) UnmarshalJSON(input []byte) error {
var data executionPayloadHeaderJSON
if err := json.Unmarshal(input, &data); err != nil {
return errors.Wrap(err, "invalid JSON")
}
return e.unpack(&data)
}
// nolint:gocyclo
func (e *ExecutionPayloadHeader) unpack(data *executionPayloadHeaderJSON) error {
if data.ParentHash == "" {
return errors.New("parent hash missing")
}
parentHash, err := hex.DecodeString(strings.TrimPrefix(data.ParentHash, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for parent hash")
}
if len(parentHash) != phase0.Hash32Length {
return errors.New("incorrect length for parent hash")
}
copy(e.ParentHash[:], parentHash)
if data.FeeRecipient == "" {
return errors.New("fee recipient missing")
}
feeRecipient, err := hex.DecodeString(strings.TrimPrefix(data.FeeRecipient, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for fee recipient")
}
if len(feeRecipient) != bellatrix.FeeRecipientLength {
return errors.New("incorrect length for fee recipient")
}
copy(e.FeeRecipient[:], feeRecipient)
if data.StateRoot == "" {
return errors.New("state root missing")
}
stateRoot, err := hex.DecodeString(strings.TrimPrefix(data.StateRoot, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for state root")
}
if len(stateRoot) != 32 {
return errors.New("incorrect length for state root")
}
copy(e.StateRoot[:], stateRoot)
if data.ReceiptsRoot == "" {
return errors.New("receipts root missing")
}
receiptsRoot, err := hex.DecodeString(strings.TrimPrefix(data.ReceiptsRoot, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for receipts root")
}
if len(receiptsRoot) != 32 {
return errors.New("incorrect length for receipts root")
}
copy(e.ReceiptsRoot[:], receiptsRoot)
if data.LogsBloom == "" {
return errors.New("logs bloom missing")
}
logsBloom, err := hex.DecodeString(strings.TrimPrefix(data.LogsBloom, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for logs bloom")
}
if len(logsBloom) != 256 {
return errors.New("incorrect length for logs bloom")
}
copy(e.LogsBloom[:], logsBloom)
if data.PrevRandao == "" {
return errors.New("prev randao missing")
}
prevRandao, err := hex.DecodeString(strings.TrimPrefix(data.PrevRandao, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for prev randao")
}
if len(prevRandao) != 32 {
return errors.New("incorrect length for prev randao")
}
copy(e.PrevRandao[:], prevRandao)
if data.BlockNumber == "" {
return errors.New("block number missing")
}
blockNumber, err := strconv.ParseUint(data.BlockNumber, 10, 64)
if err != nil {
return errors.Wrap(err, "invalid value for block number")
}
e.BlockNumber = blockNumber
if data.GasLimit == "" {
return errors.New("gas limit missing")
}
gasLimit, err := strconv.ParseUint(data.GasLimit, 10, 64)
if err != nil {
return errors.Wrap(err, "invalid value for gas limit")
}
e.GasLimit = gasLimit
if data.GasUsed == "" {
return errors.New("gas used missing")
}
gasUsed, err := strconv.ParseUint(data.GasUsed, 10, 64)
if err != nil {
return errors.Wrap(err, "invalid value for gas used")
}
e.GasUsed = gasUsed
if data.Timestamp == "" {
return errors.New("timestamp missing")
}
e.Timestamp, err = strconv.ParseUint(data.Timestamp, 10, 64)
if err != nil {
return errors.Wrap(err, "invalid value for timestamp")
}
if data.ExtraData == "" {
return errors.New("extra data missing")
}
switch {
case data.ExtraData == "0x":
e.ExtraData = make([]byte, 0)
default:
data.ExtraData = strings.TrimPrefix(data.ExtraData, "0x")
if len(data.ExtraData)%2 == 1 {
data.ExtraData = fmt.Sprintf("0%s", data.ExtraData)
}
extraData, err := hex.DecodeString(data.ExtraData)
if err != nil {
return errors.Wrap(err, "invalid value for extra data")
}
if len(extraData) > 32 {
return errors.New("incorrect length for extra data")
}
e.ExtraData = extraData
}
if data.BaseFeePerGas == "" {
return errors.New("base fee per gas missing")
}
baseFeePerGas := new(big.Int)
var ok bool
input := data.BaseFeePerGas
if strings.HasPrefix(data.BaseFeePerGas, "0x") {
input = strings.TrimPrefix(input, "0x")
if len(data.BaseFeePerGas)%2 == 1 {
input = fmt.Sprintf("0%s", input)
}
baseFeePerGas, ok = baseFeePerGas.SetString(input, 16)
} else {
baseFeePerGas, ok = baseFeePerGas.SetString(input, 10)
}
if !ok {
return errors.New("invalid value for base fee per gas")
}
if baseFeePerGas.Cmp(maxBaseFeePerGas) > 0 {
return errors.New("overflow for base fee per gas")
}
// We need to store internally as little-endian, but big.Int uses
// big-endian so do it manually.
baseFeePerGasBEBytes := baseFeePerGas.Bytes()
var baseFeePerGasLEBytes [32]byte
baseFeeLen := len(baseFeePerGasBEBytes)
for i := 0; i < baseFeeLen; i++ {
baseFeePerGasLEBytes[i] = baseFeePerGasBEBytes[baseFeeLen-1-i]
}
copy(e.BaseFeePerGas[:], baseFeePerGasLEBytes[:])
if data.BlockHash == "" {
return errors.New("block hash missing")
}
blockHash, err := hex.DecodeString(strings.TrimPrefix(data.BlockHash, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for block hash")
}
if len(blockHash) != phase0.Hash32Length {
return errors.New("incorrect length for block hash")
}
copy(e.BlockHash[:], blockHash)
if data.TransactionsRoot == "" {
return errors.New("transactions root missing")
}
transactionsRoot, err := hex.DecodeString(strings.TrimPrefix(data.TransactionsRoot, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for transactions root")
}
if len(transactionsRoot) != phase0.Hash32Length {
return errors.New("incorrect length for transactions root")
}
copy(e.TransactionsRoot[:], transactionsRoot)
if data.WithdrawalsRoot == "" {
return errors.New("withdrawals root missing")
}
withdrawalsRoot, err := hex.DecodeString(strings.TrimPrefix(data.WithdrawalsRoot, "0x"))
if err != nil {
return errors.Wrap(err, "invalid value for withdrawals root")
}
if len(withdrawalsRoot) != phase0.Hash32Length {
return errors.New("incorrect length for withdrawals root")
}
copy(e.WithdrawalsRoot[:], withdrawalsRoot)
return nil
}
// MarshalYAML implements yaml.Marshaler.
func (e *ExecutionPayloadHeader) MarshalYAML() ([]byte, error) {
extraData := "0x"
if len(e.ExtraData) > 0 {
extraData = fmt.Sprintf("%#x", e.ExtraData)
}
// base fee per gas is stored little-endian but we need it
// big-endian for big.Int.
var baseFeePerGasBEBytes [32]byte
for i := 0; i < 32; i++ {
baseFeePerGasBEBytes[i] = e.BaseFeePerGas[32-1-i]
}
baseFeePerGas := new(big.Int).SetBytes(baseFeePerGasBEBytes[:])
yamlBytes, err := yaml.MarshalWithOptions(&executionPayloadHeaderYAML{
ParentHash: fmt.Sprintf("%#x", e.ParentHash),
FeeRecipient: e.FeeRecipient.String(),
StateRoot: fmt.Sprintf("%#x", e.StateRoot),
ReceiptsRoot: fmt.Sprintf("%#x", e.ReceiptsRoot),
LogsBloom: fmt.Sprintf("%#x", e.LogsBloom),
PrevRandao: fmt.Sprintf("%#x", e.PrevRandao),
BlockNumber: e.BlockNumber,
GasLimit: e.GasLimit,
GasUsed: e.GasUsed,
Timestamp: e.Timestamp,
ExtraData: extraData,
BaseFeePerGas: baseFeePerGas.String(),
BlockHash: fmt.Sprintf("%#x", e.BlockHash),
TransactionsRoot: fmt.Sprintf("%#x", e.TransactionsRoot),
WithdrawalsRoot: fmt.Sprintf("%#x", e.WithdrawalsRoot),
}, yaml.Flow(true))
if err != nil {
return nil, err
}
return bytes.ReplaceAll(yamlBytes, []byte(`"`), []byte(`'`)), nil
}
// UnmarshalYAML implements yaml.Unmarshaler.
func (e *ExecutionPayloadHeader) UnmarshalYAML(input []byte) error {
// We unmarshal to the JSON struct to save on duplicate code.
var data executionPayloadHeaderJSON
if err := yaml.Unmarshal(input, &data); err != nil {
return err
}
return e.unpack(&data)
}
// String returns a string version of the structure.
func (e *ExecutionPayloadHeader) String() string {
data, err := yaml.Marshal(e)
if err != nil {
return fmt.Sprintf("ERR: %v", err)
}
return string(data)
}