-
Notifications
You must be signed in to change notification settings - Fork 246
/
eip4844.rs
1081 lines (954 loc) · 43.3 KB
/
eip4844.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
mod builder;
pub use builder::{SidecarBuilder, SidecarCoder, SimpleCoder};
pub mod utils;
use crate::{SignableTransaction, Signed, Transaction, TxType};
use alloy_eips::{eip2930::AccessList, eip4844::DATA_GAS_PER_BLOB};
use alloy_primitives::{keccak256, Address, Bytes, ChainId, Signature, TxKind, B256, U256};
use alloy_rlp::{length_of_length, BufMut, Decodable, Encodable, Header};
use core::mem;
#[doc(inline)]
pub use alloy_eips::eip4844::BlobTransactionSidecar;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
pub use alloy_eips::eip4844::{Blob, Bytes48};
#[cfg(feature = "kzg")]
use c_kzg::{KzgCommitment, KzgProof, KzgSettings};
#[cfg(feature = "kzg")]
use std::ops::Deref;
/// An error that can occur when validating a [TxEip4844Variant].
#[derive(Debug, thiserror::Error)]
#[cfg(feature = "kzg")]
pub enum BlobTransactionValidationError {
/// Proof validation failed.
#[error("invalid KZG proof")]
InvalidProof,
/// An error returned by [`c_kzg`].
#[error("KZG error: {0:?}")]
KZGError(#[from] c_kzg::Error),
/// The inner transaction is not a blob transaction.
#[error("unable to verify proof for non blob transaction: {0}")]
NotBlobTransaction(u8),
/// Using a standalone [TxEip4844] instead of the [TxEip4844WithSidecar] variant, which
/// includes the sidecar for validation.
#[error("eip4844 tx variant without sidecar being used for verification. Please use the TxEip4844WithSidecar variant, which includes the sidecar")]
MissingSidecar,
/// The versioned hash is incorrect.
#[error("wrong versioned hash: have {have}, expected {expected}")]
WrongVersionedHash {
/// The versioned hash we got
have: B256,
/// The versioned hash we expected
expected: B256,
},
}
/// [EIP-4844 Blob Transaction](https://eips.ethereum.org/EIPS/eip-4844#blob-transaction)
///
/// A transaction with blob hashes and max blob fee.
/// It can either be a standalone transaction, mainly seen when retrieving historical transactions,
/// or a transaction with a sidecar, which is used when submitting a transaction to the network and
/// when receiving and sending transactions during the gossip stage.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum TxEip4844Variant {
/// A standalone transaction with blob hashes and max blob fee.
TxEip4844(TxEip4844),
/// A transaction with a sidecar, which contains the blob data, commitments, and proofs.
TxEip4844WithSidecar(TxEip4844WithSidecar),
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for TxEip4844Variant {
fn deserialize<D>(deserializer: D) -> Result<TxEip4844Variant, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(serde::Deserialize)]
struct TxEip4844SerdeHelper {
#[serde(flatten)]
tx: TxEip4844,
#[serde(flatten)]
sidecar: Option<BlobTransactionSidecar>,
}
let tx = TxEip4844SerdeHelper::deserialize(deserializer)?;
if let Some(sidecar) = tx.sidecar {
Ok(TxEip4844Variant::TxEip4844WithSidecar(TxEip4844WithSidecar::from_tx_and_sidecar(
tx.tx, sidecar,
)))
} else {
Ok(TxEip4844Variant::TxEip4844(tx.tx))
}
}
}
impl From<TxEip4844WithSidecar> for TxEip4844Variant {
fn from(tx: TxEip4844WithSidecar) -> Self {
TxEip4844Variant::TxEip4844WithSidecar(tx)
}
}
impl From<TxEip4844> for TxEip4844Variant {
fn from(tx: TxEip4844) -> Self {
TxEip4844Variant::TxEip4844(tx)
}
}
impl From<(TxEip4844, BlobTransactionSidecar)> for TxEip4844Variant {
fn from((tx, sidecar): (TxEip4844, BlobTransactionSidecar)) -> Self {
TxEip4844Variant::TxEip4844WithSidecar(TxEip4844WithSidecar::from_tx_and_sidecar(
tx, sidecar,
))
}
}
impl TxEip4844Variant {
/// Verifies that the transaction's blob data, commitments, and proofs are all valid.
///
/// See also [TxEip4844::validate_blob]
#[cfg(feature = "kzg")]
pub fn validate(
&self,
proof_settings: &KzgSettings,
) -> Result<(), BlobTransactionValidationError> {
match self {
TxEip4844Variant::TxEip4844(_) => Err(BlobTransactionValidationError::MissingSidecar),
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.validate_blob(proof_settings),
}
}
/// Get the transaction type.
pub const fn tx_type(&self) -> TxType {
TxType::Eip4844
}
/// Get access to the inner tx [TxEip4844].
pub const fn tx(&self) -> &TxEip4844 {
match self {
TxEip4844Variant::TxEip4844(tx) => tx,
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx(),
}
}
/// Outputs the length of the transaction's fields, without a RLP header.
#[doc(hidden)]
pub fn fields_len(&self) -> usize {
match self {
TxEip4844Variant::TxEip4844(tx) => tx.fields_len(),
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx().fields_len(),
}
}
/// Encodes the [TxEip4844Variant] fields as RLP, with a tx type. If `with_header` is `false`,
/// the following will be encoded:
/// `tx_type (0x03) || rlp([transaction_payload_body, blobs, commitments, proofs])`
///
/// If `with_header` is `true`, the following will be encoded:
/// `rlp(tx_type (0x03) || rlp([transaction_payload_body, blobs, commitments, proofs]))`
#[doc(hidden)]
pub fn encode_with_signature(
&self,
signature: &Signature,
out: &mut dyn BufMut,
with_header: bool,
) {
let payload_length = match self {
TxEip4844Variant::TxEip4844(tx) => tx.fields_len() + signature.rlp_vrs_len(),
TxEip4844Variant::TxEip4844WithSidecar(tx) => {
let payload_length = tx.tx().fields_len() + signature.rlp_vrs_len();
let inner_header = Header { list: true, payload_length };
inner_header.length() + payload_length + tx.sidecar().fields_len()
}
};
if with_header {
Header {
list: false,
payload_length: 1
+ Header { list: false, payload_length }.length()
+ payload_length,
}
.encode(out);
}
out.put_u8(self.tx_type() as u8);
match self {
TxEip4844Variant::TxEip4844(tx) => {
tx.encode_with_signature_fields(signature, out);
}
TxEip4844Variant::TxEip4844WithSidecar(tx) => {
tx.encode_with_signature_fields(signature, out);
}
}
}
/// Decodes the transaction from RLP bytes, including the signature.
///
/// This __does not__ expect the bytes to start with a transaction type byte or string
/// header.
///
/// This __does__ expect the bytes to start with a list header and include a signature.
#[doc(hidden)]
pub fn decode_signed_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Signed<Self>> {
let mut current_buf = *buf;
let _header = Header::decode(&mut current_buf)?;
// There are two possibilities when decoding a signed EIP-4844 transaction:
// If it's a historical transaction, it will only have the transaction fields, and no
// sidecar. If it's a transaction received during the gossip stage or sent through
// eth_sendRawTransaction, it will have the transaction fields and a sidecar.
//
// To disambiguate, we try to decode two list headers. If there is only one list header, we
// assume it's a historical transaction. If there are two, we know the transaction contains
// a sidecar.
let header = Header::decode(&mut current_buf)?;
if header.list {
let tx = TxEip4844WithSidecar::decode_signed_fields(buf)?;
let (tx, signature, hash) = tx.into_parts();
return Ok(Signed::new_unchecked(
TxEip4844Variant::TxEip4844WithSidecar(tx),
signature,
hash,
));
}
// Since there is not a second list header, this is a historical 4844 transaction without a
// sidecar.
let tx = TxEip4844::decode_signed_fields(buf)?;
let (tx, signature, hash) = tx.into_parts();
Ok(Signed::new_unchecked(TxEip4844Variant::TxEip4844(tx), signature, hash))
}
}
impl Transaction for TxEip4844Variant {
fn chain_id(&self) -> Option<ChainId> {
match self {
TxEip4844Variant::TxEip4844(tx) => Some(tx.chain_id),
TxEip4844Variant::TxEip4844WithSidecar(tx) => Some(tx.tx().chain_id),
}
}
fn gas_limit(&self) -> u128 {
match self {
TxEip4844Variant::TxEip4844(tx) => tx.gas_limit,
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx().gas_limit,
}
}
fn gas_price(&self) -> Option<u128> {
None
}
fn input(&self) -> &[u8] {
match self {
TxEip4844Variant::TxEip4844(tx) => tx.input.as_ref(),
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx().input.as_ref(),
}
}
fn nonce(&self) -> u64 {
match self {
TxEip4844Variant::TxEip4844(tx) => tx.nonce,
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx().nonce,
}
}
fn to(&self) -> TxKind {
match self {
TxEip4844Variant::TxEip4844(tx) => tx.to,
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx.to,
}
.into()
}
fn value(&self) -> U256 {
match self {
TxEip4844Variant::TxEip4844(tx) => tx.value,
TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx.value,
}
}
}
impl SignableTransaction<Signature> for TxEip4844Variant {
fn set_chain_id(&mut self, chain_id: ChainId) {
match self {
TxEip4844Variant::TxEip4844(ref mut inner) => {
inner.chain_id = chain_id;
}
TxEip4844Variant::TxEip4844WithSidecar(ref mut inner) => {
inner.tx.chain_id = chain_id;
}
}
}
fn payload_len_for_signature(&self) -> usize {
let payload_length = self.fields_len();
// 'transaction type byte length' + 'header length' + 'payload length'
1 + length_of_length(payload_length) + payload_length
}
fn into_signed(self, signature: Signature) -> Signed<Self> {
let payload_length = 1 + self.fields_len() + signature.rlp_vrs_len();
let mut buf = Vec::with_capacity(payload_length);
// we use the inner tx to encode the fields
self.tx().encode_with_signature(&signature, &mut buf, false);
let hash = keccak256(&buf);
// Drop any v chain id value to ensure the signature format is correct at the time of
// combination for an EIP-4844 transaction. V should indicate the y-parity of the
// signature.
Signed::new_unchecked(self, signature.with_parity_bool(), hash)
}
fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
// A signature for a [TxEip4844WithSidecar] is a signature over the [TxEip4844Variant]
// EIP-2718 payload fields:
// (BLOB_TX_TYPE ||
// rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value,
// data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))
self.tx().encode_for_signing(out);
}
}
/// [EIP-4844 Blob Transaction](https://eips.ethereum.org/EIPS/eip-4844#blob-transaction)
///
/// A transaction with blob hashes and max blob fee. It does not have the Blob sidecar.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TxEip4844 {
/// Added as EIP-pub 155: Simple replay attack protection
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u64_via_ruint"))]
pub chain_id: ChainId,
/// A scalar value equal to the number of transactions sent by the sender; formally Tn.
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u64_via_ruint"))]
pub nonce: u64,
/// A scalar value equal to the maximum
/// amount of gas that should be used in executing
/// this transaction. This is paid up-front, before any
/// computation is done and may not be increased
/// later; formally Tg.
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u128_via_ruint"))]
pub gas_limit: u128,
/// A scalar value equal to the maximum
/// amount of gas that should be used in executing
/// this transaction. This is paid up-front, before any
/// computation is done and may not be increased
/// later; formally Tg.
///
/// As ethereum circulation is around 120mil eth as of 2022 that is around
/// 120000000000000000000000000 wei we are safe to use u128 as its max number is:
/// 340282366920938463463374607431768211455
///
/// This is also known as `GasFeeCap`
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u128_via_ruint"))]
pub max_fee_per_gas: u128,
/// Max Priority fee that transaction is paying
///
/// As ethereum circulation is around 120mil eth as of 2022 that is around
/// 120000000000000000000000000 wei we are safe to use u128 as its max number is:
/// 340282366920938463463374607431768211455
///
/// This is also known as `GasTipCap`
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u128_via_ruint"))]
pub max_priority_fee_per_gas: u128,
/// The 160-bit address of the message call’s recipient.
pub to: Address,
/// A scalar value equal to the number of Wei to
/// be transferred to the message call’s recipient or,
/// in the case of contract creation, as an endowment
/// to the newly created account; formally Tv.
pub value: U256,
/// The accessList specifies a list of addresses and storage keys;
/// these addresses and storage keys are added into the `accessed_addresses`
/// and `accessed_storage_keys` global sets (introduced in EIP-2929).
/// A gas cost is charged, though at a discount relative to the cost of
/// accessing outside the list.
pub access_list: AccessList,
/// It contains a vector of fixed size hash(32 bytes)
pub blob_versioned_hashes: Vec<B256>,
/// Max fee per data gas
///
/// aka BlobFeeCap or blobGasFeeCap
#[cfg_attr(feature = "serde", serde(with = "alloy_serde::u128_via_ruint"))]
pub max_fee_per_blob_gas: u128,
/// Input has two uses depending if transaction is Create or Call (if `to` field is None or
/// Some). pub init: An unlimited size byte array specifying the
/// EVM-code for the account initialisation procedure CREATE,
/// data: An unlimited size byte array specifying the
/// input data of the message call, formally Td.
pub input: Bytes,
}
impl TxEip4844 {
/// Returns the effective gas price for the given `base_fee`.
pub const fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
match base_fee {
None => self.max_fee_per_gas,
Some(base_fee) => {
// if the tip is greater than the max priority fee per gas, set it to the max
// priority fee per gas + base fee
let tip = self.max_fee_per_gas.saturating_sub(base_fee as u128);
if tip > self.max_priority_fee_per_gas {
self.max_priority_fee_per_gas + base_fee as u128
} else {
// otherwise return the max fee per gas
self.max_fee_per_gas
}
}
}
}
/// Returns the total gas for all blobs in this transaction.
#[inline]
pub fn blob_gas(&self) -> u64 {
// SAFETY: we don't expect u64::MAX / DATA_GAS_PER_BLOB hashes in a single transaction
self.blob_versioned_hashes.len() as u64 * DATA_GAS_PER_BLOB
}
/// Verifies that the given blob data, commitments, and proofs are all valid for this
/// transaction.
///
/// Takes as input the [KzgSettings], which should contain the parameters derived from the
/// KZG trusted setup.
///
/// This ensures that the blob transaction payload has the same number of blob data elements,
/// commitments, and proofs. Each blob data element is verified against its commitment and
/// proof.
///
/// Returns [BlobTransactionValidationError::InvalidProof] if any blob KZG proof in the response
/// fails to verify, or if the versioned hashes in the transaction do not match the actual
/// commitment versioned hashes.
#[cfg(feature = "kzg")]
pub fn validate_blob(
&self,
sidecar: &BlobTransactionSidecar,
proof_settings: &KzgSettings,
) -> Result<(), BlobTransactionValidationError> {
// Ensure the versioned hashes and commitments have the same length.
if self.blob_versioned_hashes.len() != sidecar.commitments.len() {
return Err(c_kzg::Error::MismatchLength(format!(
"There are {} versioned commitment hashes and {} commitments",
self.blob_versioned_hashes.len(),
sidecar.commitments.len()
))
.into());
}
// calculate versioned hashes by zipping & iterating
for (versioned_hash, commitment) in
self.blob_versioned_hashes.iter().zip(sidecar.commitments.iter())
{
let commitment = KzgCommitment::from(*commitment.deref());
// calculate & verify versioned hash
let calculated_versioned_hash =
alloy_eips::eip4844::kzg_to_versioned_hash(commitment.as_slice());
if *versioned_hash != calculated_versioned_hash {
return Err(BlobTransactionValidationError::WrongVersionedHash {
have: *versioned_hash,
expected: calculated_versioned_hash,
});
}
}
// SAFETY: ALL types have the same size
let res = unsafe {
KzgProof::verify_blob_kzg_proof_batch(
// blobs
std::mem::transmute::<&[Blob], &[c_kzg::Blob]>(sidecar.blobs.as_slice()),
// commitments
std::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(
sidecar.commitments.as_slice(),
),
// proofs
std::mem::transmute::<&[Bytes48], &[c_kzg::Bytes48]>(sidecar.proofs.as_slice()),
proof_settings,
)
}
.map_err(BlobTransactionValidationError::KZGError)?;
if res {
Ok(())
} else {
Err(BlobTransactionValidationError::InvalidProof)
}
}
/// Decodes the inner [TxEip4844Variant] fields from RLP bytes.
///
/// NOTE: This assumes a RLP header has already been decoded, and _just_ decodes the following
/// RLP fields in the following order:
///
/// - `chain_id`
/// - `nonce`
/// - `max_priority_fee_per_gas`
/// - `max_fee_per_gas`
/// - `gas_limit`
/// - `to`
/// - `value`
/// - `data` (`input`)
/// - `access_list`
/// - `max_fee_per_blob_gas`
/// - `blob_versioned_hashes`
pub fn decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
Ok(Self {
chain_id: Decodable::decode(buf)?,
nonce: Decodable::decode(buf)?,
max_priority_fee_per_gas: Decodable::decode(buf)?,
max_fee_per_gas: Decodable::decode(buf)?,
gas_limit: Decodable::decode(buf)?,
to: Decodable::decode(buf)?,
value: Decodable::decode(buf)?,
input: Decodable::decode(buf)?,
access_list: Decodable::decode(buf)?,
max_fee_per_blob_gas: Decodable::decode(buf)?,
blob_versioned_hashes: Decodable::decode(buf)?,
})
}
/// Outputs the length of the transaction's fields, without a RLP header.
#[doc(hidden)]
pub fn fields_len(&self) -> usize {
let mut len = 0;
len += self.chain_id.length();
len += self.nonce.length();
len += self.gas_limit.length();
len += self.max_fee_per_gas.length();
len += self.max_priority_fee_per_gas.length();
len += self.to.length();
len += self.value.length();
len += self.access_list.length();
len += self.blob_versioned_hashes.length();
len += self.max_fee_per_blob_gas.length();
len += self.input.0.length();
len
}
/// Encodes only the transaction's fields into the desired buffer, without a RLP header.
pub(crate) fn encode_fields(&self, out: &mut dyn BufMut) {
self.chain_id.encode(out);
self.nonce.encode(out);
self.max_priority_fee_per_gas.encode(out);
self.max_fee_per_gas.encode(out);
self.gas_limit.encode(out);
self.to.encode(out);
self.value.encode(out);
self.input.0.encode(out);
self.access_list.encode(out);
self.max_fee_per_blob_gas.encode(out);
self.blob_versioned_hashes.encode(out);
}
/// Calculates a heuristic for the in-memory size of the [TxEip4844Variant] transaction.
#[inline]
pub fn size(&self) -> usize {
mem::size_of::<ChainId>() + // chain_id
mem::size_of::<u64>() + // nonce
mem::size_of::<u64>() + // gas_limit
mem::size_of::<u128>() + // max_fee_per_gas
mem::size_of::<u128>() + // max_priority_fee_per_gas
mem::size_of::<Address>() + // to
mem::size_of::<U256>() + // value
self.access_list.size() + // access_list
self.input.len() + // input
self.blob_versioned_hashes.capacity() * mem::size_of::<B256>() + // blob hashes size
mem::size_of::<u128>() // max_fee_per_data_gas
}
/// Returns what the encoded length should be, if the transaction were RLP encoded with the
/// given signature, depending on the value of `with_header`.
///
/// If `with_header` is `true`, the payload length will include the RLP header length.
/// If `with_header` is `false`, the payload length will not include the RLP header length.
pub(crate) fn encoded_len_with_signature(
&self,
signature: &Signature,
with_header: bool,
) -> usize {
// this counts the tx fields and signature fields
let payload_length = self.fields_len() + signature.rlp_vrs_len();
// this counts:
// * tx type byte
// * inner header length
// * inner payload length
let inner_payload_length =
1 + Header { list: true, payload_length }.length() + payload_length;
if with_header {
// header length plus length of the above, wrapped with a string header
Header { list: false, payload_length: inner_payload_length }.length()
+ inner_payload_length
} else {
inner_payload_length
}
}
/// Inner encoding function that is used for both rlp [`Encodable`] trait and for calculating
/// hash that for eip2718 does not require a rlp header
#[doc(hidden)]
pub fn encode_with_signature(
&self,
signature: &Signature,
out: &mut dyn BufMut,
with_header: bool,
) {
let payload_length = self.fields_len() + signature.rlp_vrs_len();
if with_header {
Header {
list: false,
payload_length: 1 + Header { list: true, payload_length }.length() + payload_length,
}
.encode(out);
}
out.put_u8(self.tx_type() as u8);
self.encode_with_signature_fields(signature, out);
}
/// Encodes the transaction from RLP bytes, including the signature. This __does not__ encode a
/// tx type byte or string header.
///
/// This __does__ encode a list header and include a signature.
pub(crate) fn encode_with_signature_fields(&self, signature: &Signature, out: &mut dyn BufMut) {
let payload_length = self.fields_len() + signature.rlp_vrs_len();
let header = Header { list: true, payload_length };
header.encode(out);
self.encode_fields(out);
signature.write_rlp_vrs(out);
}
/// Decodes the transaction from RLP bytes, including the signature.
///
/// This __does not__ expect the bytes to start with a transaction type byte or string
/// header.
///
/// This __does__ expect the bytes to start with a list header and include a signature.
#[doc(hidden)]
pub fn decode_signed_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Signed<Self>> {
let header = Header::decode(buf)?;
if !header.list {
return Err(alloy_rlp::Error::UnexpectedString);
}
// record original length so we can check encoding
let original_len = buf.len();
let tx = Self::decode_fields(buf)?;
let signature = Signature::decode_rlp_vrs(buf)?;
let signed = tx.into_signed(signature);
if buf.len() + header.payload_length != original_len {
return Err(alloy_rlp::Error::ListLengthMismatch {
expected: header.payload_length,
got: original_len - buf.len(),
});
}
Ok(signed)
}
/// Get transaction type
pub const fn tx_type(&self) -> TxType {
TxType::Eip4844
}
/// Encodes the EIP-4844 transaction in RLP for signing.
///
/// This encodes the transaction as:
/// `tx_type || rlp(chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to,
/// value, input, access_list, max_fee_per_blob_gas, blob_versioned_hashes)`
///
/// Note that there is no rlp header before the transaction type byte.
pub fn encode_for_signing(&self, out: &mut dyn BufMut) {
out.put_u8(self.tx_type() as u8);
Header { list: true, payload_length: self.fields_len() }.encode(out);
self.encode_fields(out);
}
/// Outputs the length of the signature RLP encoding for the transaction.
pub fn payload_len_for_signature(&self) -> usize {
let payload_length = self.fields_len();
// 'transaction type byte length' + 'header length' + 'payload length'
1 + Header { list: true, payload_length }.length() + payload_length
}
}
impl SignableTransaction<Signature> for TxEip4844 {
fn set_chain_id(&mut self, chain_id: ChainId) {
self.chain_id = chain_id;
}
fn payload_len_for_signature(&self) -> usize {
self.payload_len_for_signature()
}
fn into_signed(self, signature: Signature) -> Signed<Self> {
let mut buf = Vec::with_capacity(self.encoded_len_with_signature(&signature, false));
self.encode_with_signature(&signature, &mut buf, false);
let hash = keccak256(&buf);
// Drop any v chain id value to ensure the signature format is correct at the time of
// combination for an EIP-4844 transaction. V should indicate the y-parity of the
// signature.
Signed::new_unchecked(self, signature.with_parity_bool(), hash)
}
fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
self.encode_for_signing(out);
}
}
impl Transaction for TxEip4844 {
fn input(&self) -> &[u8] {
&self.input
}
fn to(&self) -> TxKind {
self.to.into()
}
fn value(&self) -> U256 {
self.value
}
fn chain_id(&self) -> Option<ChainId> {
Some(self.chain_id)
}
fn nonce(&self) -> u64 {
self.nonce
}
fn gas_limit(&self) -> u128 {
self.gas_limit
}
fn gas_price(&self) -> Option<u128> {
None
}
}
impl Encodable for TxEip4844 {
fn encode(&self, out: &mut dyn BufMut) {
Header { list: true, payload_length: self.fields_len() }.encode(out);
self.encode_fields(out);
}
fn length(&self) -> usize {
let payload_length = self.fields_len();
length_of_length(payload_length) + payload_length
}
}
impl Decodable for TxEip4844 {
fn decode(data: &mut &[u8]) -> alloy_rlp::Result<Self> {
let header = Header::decode(data)?;
let remaining_len = data.len();
if header.payload_length > remaining_len {
return Err(alloy_rlp::Error::InputTooShort);
}
Self::decode_fields(data)
}
}
/// [EIP-4844 Blob Transaction](https://eips.ethereum.org/EIPS/eip-4844#blob-transaction)
///
/// A transaction with blob hashes and max blob fee, which also includes the
/// [BlobTransactionSidecar]. This is the full type sent over the network as a raw transaction. It
/// wraps a [TxEip4844] to include the sidecar and the ability to decode it properly.
///
/// This is defined in [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844#networking) as an element
/// of a `PooledTransactions` response, and is also used as the format for sending raw transactions
/// through the network (eth_sendRawTransaction/eth_sendTransaction).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct TxEip4844WithSidecar {
/// The actual transaction.
#[cfg_attr(feature = "serde", serde(flatten))]
pub tx: TxEip4844,
/// The sidecar.
#[cfg_attr(feature = "serde", serde(flatten))]
pub sidecar: BlobTransactionSidecar,
}
impl TxEip4844WithSidecar {
/// Constructs a new [TxEip4844WithSidecar] from a [TxEip4844] and a [BlobTransactionSidecar].
pub const fn from_tx_and_sidecar(tx: TxEip4844, sidecar: BlobTransactionSidecar) -> Self {
Self { tx, sidecar }
}
/// Verifies that the transaction's blob data, commitments, and proofs are all valid.
///
/// See also [TxEip4844::validate_blob]
#[cfg(feature = "kzg")]
pub fn validate_blob(
&self,
proof_settings: &KzgSettings,
) -> Result<(), BlobTransactionValidationError> {
self.tx.validate_blob(&self.sidecar, proof_settings)
}
/// Get the transaction type.
pub const fn tx_type(&self) -> TxType {
self.tx.tx_type()
}
/// Get access to the inner tx [TxEip4844].
pub const fn tx(&self) -> &TxEip4844 {
&self.tx
}
/// Get access to the inner sidecar [BlobTransactionSidecar].
pub const fn sidecar(&self) -> &BlobTransactionSidecar {
&self.sidecar
}
/// Consumes the [TxEip4844WithSidecar] and returns the inner [TxEip4844].
pub fn into_tx(self) -> TxEip4844 {
self.tx
}
/// Consumes the [TxEip4844WithSidecar] and returns the inner sidecar [BlobTransactionSidecar].
pub fn into_sidecar(self) -> BlobTransactionSidecar {
self.sidecar
}
/// Consumes the [TxEip4844WithSidecar] and returns the inner [TxEip4844] and
/// [BlobTransactionSidecar].
pub fn into_parts(self) -> (TxEip4844, BlobTransactionSidecar) {
(self.tx, self.sidecar)
}
/// Encodes the transaction from RLP bytes, including the signature. This __does not__ encode a
/// tx type byte or string header.
///
/// This __does__ encode a list header and include a signature.
///
/// This encodes the following:
/// `rlp([tx_payload, blobs, commitments, proofs])`
///
/// where `tx_payload` is the RLP encoding of the [TxEip4844] transaction fields:
/// `rlp([chain_id, nonce, max_priority_fee_per_gas, ..., v, r, s])`
pub fn encode_with_signature_fields(&self, signature: &Signature, out: &mut dyn BufMut) {
let inner_payload_length = self.tx.fields_len() + signature.rlp_vrs_len();
let inner_header = Header { list: true, payload_length: inner_payload_length };
let outer_payload_length =
inner_header.length() + inner_payload_length + self.sidecar.fields_len();
let outer_header = Header { list: true, payload_length: outer_payload_length };
// write the two headers
outer_header.encode(out);
inner_header.encode(out);
// now write the fields
self.tx.encode_fields(out);
signature.write_rlp_vrs(out);
self.sidecar.encode(out);
}
/// Decodes the transaction from RLP bytes, including the signature.
///
/// This __does not__ expect the bytes to start with a transaction type byte or string
/// header.
///
/// This __does__ expect the bytes to start with a list header and include a signature.
///
/// This is the inverse of [TxEip4844WithSidecar::encode_with_signature_fields].
#[doc(hidden)]
pub fn decode_signed_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Signed<Self>> {
let header = Header::decode(buf)?;
if !header.list {
return Err(alloy_rlp::Error::UnexpectedString);
}
// record original length so we can check encoding
let original_len = buf.len();
// decode the inner tx
let inner_tx = TxEip4844::decode_signed_fields(buf)?;
// decode the sidecar
let sidecar = BlobTransactionSidecar::decode(buf)?;
if buf.len() + header.payload_length != original_len {
return Err(alloy_rlp::Error::ListLengthMismatch {
expected: header.payload_length,
got: original_len - buf.len(),
});
}
let (tx, signature, hash) = inner_tx.into_parts();
// create unchecked signed tx because these checks should have happened during construction
// of `Signed<TxEip4844>` in `TxEip4844::decode_signed_fields`
Ok(Signed::new_unchecked(
TxEip4844WithSidecar::from_tx_and_sidecar(tx, sidecar),
signature,
hash,
))
}
}
impl SignableTransaction<Signature> for TxEip4844WithSidecar {
fn set_chain_id(&mut self, chain_id: ChainId) {
self.tx.chain_id = chain_id;
}
fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
// A signature for a [TxEip4844WithSidecar] is a signature over the [TxEip4844] EIP-2718
// payload fields:
// (BLOB_TX_TYPE ||
// rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value,
// data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))
self.tx.encode_for_signing(out);
}
fn into_signed(self, signature: Signature) -> Signed<Self, Signature> {
let mut buf = Vec::with_capacity(self.tx.encoded_len_with_signature(&signature, false));
// The sidecar is NOT included in the signed payload, only the transaction fields and the
// type byte. Include the type byte.
//
// Include the transaction fields, making sure to __not__ use the sidecar, and __not__
// encode a header.
self.tx.encode_with_signature(&signature, &mut buf, false);
let hash = keccak256(&buf);
// Drop any v chain id value to ensure the signature format is correct at the time of
// combination for an EIP-4844 transaction. V should indicate the y-parity of the
// signature.
Signed::new_unchecked(self, signature.with_parity_bool(), hash)
}
fn payload_len_for_signature(&self) -> usize {
// The payload length is the length of the `transaction_payload_body` list.
// The sidecar is NOT included.
self.tx.payload_len_for_signature()
}
}
impl Transaction for TxEip4844WithSidecar {
fn chain_id(&self) -> Option<ChainId> {
self.tx.chain_id()
}
fn gas_limit(&self) -> u128 {
self.tx.gas_limit()
}
fn gas_price(&self) -> Option<u128> {
self.tx.gas_price()
}
fn nonce(&self) -> u64 {
self.tx.nonce()
}
fn to(&self) -> TxKind {
self.tx.to()
}
fn value(&self) -> U256 {
self.tx.value()
}
fn input(&self) -> &[u8] {
self.tx.input()
}
}
#[cfg(test)]
mod tests {
use super::{BlobTransactionSidecar, TxEip4844, TxEip4844WithSidecar};
use crate::{SignableTransaction, TxEip4844Variant, TxEnvelope};
use alloy_eips::{
eip2930::AccessList,
eip4844::{Blob, Bytes48},
};
use alloy_primitives::{address, b256, bytes, Signature, U256};
use alloy_rlp::{Decodable, Encodable};
#[test]
fn different_sidecar_same_hash() {
// this should make sure that the hash calculated for the `into_signed` conversion does not
// change if the sidecar is different
let tx = TxEip4844 {
chain_id: 1,
nonce: 1,
max_priority_fee_per_gas: 1,
max_fee_per_gas: 1,
gas_limit: 1,
to: Default::default(),
value: U256::from(1),
access_list: Default::default(),