-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmod.rs
More file actions
1228 lines (1064 loc) · 43.1 KB
/
mod.rs
File metadata and controls
1228 lines (1064 loc) · 43.1 KB
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
pub mod pol;
pub mod rpc;
pub mod txtype;
use alloy_consensus::{
EthereumTxEnvelope, EthereumTypedTransaction, SignableTransaction, Signed, Transaction,
TxEip4844, TxEip4844WithSidecar,
crypto::RecoveryError,
error::ValueError,
transaction::{Recovered, SignerRecoverable},
};
use alloy_eips::{
Decodable2718, Encodable2718, Typed2718, eip2718::Eip2718Result, eip2930::AccessList,
eip7002::SYSTEM_ADDRESS, eip7594::BlobTransactionSidecarVariant, eip7702::SignedAuthorization,
};
use alloy_network::TxSigner;
use alloy_primitives::{
Address, B256, Bytes, ChainId, Sealable, Sealed, Signature, TxHash, TxKind, U256,
bytes::BufMut, keccak256,
};
use alloy_rlp::{Decodable, Encodable};
use alloy_rpc_types_eth::TransactionRequest;
use reth::{providers::errors::db::DatabaseError, revm::context::TxEnv};
use reth_codecs::{
Compact,
alloy::transaction::{CompactEnvelope, Envelope, FromTxCompact, ToTxCompact},
};
use reth_db::table::{Compress, Decompress};
use reth_ethereum_primitives::TransactionSigned;
use reth_evm::{FromRecoveredTx, FromTxWithEncoded};
use reth_primitives_traits::{
InMemorySize, MaybeSerde, SignedTransaction, serde_bincode_compat::RlpBincode,
};
use reth_rpc_convert::{SignTxRequestError, SignableTxRequest};
use std::{hash::Hash, mem::size_of};
/// Transaction type identifier for Berachain POL transactions
pub const POL_TX_TYPE: u8 = 126; // 0x7E
pub const POL_TX_MAX_PRIORITY_FEE_PER_GAS: u128 = 0;
/// Error type for transaction conversion failures
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TxConversionError {
/// Cannot convert EIP-4844 consensus transaction to pooled format without sidecar
#[error("Cannot convert EIP-4844 consensus transaction to pooled format without sidecar")]
Eip4844MissingSidecar,
/// Cannot convert Berachain POL transaction to Ethereum format
#[error("Cannot convert Berachain POL transaction to Ethereum format")]
UnsupportedBerachainTransaction,
}
#[derive(Debug, Default, Clone, Hash, Eq, PartialEq, Compact)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct PoLTx {
pub chain_id: ChainId,
pub from: Address, // system address - serde skip as from is derived from recover_signer in RPC
pub to: Address,
pub nonce: u64, // MUST be block_number - 1 for POL transactions per specification
pub gas_limit: u64,
pub gas_price: u128, // gas_price to match Go struct
pub input: Bytes,
}
impl Transaction for PoLTx {
fn chain_id(&self) -> Option<ChainId> {
Some(self.chain_id)
}
fn nonce(&self) -> u64 {
self.nonce
}
fn gas_limit(&self) -> u64 {
self.gas_limit
}
fn gas_price(&self) -> Option<u128> {
Some(self.gas_price)
}
fn max_fee_per_gas(&self) -> u128 {
self.gas_price
}
fn max_priority_fee_per_gas(&self) -> Option<u128> {
Some(POL_TX_MAX_PRIORITY_FEE_PER_GAS)
}
fn max_fee_per_blob_gas(&self) -> Option<u128> {
None
}
fn priority_fee_or_price(&self) -> u128 {
self.gas_price
}
fn effective_gas_price(&self, _base_fee: Option<u64>) -> u128 {
self.gas_price
}
fn is_dynamic_fee(&self) -> bool {
false
}
fn kind(&self) -> TxKind {
TxKind::Call(self.to)
}
fn is_create(&self) -> bool {
false
}
fn value(&self) -> U256 {
U256::from(0)
}
fn input(&self) -> &Bytes {
&self.input
}
fn access_list(&self) -> Option<&AccessList> {
None
}
fn blob_versioned_hashes(&self) -> Option<&[B256]> {
None
}
fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
None
}
}
impl PoLTx {
fn tx_hash(&self) -> TxHash {
let mut buf = Vec::with_capacity(self.encode_2718_len());
self.encode_2718(&mut buf);
keccak256(&buf)
}
fn rlp_payload_length(&self) -> usize {
self.chain_id.length() +
self.from.length() +
self.to.length() +
self.nonce.length() +
self.gas_limit.length() +
self.gas_price.length() +
self.input.length()
}
fn rlp_encoded_length(&self) -> usize {
let payload_length = self.rlp_payload_length();
// Include RLP list header size
alloy_rlp::Header { list: true, payload_length }.length() + payload_length
}
fn rlp_encode(&self, out: &mut dyn BufMut) {
let payload_length = self.rlp_payload_length();
alloy_rlp::Header { list: true, payload_length }.encode(out);
self.chain_id.encode(out);
self.from.encode(out);
self.to.encode(out);
self.nonce.encode(out);
self.gas_limit.encode(out);
self.gas_price.encode(out);
self.input.encode(out);
}
fn rlp_decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let header = alloy_rlp::Header::decode(buf)?;
if !header.list {
return Err(alloy_rlp::Error::UnexpectedString);
}
let remaining = buf.len();
// Ensure payload is not shorter than indicated length
if header.payload_length > remaining {
return Err(alloy_rlp::Error::InputTooShort);
}
let decoded = Self {
chain_id: ChainId::decode(buf)?,
from: Address::decode(buf)?,
to: Address::decode(buf)?,
nonce: u64::decode(buf)?,
gas_limit: u64::decode(buf)?,
gas_price: u128::decode(buf)?,
input: Bytes::decode(buf)?,
};
// Ensure indicated length matches decoded length
if buf.len() + header.payload_length != remaining {
return Err(alloy_rlp::Error::UnexpectedLength);
};
Ok(decoded)
}
}
impl Encodable2718 for PoLTx {
fn encode_2718_len(&self) -> usize {
// 1 byte for transaction type + RLP encoded length
1 + self.rlp_encoded_length()
}
fn encode_2718(&self, out: &mut dyn BufMut) {
out.put_u8(self.ty());
self.rlp_encode(out);
}
}
impl Sealable for PoLTx {
fn hash_slow(&self) -> B256 {
self.tx_hash()
}
}
impl Decodable2718 for PoLTx {
fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self> {
if ty != u8::from(BerachainTxType::Berachain) {
return Err(alloy_eips::eip2718::Eip2718Error::UnexpectedType(ty));
}
Self::rlp_decode(buf).map_err(Into::into)
}
fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
Self::rlp_decode(buf).map_err(Into::into)
}
}
impl Typed2718 for PoLTx {
fn ty(&self) -> u8 {
u8::from(BerachainTxType::Berachain)
}
}
impl Encodable for PoLTx {
fn encode(&self, out: &mut dyn BufMut) {
// Use consistent RLP list format
self.rlp_encode(out);
}
}
impl Decodable for PoLTx {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
// Use consistent RLP list format
Self::rlp_decode(buf)
}
}
impl InMemorySize for PoLTx {
fn size(&self) -> usize {
size_of::<Self>() + self.input.len()
}
}
impl Compress for BerachainTxEnvelope {
type Compressed = Vec<u8>;
fn compress_to_buf<B: BufMut + AsMut<[u8]>>(&self, buf: &mut B) {
reth_codecs::Compact::to_compact(self, buf);
}
}
impl Decompress for BerachainTxEnvelope {
fn decompress(value: &[u8]) -> Result<Self, DatabaseError> {
let (tx, _) = reth_codecs::Compact::from_compact(value, value.len());
Ok(tx)
}
}
impl SignerRecoverable for PoLTx {
fn recover_signer(&self) -> Result<Address, RecoveryError> {
// POL transactions are always from the system address
Ok(SYSTEM_ADDRESS)
}
fn recover_signer_unchecked(&self) -> Result<Address, RecoveryError> {
Ok(SYSTEM_ADDRESS)
}
}
#[derive(Debug, Clone, alloy_consensus::TransactionEnvelope)]
#[envelope(tx_type_name = BerachainTxType)]
#[allow(clippy::large_enum_variant)]
pub enum BerachainTxEnvelope {
/// Existing Ethereum transactions
#[envelope(flatten)]
Ethereum(TransactionSigned),
/// Berachain PoL Transaction introduced in BRIP-0004
#[envelope(ty = 126)] // POL_TX_TYPE - derive macro requires literal
Berachain(Sealed<PoLTx>),
}
impl BerachainTxEnvelope {
/// Returns the [`TxEip4844`] variant if the transaction is an EIP-4844 transaction.
pub fn as_eip4844(&self) -> Option<Signed<TxEip4844>> {
match self {
Self::Ethereum(EthereumTxEnvelope::Eip4844(tx)) => Some(tx.clone()),
_ => None,
}
}
pub fn tx_type(&self) -> BerachainTxType {
match self {
// Unwrap is safe here as berachain supports all eth tx types.
Self::Ethereum(tx) => BerachainTxType::try_from(u8::from(tx.tx_type())).unwrap(),
Self::Berachain(_) => BerachainTxType::Berachain,
}
}
pub fn hash(&self) -> &TxHash {
self.tx_hash()
}
/// Converts from an EIP-4844 transaction to a [`EthereumTxEnvelope<TxEip4844WithSidecar<T>>`]
/// with the given sidecar.
///
/// Returns an `Err` containing the original [`EthereumTxEnvelope`] if the transaction is not an
/// EIP-4844 variant.
pub fn try_into_pooled_eip4844<T>(
self,
sidecar: T,
) -> Result<EthereumTxEnvelope<TxEip4844WithSidecar<T>>, ValueError<Self>> {
match self {
Self::Ethereum(tx) => match tx {
EthereumTxEnvelope::Eip4844(tx) => {
Ok(EthereumTxEnvelope::Eip4844(tx.map(|tx| tx.with_sidecar(sidecar))))
}
_ => Err(ValueError::new_static(Self::Ethereum(tx), "Expected 4844 transaction")),
},
Self::Berachain(tx) => {
Err(ValueError::new_static(Self::Berachain(tx), "Expected 4844 transaction"))
}
}
}
pub fn with_signer<T>(self, signer: Address) -> Recovered<Self> {
Recovered::new_unchecked(self, signer)
}
}
// STORAGE COMPATIBILITY: These CompactEnvelope implementations follow Reth's exact patterns
// to ensure database compatibility. Ethereum transactions use identical serialization to Reth.
// Only PoL transactions (type 126) use bera-reth specific encoding.
// See: reth/crates/storage/codecs/src/alloy/transaction/ethereum.rs for reference patterns
impl ToTxCompact for BerachainTxEnvelope {
fn to_tx_compact(&self, buf: &mut (impl BufMut + AsMut<[u8]>)) {
match self {
Self::Ethereum(tx) => {
// Delegate to TransactionSigned's implementation
tx.to_tx_compact(buf);
}
Self::Berachain(signed_tx) => {
// Serialize the PoL transaction directly
signed_tx.as_ref().to_compact(buf);
}
}
}
}
impl FromTxCompact for BerachainTxEnvelope {
type TxType = BerachainTxType;
fn from_tx_compact(buf: &[u8], tx_type: Self::TxType, signature: Signature) -> (Self, &[u8]) {
match tx_type {
BerachainTxType::Ethereum(eth_tx_type) => {
// Delegate to TransactionSigned's implementation
let (ethereum_tx, buf) =
TransactionSigned::from_tx_compact(buf, eth_tx_type, signature);
(Self::Ethereum(ethereum_tx), buf)
}
BerachainTxType::Berachain => {
// PoL transactions don't use real signatures - they use Sealed instead
let (pol_tx, buf) = PoLTx::from_compact(buf, buf.len());
let sealed = Sealed::new(pol_tx);
(Self::Berachain(sealed), buf)
}
}
}
}
impl Envelope for BerachainTxEnvelope {
fn signature(&self) -> &Signature {
match self {
Self::Ethereum(tx) => tx.signature(),
Self::Berachain(_) => {
// PoL transactions don't have real signatures - use a zero signature
static POL_SIGNATURE: Signature = Signature::new(U256::ZERO, U256::ZERO, false);
&POL_SIGNATURE
}
}
}
fn tx_type(&self) -> Self::TxType {
self.tx_type()
}
}
impl InMemorySize for BerachainTxEnvelope {
fn size(&self) -> usize {
match self {
Self::Ethereum(tx) => tx.size(),
Self::Berachain(tx) => tx.size(),
}
}
}
impl SignerRecoverable for BerachainTxEnvelope {
fn recover_signer(&self) -> Result<Address, RecoveryError> {
match self {
Self::Ethereum(tx) => tx.recover_signer(),
Self::Berachain(tx) => tx.recover_signer(),
}
}
fn recover_signer_unchecked(&self) -> Result<Address, RecoveryError> {
match self {
Self::Ethereum(tx) => tx.recover_signer_unchecked(),
Self::Berachain(tx) => tx.recover_signer_unchecked(),
}
}
}
impl SignedTransaction for BerachainTxEnvelope
where
Self: Clone + PartialEq + Eq + Decodable + Decodable2718 + MaybeSerde + InMemorySize,
{
fn tx_hash(&self) -> &TxHash {
match self {
Self::Ethereum(tx) => tx.hash(),
Self::Berachain(tx) => tx.hash_ref(),
}
}
}
impl RlpBincode for BerachainTxEnvelope {}
impl RlpBincode for PoLTx {}
impl reth_codecs::Compact for BerachainTxEnvelope {
fn to_compact<B>(&self, buf: &mut B) -> usize
where
B: BufMut + AsMut<[u8]>,
{
CompactEnvelope::to_compact(self, buf)
}
fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {
CompactEnvelope::from_compact(buf, len)
}
}
impl FromRecoveredTx<PoLTx> for TxEnv {
fn from_recovered_tx(tx: &PoLTx, caller: Address) -> Self {
Self {
tx_type: tx.ty(),
caller,
gas_limit: tx.gas_limit(),
gas_price: tx.gas_price().unwrap_or_default(),
kind: tx.kind(),
value: tx.value(),
data: tx.input.clone(),
nonce: tx.nonce(),
chain_id: None,
access_list: Default::default(),
gas_priority_fee: None,
blob_hashes: vec![],
max_fee_per_blob_gas: 0,
authorization_list: vec![],
}
}
}
impl FromRecoveredTx<BerachainTxEnvelope> for TxEnv {
fn from_recovered_tx(tx: &BerachainTxEnvelope, sender: Address) -> Self {
match tx {
BerachainTxEnvelope::Ethereum(ethereum_tx) => {
Self::from_recovered_tx(ethereum_tx, sender)
}
BerachainTxEnvelope::Berachain(berachain_tx) => {
Self::from_recovered_tx(berachain_tx.inner(), sender)
}
}
}
}
impl FromTxWithEncoded<BerachainTxEnvelope> for TxEnv {
fn from_encoded_tx(tx: &BerachainTxEnvelope, sender: Address, encoded: Bytes) -> Self {
match tx {
BerachainTxEnvelope::Ethereum(ethereum_tx) => {
TxEnv::from_encoded_tx(ethereum_tx, sender, encoded)
}
BerachainTxEnvelope::Berachain(berachain_tx) => TxEnv {
tx_type: u8::from(BerachainTxType::Berachain),
caller: SYSTEM_ADDRESS,
gas_limit: berachain_tx.gas_limit(),
gas_price: berachain_tx.gas_price().unwrap_or_default(),
kind: berachain_tx.kind(),
value: berachain_tx.value(),
data: berachain_tx.input().clone(),
nonce: berachain_tx.nonce(),
chain_id: berachain_tx.chain_id(),
access_list: AccessList(vec![]),
gas_priority_fee: berachain_tx.max_priority_fee_per_gas(),
blob_hashes: vec![],
max_fee_per_blob_gas: 0,
authorization_list: vec![],
},
}
}
}
impl From<TransactionSigned> for BerachainTxEnvelope {
fn from(tx_signed: TransactionSigned) -> Self {
// Convert to EthereumTxEnvelope first, then wrap in BerachainTxEnvelope
let ethereum_tx: EthereumTxEnvelope<TxEip4844> = tx_signed;
Self::Ethereum(ethereum_tx)
}
}
impl From<EthereumTxEnvelope<TxEip4844WithSidecar<BlobTransactionSidecarVariant>>>
for BerachainTxEnvelope
{
fn from(
ethereum_tx: EthereumTxEnvelope<TxEip4844WithSidecar<BlobTransactionSidecarVariant>>,
) -> Self {
Self::Ethereum(ethereum_tx.map_eip4844(|eip4844| eip4844.into()))
}
}
impl TryFrom<BerachainTxEnvelope>
for EthereumTxEnvelope<TxEip4844WithSidecar<BlobTransactionSidecarVariant>>
{
type Error = TxConversionError;
fn try_from(berachain_tx: BerachainTxEnvelope) -> Result<Self, Self::Error> {
match berachain_tx {
BerachainTxEnvelope::Ethereum(tx) => match tx {
EthereumTxEnvelope::Legacy(tx) => Ok(EthereumTxEnvelope::Legacy(tx)),
EthereumTxEnvelope::Eip2930(tx) => Ok(EthereumTxEnvelope::Eip2930(tx)),
EthereumTxEnvelope::Eip1559(tx) => Ok(EthereumTxEnvelope::Eip1559(tx)),
EthereumTxEnvelope::Eip4844(_tx) => {
// For consensus transactions without sidecars, we can't convert to pooled
// format This should only be called in contexts where we
// have the sidecar available
Err(TxConversionError::Eip4844MissingSidecar)
}
EthereumTxEnvelope::Eip7702(tx) => Ok(EthereumTxEnvelope::Eip7702(tx)),
},
BerachainTxEnvelope::Berachain(_) => {
Err(TxConversionError::UnsupportedBerachainTransaction)
}
}
}
}
impl SignableTxRequest<BerachainTxEnvelope> for TransactionRequest {
async fn try_build_and_sign(
self,
signer: impl TxSigner<Signature> + Send,
) -> Result<BerachainTxEnvelope, SignTxRequestError> {
let mut tx =
self.build_typed_tx().map_err(|_| SignTxRequestError::InvalidTransactionRequest)?;
let signature = signer.sign_transaction(&mut tx).await?;
let signed = match tx {
EthereumTypedTransaction::Legacy(tx) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Legacy(tx.into_signed(signature)))
}
EthereumTypedTransaction::Eip2930(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip2930(tx.into_signed(signature)),
),
EthereumTypedTransaction::Eip1559(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip1559(tx.into_signed(signature)),
),
EthereumTypedTransaction::Eip4844(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip4844(TxEip4844::from(tx).into_signed(signature)),
),
EthereumTypedTransaction::Eip7702(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip7702(tx.into_signed(signature)),
),
};
Ok(signed)
}
}
/// Converts signed Ethereum typed transactions to BerachainTxEnvelope for simulation API
impl From<Signed<EthereumTypedTransaction<alloy_consensus::TxEip4844Variant>>>
for BerachainTxEnvelope
{
fn from(
signed_tx: Signed<EthereumTypedTransaction<alloy_consensus::TxEip4844Variant>>,
) -> Self {
use alloy_consensus::EthereumTypedTransaction;
let (tx, signature, _hash) = signed_tx.into_parts();
match tx {
EthereumTypedTransaction::Legacy(tx) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Legacy(tx.into_signed(signature)))
}
EthereumTypedTransaction::Eip2930(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip2930(tx.into_signed(signature)),
),
EthereumTypedTransaction::Eip1559(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip1559(tx.into_signed(signature)),
),
EthereumTypedTransaction::Eip4844(tx) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip4844(
alloy_consensus::TxEip4844::from(tx).into_signed(signature),
))
}
EthereumTypedTransaction::Eip7702(tx) => BerachainTxEnvelope::Ethereum(
EthereumTxEnvelope::Eip7702(tx.into_signed(signature)),
),
}
}
}
#[cfg(test)]
mod compact_envelope_tests {
use super::*;
use alloy_consensus::{TxEip1559, TxEip2930, TxEip4844, TxEip7702, TxLegacy};
use alloy_eips::eip2930::AccessList;
use alloy_primitives::{Address, B256, Bytes, ChainId, TxKind, U256};
use reth_codecs::alloy::transaction::CompactEnvelope;
fn create_test_signature() -> Signature {
Signature::new(U256::from(1u64), U256::from(2u64), false)
}
fn create_test_pol_tx() -> PoLTx {
PoLTx {
chain_id: ChainId::from(80084u64),
from: Address::ZERO,
to: Address::from([1u8; 20]),
nonce: 42,
gas_limit: 21000,
gas_price: 1000000000u128,
input: Bytes::from("test data"),
}
}
#[test]
fn test_compact_envelope_roundtrip_pol_to_pol() {
let pol_tx = create_test_pol_tx();
let envelope = BerachainTxEnvelope::Berachain(Sealed::new(pol_tx.clone()));
// Encode using CompactEnvelope
let mut buf = Vec::new();
let len = CompactEnvelope::to_compact(&envelope, &mut buf);
// Decode using CompactEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
match decoded_envelope {
BerachainTxEnvelope::Berachain(decoded_pol) => {
assert_eq!(decoded_pol.as_ref(), &pol_tx);
}
_ => panic!("Expected Berachain PoL transaction"),
}
}
#[test]
fn test_compact_envelope_roundtrip_ethereum_to_berachain_legacy() {
let legacy_tx = TxLegacy {
chain_id: Some(ChainId::from(1u64)),
nonce: 10,
gas_price: 20_000_000_000u128,
gas_limit: 21_000,
to: TxKind::Call(Address::from([1u8; 20])),
value: U256::from(1000),
input: Bytes::from("hello"),
};
let signature = create_test_signature();
let signed_tx = Signed::new_unhashed(legacy_tx.clone(), signature);
// Create Ethereum envelope
let eth_envelope: EthereumTxEnvelope<TxEip4844> = EthereumTxEnvelope::Legacy(signed_tx);
// Encode using Ethereum CompactEnvelope
let mut buf = Vec::new();
let len = CompactEnvelope::to_compact(ð_envelope, &mut buf);
// Decode using Berachain CompactEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
match decoded_envelope {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Legacy(decoded_signed)) => {
assert_eq!(decoded_signed.tx(), &legacy_tx);
assert_eq!(decoded_signed.signature(), &signature);
}
_ => panic!("Expected Ethereum Legacy transaction"),
}
}
#[test]
fn test_compact_envelope_roundtrip_ethereum_to_berachain_eip1559() {
let eip1559_tx = TxEip1559 {
chain_id: ChainId::from(1u64),
nonce: 5,
gas_limit: 30_000,
max_fee_per_gas: 50_000_000_000u128,
max_priority_fee_per_gas: 2_000_000_000u128,
to: TxKind::Call(Address::from([2u8; 20])),
value: U256::from(2000),
access_list: AccessList::default(),
input: Bytes::from("eip1559 test"),
};
let signature = create_test_signature();
let signed_tx = Signed::new_unhashed(eip1559_tx.clone(), signature);
// Create Ethereum envelope
let eth_envelope: EthereumTxEnvelope<TxEip4844> = EthereumTxEnvelope::Eip1559(signed_tx);
// Encode using Ethereum CompactEnvelope
let mut buf = Vec::new();
let len = CompactEnvelope::to_compact(ð_envelope, &mut buf);
// Decode using Berachain CompactEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
match decoded_envelope {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip1559(decoded_signed)) => {
assert_eq!(decoded_signed.tx(), &eip1559_tx);
assert_eq!(decoded_signed.signature(), &signature);
}
_ => panic!("Expected Ethereum EIP-1559 transaction"),
}
}
#[test]
fn test_compact_envelope_roundtrip_ethereum_to_berachain_eip4844() {
let eip4844_tx = TxEip4844 {
chain_id: ChainId::from(1u64),
nonce: 7,
gas_limit: 50_000,
max_fee_per_gas: 100_000_000_000u128,
max_priority_fee_per_gas: 5_000_000_000u128,
to: Address::from([3u8; 20]),
value: U256::from(3000),
access_list: AccessList::default(),
blob_versioned_hashes: vec![B256::from([4u8; 32])],
max_fee_per_blob_gas: 10_000_000_000u128,
input: Bytes::from("eip4844 test"),
};
let signature = create_test_signature();
let signed_tx = Signed::new_unhashed(eip4844_tx.clone(), signature);
// Create Ethereum envelope
let eth_envelope: EthereumTxEnvelope<TxEip4844> = EthereumTxEnvelope::Eip4844(signed_tx);
// Encode using Ethereum CompactEnvelope
let mut buf = Vec::new();
let len = CompactEnvelope::to_compact(ð_envelope, &mut buf);
// Decode using Berachain CompactEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
match decoded_envelope {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip4844(decoded_signed)) => {
// TransactionSigned uses TxEip4844 directly
assert_eq!(decoded_signed.tx(), &eip4844_tx);
assert_eq!(decoded_signed.signature(), &signature);
}
_ => panic!("Expected Ethereum EIP-4844 transaction"),
}
}
#[test]
fn test_compact_roundtrip_ethereum_to_berachain() {
use reth_codecs::Compact;
// Test that Ethereum transactions compacted by Ethereum Compact
// can be decompacted by Berachain Compact for database compatibility
let test_cases = vec![
("Legacy", create_legacy_envelope()),
("EIP-2930", create_eip2930_envelope()),
("EIP-1559", create_eip1559_envelope()),
("EIP-4844", create_eip4844_envelope()),
("EIP-7702", create_eip7702_envelope()),
];
for (tx_name, eth_envelope) in test_cases {
// Compact using Ethereum envelope (simulates Reth storage)
let mut eth_buf = Vec::new();
let eth_len = Compact::to_compact(ð_envelope, &mut eth_buf);
// Convert to BerachainTxEnvelope and compact using our implementation
let berachain_envelope = match ð_envelope {
EthereumTxEnvelope::Legacy(signed) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Legacy(signed.clone()))
}
EthereumTxEnvelope::Eip2930(signed) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip2930(signed.clone()))
}
EthereumTxEnvelope::Eip1559(signed) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip1559(signed.clone()))
}
EthereumTxEnvelope::Eip4844(signed) => {
// Direct conversion since TransactionSigned uses TxEip4844
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip4844(signed.clone()))
}
EthereumTxEnvelope::Eip7702(signed) => {
BerachainTxEnvelope::Ethereum(EthereumTxEnvelope::Eip7702(signed.clone()))
}
};
let mut bera_buf = Vec::new();
let bera_len = Compact::to_compact(&berachain_envelope, &mut bera_buf);
// Verify the compacted content is identical
assert_eq!(
eth_buf, bera_buf,
"{tx_name}: Compacted content must be identical for database compatibility"
);
assert_eq!(eth_len, bera_len, "{tx_name}: Compacted length must be identical");
// Decompact using BerachainTxEnvelope (our implementation)
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(ð_buf, eth_len);
// Verify it decodes correctly as Ethereum transaction
match decoded_envelope {
BerachainTxEnvelope::Ethereum(decoded_tx) => {
// Verify transaction type matches
let original_type = match ð_envelope {
EthereumTxEnvelope::Legacy(_) => 0u8,
EthereumTxEnvelope::Eip2930(_) => 1u8,
EthereumTxEnvelope::Eip1559(_) => 2u8,
EthereumTxEnvelope::Eip4844(_) => 3u8,
EthereumTxEnvelope::Eip7702(_) => 4u8,
};
let decoded_type = match &decoded_tx {
EthereumTxEnvelope::Legacy(_) => 0u8,
EthereumTxEnvelope::Eip2930(_) => 1u8,
EthereumTxEnvelope::Eip1559(_) => 2u8,
EthereumTxEnvelope::Eip4844(_) => 3u8,
EthereumTxEnvelope::Eip7702(_) => 4u8,
};
assert_eq!(
original_type, decoded_type,
"{tx_name}: Transaction type should be preserved"
);
}
BerachainTxEnvelope::Berachain(_) => {
panic!("{tx_name}: Should not decode as Berachain PoL transaction");
}
}
}
}
#[test]
fn test_compact_roundtrip_pol_to_pol() {
use reth_codecs::Compact;
let pol_tx = create_test_pol_tx();
let berachain_envelope = BerachainTxEnvelope::Berachain(Sealed::new(pol_tx.clone()));
// Compact using BerachainTxEnvelope
let mut buf = Vec::new();
let len = Compact::to_compact(&berachain_envelope, &mut buf);
// Decompact using BerachainTxEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
// Verify the PoL transaction is preserved
match decoded_envelope {
BerachainTxEnvelope::Berachain(decoded_sealed) => {
assert_eq!(
decoded_sealed.as_ref(),
&pol_tx,
"PoL transaction data should be preserved"
);
}
_ => panic!("Should preserve Berachain PoL transaction format"),
}
}
#[test]
fn test_compact_envelope_roundtrip_all_ethereum_types() {
// Test that all Ethereum transaction types can be encoded by Ethereum
// and decoded by Berachain for full backwards compatibility
// Legacy
let legacy = create_legacy_envelope();
test_compact_envelope_ethereum_to_berachain_roundtrip(legacy, "Legacy");
// EIP-2930
let eip2930 = create_eip2930_envelope();
test_compact_envelope_ethereum_to_berachain_roundtrip(eip2930, "EIP-2930");
// EIP-1559
let eip1559 = create_eip1559_envelope();
test_compact_envelope_ethereum_to_berachain_roundtrip(eip1559, "EIP-1559");
// EIP-4844
let eip4844 = create_eip4844_envelope();
test_compact_envelope_ethereum_to_berachain_roundtrip(eip4844, "EIP-4844");
// EIP-7702
let eip7702 = create_eip7702_envelope();
test_compact_envelope_ethereum_to_berachain_roundtrip(eip7702, "EIP-7702");
}
fn test_compact_envelope_ethereum_to_berachain_roundtrip(
eth_envelope: EthereumTxEnvelope<TxEip4844>,
tx_name: &str,
) {
// Encode using Ethereum CompactEnvelope
let mut buf = Vec::new();
let len = CompactEnvelope::to_compact(ð_envelope, &mut buf);
// Decode using Berachain CompactEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
// Verify it's wrapped in Ethereum variant
match decoded_envelope {
BerachainTxEnvelope::Ethereum(_) => {
// Success - we can decode Ethereum transactions
}
BerachainTxEnvelope::Berachain(_) => {
panic!("{tx_name}: Should not decode as Berachain PoL transaction");
}
}
}
#[test]
fn test_compact_envelope_roundtrip_pol_to_pol_comprehensive() {
// Test that Berachain transactions can be encoded and decoded by Berachain
let pol_tx = create_test_pol_tx();
let berachain_envelope = BerachainTxEnvelope::Berachain(Sealed::new(pol_tx.clone()));
// Encode using Berachain CompactEnvelope
let mut buf = Vec::new();
let len = CompactEnvelope::to_compact(&berachain_envelope, &mut buf);
// Decode using Berachain CompactEnvelope
let (decoded_envelope, _) =
<BerachainTxEnvelope as CompactEnvelope>::from_compact(&buf, len);
match decoded_envelope {
BerachainTxEnvelope::Berachain(decoded_pol) => {
assert_eq!(decoded_pol.as_ref(), &pol_tx);
}
_ => panic!("Expected Berachain PoL transaction"),
}
}
#[test]
fn test_compact_envelope_storage_format_compatibility() {
// Test that our CompactEnvelope format matches what Reth would produce
// for Ethereum transactions (ensuring database compatibility)
let legacy_tx = create_legacy_envelope();
// Encode using Ethereum CompactEnvelope
let mut eth_buf = Vec::new();
let eth_len = CompactEnvelope::to_compact(&legacy_tx, &mut eth_buf);
// Encode the same transaction wrapped in BerachainTxEnvelope
let berachain_envelope = BerachainTxEnvelope::Ethereum(match legacy_tx.clone() {
EthereumTxEnvelope::Legacy(signed) => EthereumTxEnvelope::Legacy(signed),
_ => panic!("Expected legacy"),
});
let mut bera_buf = Vec::new();
let bera_len = CompactEnvelope::to_compact(&berachain_envelope, &mut bera_buf);
// The serialized format should be identical for storage compatibility
assert_eq!(eth_buf, bera_buf, "Storage format must be identical for compatibility");
assert_eq!(eth_len, bera_len, "Serialized length must be identical");
}
// Helper functions to create test envelopes
fn create_legacy_envelope() -> EthereumTxEnvelope<TxEip4844> {
let tx = TxLegacy {
chain_id: Some(ChainId::from(1u64)),
nonce: 1,
gas_price: 20_000_000_000u128,
gas_limit: 21_000,
to: TxKind::Call(Address::from([1u8; 20])),
value: U256::from(100),
input: Bytes::new(),
};
let signed = Signed::new_unhashed(tx, create_test_signature());
EthereumTxEnvelope::Legacy(signed)
}
fn create_eip2930_envelope() -> EthereumTxEnvelope<TxEip4844> {
let tx = TxEip2930 {
chain_id: ChainId::from(1u64),
nonce: 2,
gas_price: 25_000_000_000u128,