-
Notifications
You must be signed in to change notification settings - Fork 237
/
payload.rs
1344 lines (1206 loc) · 61.3 KB
/
payload.rs
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Payload types.
use alloy_consensus::{Blob, Bytes48};
use alloy_eips::{eip6110::DepositRequest, eip7002::WithdrawalRequest};
use alloy_primitives::{Address, Bloom, Bytes, B256, B64, U256};
use alloy_rpc_types_eth::{transaction::BlobTransactionSidecar, Withdrawal};
use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
/// The execution payload body response that allows for `null` values.
pub type ExecutionPayloadBodiesV1 = Vec<Option<ExecutionPayloadBodyV1>>;
/// And 8-byte identifier for an execution payload.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PayloadId(pub B64);
// === impl PayloadId ===
impl PayloadId {
/// Creates a new payload id from the given identifier.
pub fn new(id: [u8; 8]) -> Self {
Self(B64::from(id))
}
}
impl fmt::Display for PayloadId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
/// This represents the `executionPayload` field in the return value of `engine_getPayloadV2`,
/// specified as:
///
/// - `executionPayload`: `ExecutionPayloadV1` | `ExecutionPayloadV2` where:
/// - `ExecutionPayloadV1` **MUST** be returned if the payload `timestamp` is lower than the
/// Shanghai timestamp
/// - `ExecutionPayloadV2` **MUST** be returned if the payload `timestamp` is greater or equal to
/// the Shanghai timestamp
///
/// See:
/// <https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/shanghai.md#response>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ExecutionPayloadFieldV2 {
/// V1 payload
V1(ExecutionPayloadV1),
/// V2 payload
V2(ExecutionPayloadV2),
}
impl ExecutionPayloadFieldV2 {
/// Returns the inner [ExecutionPayloadV1]
pub fn into_v1_payload(self) -> ExecutionPayloadV1 {
match self {
Self::V1(payload) => payload,
Self::V2(payload) => payload.payload_inner,
}
}
}
/// This is the input to `engine_newPayloadV2`, which may or may not have a withdrawals field.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ExecutionPayloadInputV2 {
/// The V1 execution payload
#[serde(flatten)]
pub execution_payload: ExecutionPayloadV1,
/// The payload withdrawals
#[serde(skip_serializing_if = "Option::is_none")]
pub withdrawals: Option<Vec<Withdrawal>>,
}
/// This structure maps for the return value of `engine_getPayload` of the beacon chain spec, for
/// V2.
///
/// See also:
/// <https://github.com/ethereum/execution-apis/blob/main/src/engine/shanghai.md#engine_getpayloadv2>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionPayloadEnvelopeV2 {
/// Execution payload, which could be either V1 or V2
///
/// V1 (_NO_ withdrawals) MUST be returned if the payload timestamp is lower than the Shanghai
/// timestamp
///
/// V2 (_WITH_ withdrawals) MUST be returned if the payload timestamp is greater or equal to
/// the Shanghai timestamp
pub execution_payload: ExecutionPayloadFieldV2,
/// The expected value to be received by the feeRecipient in wei
pub block_value: U256,
}
impl ExecutionPayloadEnvelopeV2 {
/// Returns the [ExecutionPayload] for the `engine_getPayloadV1` endpoint
pub fn into_v1_payload(self) -> ExecutionPayloadV1 {
self.execution_payload.into_v1_payload()
}
}
/// This structure maps for the return value of `engine_getPayload` of the beacon chain spec, for
/// V3.
///
/// See also:
/// <https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/cancun.md#response-2>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionPayloadEnvelopeV3 {
/// Execution payload V3
pub execution_payload: ExecutionPayloadV3,
/// The expected value to be received by the feeRecipient in wei
pub block_value: U256,
/// The blobs, commitments, and proofs associated with the executed payload.
pub blobs_bundle: BlobsBundleV1,
/// Introduced in V3, this represents a suggestion from the execution layer if the payload
/// should be used instead of an externally provided one.
pub should_override_builder: bool,
}
/// This structure maps for the return value of `engine_getPayload` of the beacon chain spec, for
/// V4.
///
/// See also:
/// <https://github.com/ethereum/execution-apis/blob/main/src/engine/prague.md#engine_getpayloadv4>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionPayloadEnvelopeV4 {
/// Execution payload V4
pub execution_payload: ExecutionPayloadV4,
/// The expected value to be received by the feeRecipient in wei
pub block_value: U256,
/// The blobs, commitments, and proofs associated with the executed payload.
pub blobs_bundle: BlobsBundleV1,
/// Introduced in V3, this represents a suggestion from the execution layer if the payload
/// should be used instead of an externally provided one.
pub should_override_builder: bool,
}
/// This structure maps on the ExecutionPayload structure of the beacon chain spec.
///
/// See also: <https://github.com/ethereum/execution-apis/blob/6709c2a795b707202e93c4f2867fa0bf2640a84f/src/engine/paris.md#executionpayloadv1>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ssz", derive(ssz_derive::Encode, ssz_derive::Decode))]
pub struct ExecutionPayloadV1 {
/// The parent hash of the block.
pub parent_hash: B256,
/// The fee recipient of the block.
pub fee_recipient: Address,
/// The state root of the block.
pub state_root: B256,
/// The receipts root of the block.
pub receipts_root: B256,
/// The logs bloom of the block.
pub logs_bloom: Bloom,
/// The previous randao of the block.
pub prev_randao: B256,
/// The block number.
#[serde(with = "alloy_serde::quantity")]
pub block_number: u64,
/// The gas limit of the block.
#[serde(with = "alloy_serde::quantity")]
pub gas_limit: u64,
/// The gas used of the block.
#[serde(with = "alloy_serde::quantity")]
pub gas_used: u64,
/// The timestamp of the block.
#[serde(with = "alloy_serde::quantity")]
pub timestamp: u64,
/// The extra data of the block.
pub extra_data: Bytes,
/// The base fee per gas of the block.
pub base_fee_per_gas: U256,
/// The block hash of the block.
pub block_hash: B256,
/// The transactions of the block.
pub transactions: Vec<Bytes>,
}
/// This structure maps on the ExecutionPayloadV2 structure of the beacon chain spec.
///
/// See also: <https://github.com/ethereum/execution-apis/blob/6709c2a795b707202e93c4f2867fa0bf2640a84f/src/engine/shanghai.md#executionpayloadv2>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ExecutionPayloadV2 {
/// Inner V1 payload
#[serde(flatten)]
pub payload_inner: ExecutionPayloadV1,
/// Array of [`Withdrawal`] enabled with V2
/// See <https://github.com/ethereum/execution-apis/blob/6709c2a795b707202e93c4f2867fa0bf2640a84f/src/engine/shanghai.md#executionpayloadv2>
pub withdrawals: Vec<Withdrawal>,
}
impl ExecutionPayloadV2 {
/// Returns the timestamp for the execution payload.
pub const fn timestamp(&self) -> u64 {
self.payload_inner.timestamp
}
}
#[cfg(feature = "ssz")]
impl ssz::Decode for ExecutionPayloadV2 {
fn is_ssz_fixed_len() -> bool {
false
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
let mut builder = ssz::SszDecoderBuilder::new(bytes);
builder.register_type::<B256>()?;
builder.register_type::<Address>()?;
builder.register_type::<B256>()?;
builder.register_type::<B256>()?;
builder.register_type::<Bloom>()?;
builder.register_type::<B256>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
builder.register_type::<Bytes>()?;
builder.register_type::<U256>()?;
builder.register_type::<B256>()?;
builder.register_type::<Vec<Bytes>>()?;
builder.register_type::<Vec<Withdrawal>>()?;
let mut decoder = builder.build()?;
Ok(Self {
payload_inner: ExecutionPayloadV1 {
parent_hash: decoder.decode_next()?,
fee_recipient: decoder.decode_next()?,
state_root: decoder.decode_next()?,
receipts_root: decoder.decode_next()?,
logs_bloom: decoder.decode_next()?,
prev_randao: decoder.decode_next()?,
block_number: decoder.decode_next()?,
gas_limit: decoder.decode_next()?,
gas_used: decoder.decode_next()?,
timestamp: decoder.decode_next()?,
extra_data: decoder.decode_next()?,
base_fee_per_gas: decoder.decode_next()?,
block_hash: decoder.decode_next()?,
transactions: decoder.decode_next()?,
},
withdrawals: decoder.decode_next()?,
})
}
}
#[cfg(feature = "ssz")]
impl ssz::Encode for ExecutionPayloadV2 {
fn is_ssz_fixed_len() -> bool {
false
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
let offset = <B256 as ssz::Encode>::ssz_fixed_len() * 5
+ <Address as ssz::Encode>::ssz_fixed_len()
+ <Bloom as ssz::Encode>::ssz_fixed_len()
+ <u64 as ssz::Encode>::ssz_fixed_len() * 4
+ <U256 as ssz::Encode>::ssz_fixed_len()
+ ssz::BYTES_PER_LENGTH_OFFSET * 3;
let mut encoder = ssz::SszEncoder::container(buf, offset);
encoder.append(&self.payload_inner.parent_hash);
encoder.append(&self.payload_inner.fee_recipient);
encoder.append(&self.payload_inner.state_root);
encoder.append(&self.payload_inner.receipts_root);
encoder.append(&self.payload_inner.logs_bloom);
encoder.append(&self.payload_inner.prev_randao);
encoder.append(&self.payload_inner.block_number);
encoder.append(&self.payload_inner.gas_limit);
encoder.append(&self.payload_inner.gas_used);
encoder.append(&self.payload_inner.timestamp);
encoder.append(&self.payload_inner.extra_data);
encoder.append(&self.payload_inner.base_fee_per_gas);
encoder.append(&self.payload_inner.block_hash);
encoder.append(&self.payload_inner.transactions);
encoder.append(&self.withdrawals);
encoder.finalize();
}
fn ssz_bytes_len(&self) -> usize {
<ExecutionPayloadV1 as ssz::Encode>::ssz_bytes_len(&self.payload_inner)
+ ssz::BYTES_PER_LENGTH_OFFSET
+ self.withdrawals.ssz_bytes_len()
}
}
/// This structure maps on the ExecutionPayloadV3 structure of the beacon chain spec.
///
/// See also: <https://github.com/ethereum/execution-apis/blob/6709c2a795b707202e93c4f2867fa0bf2640a84f/src/engine/shanghai.md#executionpayloadv2>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionPayloadV3 {
/// Inner V2 payload
#[serde(flatten)]
pub payload_inner: ExecutionPayloadV2,
/// Array of hex [`u64`] representing blob gas used, enabled with V3
/// See <https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/cancun.md#ExecutionPayloadV3>
#[serde(with = "alloy_serde::quantity")]
pub blob_gas_used: u64,
/// Array of hex[`u64`] representing excess blob gas, enabled with V3
/// See <https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/cancun.md#ExecutionPayloadV3>
#[serde(with = "alloy_serde::quantity")]
pub excess_blob_gas: u64,
}
impl ExecutionPayloadV3 {
/// Returns the withdrawals for the payload.
pub const fn withdrawals(&self) -> &Vec<Withdrawal> {
&self.payload_inner.withdrawals
}
/// Returns the timestamp for the payload.
pub const fn timestamp(&self) -> u64 {
self.payload_inner.payload_inner.timestamp
}
}
#[cfg(feature = "ssz")]
impl ssz::Decode for ExecutionPayloadV3 {
fn is_ssz_fixed_len() -> bool {
false
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
let mut builder = ssz::SszDecoderBuilder::new(bytes);
builder.register_type::<B256>()?;
builder.register_type::<Address>()?;
builder.register_type::<B256>()?;
builder.register_type::<B256>()?;
builder.register_type::<Bloom>()?;
builder.register_type::<B256>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
builder.register_type::<Bytes>()?;
builder.register_type::<U256>()?;
builder.register_type::<B256>()?;
builder.register_type::<Vec<Bytes>>()?;
builder.register_type::<Vec<Withdrawal>>()?;
builder.register_type::<u64>()?;
builder.register_type::<u64>()?;
let mut decoder = builder.build()?;
Ok(Self {
payload_inner: ExecutionPayloadV2 {
payload_inner: ExecutionPayloadV1 {
parent_hash: decoder.decode_next()?,
fee_recipient: decoder.decode_next()?,
state_root: decoder.decode_next()?,
receipts_root: decoder.decode_next()?,
logs_bloom: decoder.decode_next()?,
prev_randao: decoder.decode_next()?,
block_number: decoder.decode_next()?,
gas_limit: decoder.decode_next()?,
gas_used: decoder.decode_next()?,
timestamp: decoder.decode_next()?,
extra_data: decoder.decode_next()?,
base_fee_per_gas: decoder.decode_next()?,
block_hash: decoder.decode_next()?,
transactions: decoder.decode_next()?,
},
withdrawals: decoder.decode_next()?,
},
blob_gas_used: decoder.decode_next()?,
excess_blob_gas: decoder.decode_next()?,
})
}
}
#[cfg(feature = "ssz")]
impl ssz::Encode for ExecutionPayloadV3 {
fn is_ssz_fixed_len() -> bool {
false
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
let offset = <B256 as ssz::Encode>::ssz_fixed_len() * 5
+ <Address as ssz::Encode>::ssz_fixed_len()
+ <Bloom as ssz::Encode>::ssz_fixed_len()
+ <u64 as ssz::Encode>::ssz_fixed_len() * 6
+ <U256 as ssz::Encode>::ssz_fixed_len()
+ ssz::BYTES_PER_LENGTH_OFFSET * 3;
let mut encoder = ssz::SszEncoder::container(buf, offset);
encoder.append(&self.payload_inner.payload_inner.parent_hash);
encoder.append(&self.payload_inner.payload_inner.fee_recipient);
encoder.append(&self.payload_inner.payload_inner.state_root);
encoder.append(&self.payload_inner.payload_inner.receipts_root);
encoder.append(&self.payload_inner.payload_inner.logs_bloom);
encoder.append(&self.payload_inner.payload_inner.prev_randao);
encoder.append(&self.payload_inner.payload_inner.block_number);
encoder.append(&self.payload_inner.payload_inner.gas_limit);
encoder.append(&self.payload_inner.payload_inner.gas_used);
encoder.append(&self.payload_inner.payload_inner.timestamp);
encoder.append(&self.payload_inner.payload_inner.extra_data);
encoder.append(&self.payload_inner.payload_inner.base_fee_per_gas);
encoder.append(&self.payload_inner.payload_inner.block_hash);
encoder.append(&self.payload_inner.payload_inner.transactions);
encoder.append(&self.payload_inner.withdrawals);
encoder.append(&self.blob_gas_used);
encoder.append(&self.excess_blob_gas);
encoder.finalize();
}
fn ssz_bytes_len(&self) -> usize {
<ExecutionPayloadV2 as ssz::Encode>::ssz_bytes_len(&self.payload_inner)
+ <u64 as ssz::Encode>::ssz_fixed_len() * 2
}
}
/// This structure maps on the ExecutionPayloadV4 structure of the beacon chain spec.
///
/// See also: <https://github.com/ethereum/execution-apis/blob/main/src/engine/prague.md#ExecutionPayloadV4>
///
/// This structure has the syntax of ExecutionPayloadV3 and appends the new fields: depositRequests
/// and withdrawalRequests.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecutionPayloadV4 {
/// Inner V3 payload
#[serde(flatten)]
pub payload_inner: ExecutionPayloadV3,
/// Array of deposit requests.
///
/// This maps directly to the deposit requests defined in [EIP-6110](https://eips.ethereum.org/EIPS/eip-6110).
pub deposit_requests: Vec<DepositRequest>,
/// Array of execution layer triggerable withdrawal requests.
///
/// See [EIP-7002](https://eips.ethereum.org/EIPS/eip-7002).
pub withdrawal_requests: Vec<WithdrawalRequest>,
}
impl ExecutionPayloadV4 {
/// Returns the withdrawals for the payload.
pub const fn withdrawals(&self) -> &Vec<Withdrawal> {
self.payload_inner.withdrawals()
}
/// Returns the timestamp for the payload.
pub const fn timestamp(&self) -> u64 {
self.payload_inner.payload_inner.timestamp()
}
}
/// This includes all bundled blob related data of an executed payload.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobsBundleV1 {
/// All commitments in the bundle.
pub commitments: Vec<alloy_consensus::Bytes48>,
/// All proofs in the bundle.
pub proofs: Vec<alloy_consensus::Bytes48>,
/// All blobs in the bundle.
pub blobs: Vec<alloy_consensus::Blob>,
}
#[cfg(feature = "ssz")]
#[derive(ssz_derive::Encode, ssz_derive::Decode)]
struct BlobsBundleV1Ssz {
commitments: Vec<alloy_primitives::FixedBytes<48>>,
proofs: Vec<alloy_primitives::FixedBytes<48>>,
blobs: Vec<alloy_primitives::FixedBytes<{ alloy_eips::eip4844::BYTES_PER_BLOB }>>,
}
#[cfg(feature = "ssz")]
impl BlobsBundleV1Ssz {
const _ASSERT: [(); std::mem::size_of::<BlobsBundleV1>()] = [(); std::mem::size_of::<Self>()];
const fn wrap_ref(other: &BlobsBundleV1) -> &Self {
// SAFETY: Same repr and size
unsafe { &*(other as *const BlobsBundleV1 as *const Self) }
}
fn unwrap(self) -> BlobsBundleV1 {
// SAFETY: Same repr and size
unsafe { std::mem::transmute(self) }
}
}
#[cfg(feature = "ssz")]
impl ssz::Encode for BlobsBundleV1 {
fn is_ssz_fixed_len() -> bool {
<BlobsBundleV1Ssz as ssz::Encode>::is_ssz_fixed_len()
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
BlobsBundleV1Ssz::wrap_ref(self).ssz_append(buf)
}
fn ssz_fixed_len() -> usize {
<BlobsBundleV1Ssz as ssz::Encode>::ssz_fixed_len()
}
fn ssz_bytes_len(&self) -> usize {
BlobsBundleV1Ssz::wrap_ref(self).ssz_bytes_len()
}
fn as_ssz_bytes(&self) -> Vec<u8> {
BlobsBundleV1Ssz::wrap_ref(self).as_ssz_bytes()
}
}
#[cfg(feature = "ssz")]
impl ssz::Decode for BlobsBundleV1 {
fn is_ssz_fixed_len() -> bool {
<BlobsBundleV1Ssz as ssz::Decode>::is_ssz_fixed_len()
}
fn ssz_fixed_len() -> usize {
<BlobsBundleV1Ssz as ssz::Decode>::ssz_fixed_len()
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
BlobsBundleV1Ssz::from_ssz_bytes(bytes).map(BlobsBundleV1Ssz::unwrap)
}
}
impl BlobsBundleV1 {
/// Creates a new blob bundle from the given sidecars.
///
/// This folds the sidecar fields into single commit, proof, and blob vectors.
pub fn new(sidecars: impl IntoIterator<Item = BlobTransactionSidecar>) -> Self {
let (commitments, proofs, blobs) = sidecars.into_iter().fold(
(Vec::new(), Vec::new(), Vec::new()),
|(mut commitments, mut proofs, mut blobs), sidecar| {
commitments.extend(sidecar.commitments);
proofs.extend(sidecar.proofs);
blobs.extend(sidecar.blobs);
(commitments, proofs, blobs)
},
);
Self { commitments, proofs, blobs }
}
/// Take `len` blob data from the bundle.
///
/// # Panics
///
/// If len is more than the blobs bundle len.
pub fn take(&mut self, len: usize) -> (Vec<Bytes48>, Vec<Bytes48>, Vec<Blob>) {
(
self.commitments.drain(0..len).collect(),
self.proofs.drain(0..len).collect(),
self.blobs.drain(0..len).collect(),
)
}
/// Returns the sidecar from the bundle
///
/// # Panics
///
/// If len is more than the blobs bundle len.
pub fn pop_sidecar(&mut self, len: usize) -> BlobTransactionSidecar {
let (commitments, proofs, blobs) = self.take(len);
BlobTransactionSidecar { commitments, proofs, blobs }
}
}
impl From<Vec<BlobTransactionSidecar>> for BlobsBundleV1 {
fn from(sidecars: Vec<BlobTransactionSidecar>) -> Self {
Self::new(sidecars)
}
}
impl FromIterator<BlobTransactionSidecar> for BlobsBundleV1 {
fn from_iter<T: IntoIterator<Item = BlobTransactionSidecar>>(iter: T) -> Self {
Self::new(iter)
}
}
/// An execution payload, which can be either [ExecutionPayloadV1], [ExecutionPayloadV2], or
/// [ExecutionPayloadV3].
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum ExecutionPayload {
/// V1 payload
V1(ExecutionPayloadV1),
/// V2 payload
V2(ExecutionPayloadV2),
/// V3 payload
V3(ExecutionPayloadV3),
/// V4 payload
V4(ExecutionPayloadV4),
}
impl ExecutionPayload {
/// Returns a reference to the V1 payload.
pub const fn as_v1(&self) -> &ExecutionPayloadV1 {
match self {
Self::V1(payload) => payload,
Self::V2(payload) => &payload.payload_inner,
Self::V3(payload) => &payload.payload_inner.payload_inner,
Self::V4(payload) => &payload.payload_inner.payload_inner.payload_inner,
}
}
/// Returns a mutable reference to the V1 payload.
pub fn as_v1_mut(&mut self) -> &mut ExecutionPayloadV1 {
match self {
Self::V1(payload) => payload,
Self::V2(payload) => &mut payload.payload_inner,
Self::V3(payload) => &mut payload.payload_inner.payload_inner,
Self::V4(payload) => &mut payload.payload_inner.payload_inner.payload_inner,
}
}
/// Consumes the payload and returns the V1 payload.
pub fn into_v1(self) -> ExecutionPayloadV1 {
match self {
Self::V1(payload) => payload,
Self::V2(payload) => payload.payload_inner,
Self::V3(payload) => payload.payload_inner.payload_inner,
Self::V4(payload) => payload.payload_inner.payload_inner.payload_inner,
}
}
/// Returns a reference to the V2 payload, if any.
pub const fn as_v2(&self) -> Option<&ExecutionPayloadV2> {
match self {
Self::V1(_) => None,
Self::V2(payload) => Some(payload),
Self::V3(payload) => Some(&payload.payload_inner),
Self::V4(payload) => Some(&payload.payload_inner.payload_inner),
}
}
/// Returns a mutable reference to the V2 payload, if any.
pub fn as_v2_mut(&mut self) -> Option<&mut ExecutionPayloadV2> {
match self {
Self::V1(_) => None,
Self::V2(payload) => Some(payload),
Self::V3(payload) => Some(&mut payload.payload_inner),
Self::V4(payload) => Some(&mut payload.payload_inner.payload_inner),
}
}
/// Returns a reference to the V2 payload, if any.
pub const fn as_v3(&self) -> Option<&ExecutionPayloadV3> {
match self {
Self::V1(_) | Self::V2(_) => None,
Self::V3(payload) => Some(payload),
Self::V4(payload) => Some(&payload.payload_inner),
}
}
/// Returns a mutable reference to the V2 payload, if any.
pub fn as_v3_mut(&mut self) -> Option<&mut ExecutionPayloadV3> {
match self {
Self::V1(_) | Self::V2(_) => None,
Self::V3(payload) => Some(payload),
Self::V4(payload) => Some(&mut payload.payload_inner),
}
}
/// Returns a reference to the V4 payload, if any.
pub const fn as_v4(&self) -> Option<&ExecutionPayloadV4> {
match self {
Self::V1(_) | Self::V2(_) | Self::V3(_) => None,
Self::V4(payload) => Some(payload),
}
}
/// Returns a mutable reference to the V4 payload, if any.
pub fn as_v4_mut(&mut self) -> Option<&mut ExecutionPayloadV4> {
match self {
Self::V1(_) | Self::V2(_) | Self::V3(_) => None,
Self::V4(payload) => Some(payload),
}
}
/// Returns the withdrawals for the payload.
pub const fn withdrawals(&self) -> Option<&Vec<Withdrawal>> {
match self.as_v2() {
Some(payload) => Some(&payload.withdrawals),
None => None,
}
}
/// Returns the timestamp for the payload.
pub const fn timestamp(&self) -> u64 {
self.as_v1().timestamp
}
/// Returns the parent hash for the payload.
pub const fn parent_hash(&self) -> B256 {
self.as_v1().parent_hash
}
/// Returns the block hash for the payload.
pub const fn block_hash(&self) -> B256 {
self.as_v1().block_hash
}
/// Returns the block number for this payload.
pub const fn block_number(&self) -> u64 {
self.as_v1().block_number
}
/// Returns the prev randao for this payload.
pub const fn prev_randao(&self) -> B256 {
self.as_v1().prev_randao
}
}
impl From<ExecutionPayloadV1> for ExecutionPayload {
fn from(payload: ExecutionPayloadV1) -> Self {
Self::V1(payload)
}
}
impl From<ExecutionPayloadV2> for ExecutionPayload {
fn from(payload: ExecutionPayloadV2) -> Self {
Self::V2(payload)
}
}
impl From<ExecutionPayloadV3> for ExecutionPayload {
fn from(payload: ExecutionPayloadV3) -> Self {
Self::V3(payload)
}
}
impl From<ExecutionPayloadV4> for ExecutionPayload {
fn from(payload: ExecutionPayloadV4) -> Self {
Self::V4(payload)
}
}
// Deserializes untagged ExecutionPayload by trying each variant in falling order
impl<'de> Deserialize<'de> for ExecutionPayload {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum ExecutionPayloadDesc {
V4(ExecutionPayloadV4),
V3(ExecutionPayloadV3),
V2(ExecutionPayloadV2),
V1(ExecutionPayloadV1),
}
match ExecutionPayloadDesc::deserialize(deserializer)? {
ExecutionPayloadDesc::V4(payload) => Ok(Self::V4(payload)),
ExecutionPayloadDesc::V3(payload) => Ok(Self::V3(payload)),
ExecutionPayloadDesc::V2(payload) => Ok(Self::V2(payload)),
ExecutionPayloadDesc::V1(payload) => Ok(Self::V1(payload)),
}
}
}
/// Error that can occur when handling payloads.
#[derive(Debug, thiserror::Error)]
pub enum PayloadError {
/// Invalid payload extra data.
#[error("invalid payload extra data: {0}")]
ExtraData(Bytes),
/// Invalid payload base fee.
#[error("invalid payload base fee: {0}")]
BaseFee(U256),
/// Invalid payload blob gas used.
#[error("invalid payload blob gas used: {0}")]
BlobGasUsed(U256),
/// Invalid payload excess blob gas.
#[error("invalid payload excess blob gas: {0}")]
ExcessBlobGas(U256),
/// withdrawals present in pre-shanghai payload.
#[error("withdrawals present in pre-shanghai payload")]
PreShanghaiBlockWithWitdrawals,
/// withdrawals missing in post-shanghai payload.
#[error("withdrawals missing in post-shanghai payload")]
PostShanghaiBlockWithoutWitdrawals,
/// blob transactions present in pre-cancun payload.
#[error("blob transactions present in pre-cancun payload")]
PreCancunBlockWithBlobTransactions,
/// blob gas used present in pre-cancun payload.
#[error("blob gas used present in pre-cancun payload")]
PreCancunBlockWithBlobGasUsed,
/// excess blob gas present in pre-cancun payload.
#[error("excess blob gas present in pre-cancun payload")]
PreCancunBlockWithExcessBlobGas,
/// cancun fields present in pre-cancun payload.
#[error("cancun fields present in pre-cancun payload")]
PreCancunWithCancunFields,
/// blob transactions missing in post-cancun payload.
#[error("blob transactions missing in post-cancun payload")]
PostCancunBlockWithoutBlobTransactions,
/// blob gas used missing in post-cancun payload.
#[error("blob gas used missing in post-cancun payload")]
PostCancunBlockWithoutBlobGasUsed,
/// excess blob gas missing in post-cancun payload.
#[error("excess blob gas missing in post-cancun payload")]
PostCancunBlockWithoutExcessBlobGas,
/// cancun fields missing in post-cancun payload.
#[error("cancun fields missing in post-cancun payload")]
PostCancunWithoutCancunFields,
/// Invalid payload block hash.
#[error("block hash mismatch: want {consensus}, got {execution}")]
BlockHash {
/// The block hash computed from the payload.
execution: B256,
/// The block hash provided with the payload.
consensus: B256,
},
/// Expected blob versioned hashes do not match the given transactions.
#[error("expected blob versioned hashes do not match the given transactions")]
InvalidVersionedHashes,
/// Encountered decoding error.
#[error(transparent)]
Decode(#[from] alloy_rlp::Error),
}
impl PayloadError {
/// Returns `true` if the error is caused by a block hash mismatch.
#[inline]
pub const fn is_block_hash_mismatch(&self) -> bool {
matches!(self, Self::BlockHash { .. })
}
/// Returns `true` if the error is caused by invalid block hashes (Cancun).
#[inline]
pub const fn is_invalid_versioned_hashes(&self) -> bool {
matches!(self, Self::InvalidVersionedHashes)
}
}
/// This structure contains a body of an execution payload.
///
/// See also: <https://github.com/ethereum/execution-apis/blob/6452a6b194d7db269bf1dbd087a267251d3cc7f8/src/engine/shanghai.md#executionpayloadbodyv1>
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionPayloadBodyV1 {
/// Enveloped encoded transactions.
pub transactions: Vec<Bytes>,
/// All withdrawals in the block.
///
/// Will always be `None` if pre shanghai.
pub withdrawals: Option<Vec<Withdrawal>>,
}
/// This structure contains the attributes required to initiate a payload build process in the
/// context of an `engine_forkchoiceUpdated` call.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayloadAttributes {
/// Value for the `timestamp` field of the new payload
#[serde(with = "alloy_serde::quantity")]
pub timestamp: u64,
/// Value for the `prevRandao` field of the new payload
pub prev_randao: B256,
/// Suggested value for the `feeRecipient` field of the new payload
pub suggested_fee_recipient: Address,
/// Array of [`Withdrawal`] enabled with V2
/// See <https://github.com/ethereum/execution-apis/blob/6452a6b194d7db269bf1dbd087a267251d3cc7f8/src/engine/shanghai.md#payloadattributesv2>
#[serde(skip_serializing_if = "Option::is_none")]
pub withdrawals: Option<Vec<Withdrawal>>,
/// Root of the parent beacon block enabled with V3.
///
/// See also <https://github.com/ethereum/execution-apis/blob/main/src/engine/cancun.md#payloadattributesv3>
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_beacon_block_root: Option<B256>,
}
/// This structure contains the result of processing a payload or fork choice update.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayloadStatus {
/// The status of the payload.
#[serde(flatten)]
pub status: PayloadStatusEnum,
/// Hash of the most recent valid block in the branch defined by payload and its ancestors
pub latest_valid_hash: Option<B256>,
}
impl PayloadStatus {
/// Initializes a new payload status.
pub const fn new(status: PayloadStatusEnum, latest_valid_hash: Option<B256>) -> Self {
Self { status, latest_valid_hash }
}
/// Creates a new payload status from the given status.
pub const fn from_status(status: PayloadStatusEnum) -> Self {
Self { status, latest_valid_hash: None }
}
/// Sets the latest valid hash.
pub const fn with_latest_valid_hash(mut self, latest_valid_hash: B256) -> Self {
self.latest_valid_hash = Some(latest_valid_hash);
self
}
/// Sets the latest valid hash if it's not None.
pub const fn maybe_latest_valid_hash(mut self, latest_valid_hash: Option<B256>) -> Self {
self.latest_valid_hash = latest_valid_hash;
self
}
/// Returns true if the payload status is syncing.
pub const fn is_syncing(&self) -> bool {
self.status.is_syncing()
}
/// Returns true if the payload status is valid.
pub const fn is_valid(&self) -> bool {
self.status.is_valid()
}
/// Returns true if the payload status is invalid.
pub const fn is_invalid(&self) -> bool {
self.status.is_invalid()
}
}
impl fmt::Display for PayloadStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"PayloadStatus {{ status: {}, latestValidHash: {:?} }}",
self.status, self.latest_valid_hash
)
}
}
impl Serialize for PayloadStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("status", self.status.as_str())?;
map.serialize_entry("latestValidHash", &self.latest_valid_hash)?;
map.serialize_entry("validationError", &self.status.validation_error())?;
map.end()
}
}
impl From<PayloadError> for PayloadStatusEnum {
fn from(error: PayloadError) -> Self {
Self::Invalid { validation_error: error.to_string() }
}
}
/// Represents the status response of a payload.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayloadStatusEnum {
/// VALID is returned by the engine API in the following calls:
/// - newPayload: if the payload was already known or was just validated and executed
/// - forkchoiceUpdate: if the chain accepted the reorg (might ignore if it's stale)
Valid,
/// INVALID is returned by the engine API in the following calls:
/// - newPayload: if the payload failed to execute on top of the local chain
/// - forkchoiceUpdate: if the new head is unknown, pre-merge, or reorg to it fails
Invalid {
/// The error message for the invalid payload.
#[serde(rename = "validationError")]
validation_error: String,
},
/// SYNCING is returned by the engine API in the following calls:
/// - newPayload: if the payload was accepted on top of an active sync
/// - forkchoiceUpdate: if the new head was seen before, but not part of the chain
Syncing,
/// ACCEPTED is returned by the engine API in the following calls:
/// - newPayload: if the payload was accepted, but not processed (side chain)
Accepted,
}
impl PayloadStatusEnum {
/// Returns the string representation of the payload status.
pub const fn as_str(&self) -> &'static str {
match self {
Self::Valid => "VALID",
Self::Invalid { .. } => "INVALID",
Self::Syncing => "SYNCING",
Self::Accepted => "ACCEPTED",
}
}
/// Returns the validation error if the payload status is invalid.
pub fn validation_error(&self) -> Option<&str> {
match self {
Self::Invalid { validation_error } => Some(validation_error),
_ => None,
}
}
/// Returns true if the payload status is syncing.