Skip to main content

anvil_core/eth/
block.rs

1use super::transaction::TransactionInfo;
2use crate::eth::transaction::MaybeImpersonatedTransaction;
3use alloy_consensus::{
4    BlockBody, EMPTY_OMMER_ROOT_HASH, Typed2718, proofs::ordered_trie_root_with_encoder,
5    transaction::RlpEcdsaEncodableTx,
6};
7use alloy_eips::eip2718::Encodable2718;
8use alloy_network::Network;
9use foundry_primitives::{FoundryHeader, FoundryTxEnvelope};
10
11/// Type alias for a block containing potentially impersonated transactions.
12pub type Block<T = FoundryTxEnvelope, H = FoundryHeader> =
13    alloy_consensus::Block<MaybeImpersonatedTransaction<T>, H>;
14
15/// Container type that gathers all block data, generic over a [`Network`].
16#[derive(Clone, Debug)]
17pub struct BlockInfo<N: Network> {
18    pub block: Block<N::TxEnvelope>,
19    pub transactions: Vec<TransactionInfo>,
20    pub receipts: Vec<N::ReceiptEnvelope>,
21}
22
23/// A transaction that can be encoded for inclusion in a block body.
24pub trait EncodableBlockTransaction: Encodable2718 {
25    /// Encodes the transaction in its canonical block-body form.
26    fn encode_2718_for_block(&self, out: &mut dyn bytes::BufMut);
27}
28
29impl EncodableBlockTransaction for FoundryTxEnvelope {
30    fn encode_2718_for_block(&self, out: &mut dyn bytes::BufMut) {
31        if let Self::Eip4844(tx) = self {
32            out.put_u8(self.ty());
33            tx.tx().tx().rlp_encode_signed(tx.signature(), out);
34        } else {
35            self.encode_2718(out);
36        }
37    }
38}
39
40/// Returns a block whose transactions use canonical block-body representations.
41pub fn canonical_block(mut block: Block) -> Block {
42    block.body.transactions = block
43        .body
44        .transactions
45        .into_iter()
46        .map(|tx| tx.map(FoundryTxEnvelope::into_canonical))
47        .collect();
48    block
49}
50
51/// Helper function to create a new block with Header and Anvil transactions, generic over the
52/// transaction envelope with a default of [`FoundryTxEnvelope`].
53///
54/// Note: if the `impersonate-tx` feature is enabled this will also accept
55/// `MaybeImpersonatedTransaction`.
56pub fn create_block<T, Tx>(
57    mut header: FoundryHeader,
58    transactions: impl IntoIterator<Item = T>,
59) -> Block<Tx>
60where
61    Tx: EncodableBlockTransaction,
62    T: Into<MaybeImpersonatedTransaction<Tx>>,
63{
64    let transactions: Vec<_> = transactions.into_iter().map(Into::into).collect();
65    let transactions_root = ordered_trie_root_with_encoder(&transactions, |tx, out| {
66        tx.as_ref().encode_2718_for_block(out)
67    });
68
69    header.set_transactions_root(transactions_root);
70    header.set_ommers_hash(EMPTY_OMMER_ROOT_HASH);
71
72    let body = BlockBody { transactions, ommers: Vec::new(), withdrawals: None };
73    Block::new(header, body)
74}
75
76#[cfg(test)]
77mod tests {
78
79    use alloy_consensus::{
80        BlobTransactionSidecar, BlobTransactionSidecarVariant, BlockHeader, Header,
81        SignableTransaction, TxEip4844, TxEip4844Variant, proofs::calculate_transaction_root,
82    };
83    use alloy_primitives::{
84        Address, B64, B256, Bloom, Signature, U256, address, b256,
85        hex::{self, FromHex},
86    };
87    use alloy_rlp::Decodable;
88
89    use super::*;
90
91    fn assert_blob_transaction_root(sidecar: BlobTransactionSidecarVariant) {
92        let tx = TxEip4844 {
93            chain_id: 1,
94            nonce: 0,
95            gas_limit: 21_000,
96            max_fee_per_gas: 1,
97            max_priority_fee_per_gas: 1,
98            to: Address::ZERO,
99            value: U256::ZERO,
100            access_list: Default::default(),
101            blob_versioned_hashes: vec![B256::ZERO],
102            max_fee_per_blob_gas: 1,
103            input: Default::default(),
104        };
105        let signature = Signature::new(U256::ONE, U256::ONE, false);
106        let canonical = FoundryTxEnvelope::Eip4844(
107            TxEip4844Variant::TxEip4844(tx.clone()).into_signed(signature),
108        );
109        let pooled = FoundryTxEnvelope::Eip4844(
110            TxEip4844Variant::TxEip4844WithSidecar(tx.with_sidecar(sidecar)).into_signed(signature),
111        );
112
113        let canonical_root = calculate_transaction_root(&[canonical]);
114        let pooled_root = calculate_transaction_root(std::slice::from_ref(&pooled));
115        let block = create_block(FoundryHeader::default(), [pooled]);
116
117        assert_ne!(canonical_root, pooled_root);
118        assert_eq!(block.header.transactions_root(), canonical_root);
119    }
120
121    #[test]
122    fn blob_transaction_root_uses_canonical_encoding() {
123        assert_blob_transaction_root(BlobTransactionSidecarVariant::Eip4844(
124            BlobTransactionSidecar::new(
125                vec![Default::default()],
126                vec![Default::default()],
127                vec![Default::default()],
128            ),
129        ));
130        assert_blob_transaction_root(BlobTransactionSidecarVariant::Eip7594(Default::default()));
131    }
132
133    #[test]
134    fn header_rlp_roundtrip() {
135        let mut header = Header {
136            parent_hash: Default::default(),
137            ommers_hash: Default::default(),
138            beneficiary: Default::default(),
139            state_root: Default::default(),
140            transactions_root: Default::default(),
141            receipts_root: Default::default(),
142            logs_bloom: Default::default(),
143            difficulty: Default::default(),
144            number: 124u64,
145            gas_limit: Default::default(),
146            gas_used: 1337u64,
147            timestamp: 0,
148            extra_data: Default::default(),
149            mix_hash: Default::default(),
150            nonce: B64::with_last_byte(99),
151            withdrawals_root: Default::default(),
152            blob_gas_used: Default::default(),
153            excess_blob_gas: Default::default(),
154            parent_beacon_block_root: Default::default(),
155            base_fee_per_gas: None,
156            requests_hash: None,
157            block_access_list_hash: None,
158            slot_number: None,
159        };
160
161        let encoded = alloy_rlp::encode(&header);
162        let decoded: Header = Header::decode(&mut encoded.as_ref()).unwrap();
163        assert_eq!(header, decoded);
164
165        header.base_fee_per_gas = Some(12345u64);
166
167        let encoded = alloy_rlp::encode(&header);
168        let decoded: Header = Header::decode(&mut encoded.as_ref()).unwrap();
169        assert_eq!(header, decoded);
170    }
171
172    #[test]
173    fn test_encode_block_header() {
174        use alloy_rlp::Encodable;
175
176        let expected = hex::decode("f901f9a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000940000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008208ae820d0582115c8215b3821a0a827788a00000000000000000000000000000000000000000000000000000000000000000880000000000000000").unwrap();
177        let mut data = vec![];
178        let header = Header {
179            parent_hash: B256::ZERO,
180            ommers_hash: B256::ZERO,
181            beneficiary: Address::ZERO,
182            state_root: B256::ZERO,
183            transactions_root: B256::ZERO,
184            receipts_root: B256::ZERO,
185            logs_bloom: Bloom::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(),
186            difficulty: U256::from(2222),
187            number: 0xd05u64,
188            gas_limit: 0x115cu64,
189            gas_used: 0x15b3u64,
190            timestamp: 0x1a0au64,
191            extra_data: hex::decode("7788").unwrap().into(),
192            mix_hash: B256::ZERO,
193            withdrawals_root: None,
194            blob_gas_used: None,
195            excess_blob_gas: None,
196            parent_beacon_block_root: None,
197            nonce: B64::ZERO,
198            base_fee_per_gas: None,
199            requests_hash: None,
200            block_access_list_hash: None,
201            slot_number: None,
202        };
203
204        header.encode(&mut data);
205        assert_eq!(hex::encode(&data), hex::encode(expected));
206        assert_eq!(header.length(), data.len());
207    }
208
209    #[test]
210    // Test vector from: https://eips.ethereum.org/EIPS/eip-2481
211    fn test_decode_block_header() {
212        let data = hex::decode("f901f9a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000940000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008208ae820d0582115c8215b3821a0a827788a00000000000000000000000000000000000000000000000000000000000000000880000000000000000").unwrap();
213        let expected = Header {
214            parent_hash: B256::ZERO,
215            ommers_hash: B256::ZERO,
216            beneficiary: Address::ZERO,
217            state_root: B256::ZERO,
218            transactions_root: B256::ZERO,
219            receipts_root: B256::ZERO,
220            logs_bloom: <[u8; 256]>::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap().into(),
221            difficulty: U256::from(2222),
222            number: 0xd05u64,
223            gas_limit: 0x115cu64,
224            gas_used: 0x15b3u64,
225            timestamp: 0x1a0au64,
226            extra_data: hex::decode("7788").unwrap().into(),
227            mix_hash: B256::ZERO,
228            nonce: B64::ZERO,
229            withdrawals_root: None,
230            blob_gas_used: None,
231            excess_blob_gas: None,
232            parent_beacon_block_root: None,
233            base_fee_per_gas: None,
234            requests_hash: None,
235            block_access_list_hash: None,
236            slot_number: None,
237        };
238        let header = Header::decode(&mut data.as_slice()).unwrap();
239        assert_eq!(header, expected);
240    }
241
242    #[test]
243    // Test vector from: https://github.com/ethereum/tests/blob/f47bbef4da376a49c8fc3166f09ab8a6d182f765/BlockchainTests/ValidBlocks/bcEIP1559/baseFee.json#L15-L36
244    fn test_eip1559_block_header_hash() {
245        let expected_hash =
246            b256!("0x6a251c7c3c5dca7b42407a3752ff48f3bbca1fab7f9868371d9918daf1988d1f");
247        let header = Header {
248            parent_hash: b256!("e0a94a7a3c9617401586b1a27025d2d9671332d22d540e0af72b069170380f2a"),
249            ommers_hash: b256!("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"),
250            beneficiary: address!("ba5e000000000000000000000000000000000000"),
251            state_root: b256!("ec3c94b18b8a1cff7d60f8d258ec723312932928626b4c9355eb4ab3568ec7f7"),
252            transactions_root: b256!("50f738580ed699f0469702c7ccc63ed2e51bc034be9479b7bff4e68dee84accf"),
253            receipts_root: b256!("29b0562f7140574dd0d50dee8a271b22e1a0a7b78fca58f7c60370d8317ba2a9"),
254            logs_bloom: Bloom::from_hex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(),
255            difficulty: U256::from(0x020000),
256            number: 1u64,
257            gas_limit: U256::from(0x016345785d8a0000u128).to::<u64>(),
258            gas_used: U256::from(0x015534).to::<u64>(),
259            timestamp: 0x079e,
260            extra_data: hex::decode("42").unwrap().into(),
261            mix_hash: B256::ZERO,
262            nonce: B64::ZERO,
263            base_fee_per_gas: Some(875),
264            withdrawals_root: None,
265            blob_gas_used: None,
266            excess_blob_gas: None,
267            parent_beacon_block_root: None,
268            requests_hash: None,
269            block_access_list_hash: None,
270            slot_number: None,
271        };
272        assert_eq!(header.hash_slow(), expected_hash);
273    }
274
275    #[test]
276    // Test vector from network
277    fn block_network_roundtrip() {
278        use alloy_rlp::Encodable;
279
280        let data = hex::decode("f9034df90348a0fbdbd8d2d0ac5f14bd5fa90e547fe6f1d15019c724f8e7b60972d381cd5d9cf8a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794c9577e7945db22e38fc060909f2278c7746b0f9ba05017cfa3b0247e35197215ae8d610265ffebc8edca8ea66d6567eb0adecda867a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018355bb7b871fffffffffffff808462bd0e1ab9014bf90148a00000000000000000000000000000000000000000000000000000000000000000f85494319fa8f1bc4e53410e92d10d918659b16540e60a945a573efb304d04c1224cd012313e827eca5dce5d94a9c831c5a268031176ebf5f3de5051e8cba0dbfe94c9577e7945db22e38fc060909f2278c7746b0f9b808400000000f8c9b841a6946f2d16f68338cbcbd8b117374ab421128ce422467088456bceba9d70c34106128e6d4564659cf6776c08a4186063c0a05f7cffd695c10cf26a6f301b67f800b8412b782100c18c35102dc0a37ece1a152544f04ad7dc1868d18a9570f744ace60870f822f53d35e89a2ea9709ccbf1f4a25ee5003944faa845d02dde0a41d5704601b841d53caebd6c8a82456e85c2806a9e08381f959a31fb94a77e58f00e38ad97b2e0355b8519ab2122662cbe022f2a4ef7ff16adc0b2d5dcd123181ec79705116db300a063746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365880000000000000000c0c0").unwrap();
281
282        let block = <Block>::decode(&mut data.as_slice()).unwrap();
283
284        // encode and check that it matches the original data
285        let mut encoded = Vec::new();
286        block.encode(&mut encoded);
287        assert_eq!(data, encoded);
288
289        // check that length of encoding is the same as the output of `length`
290        assert_eq!(block.length(), encoded.len());
291    }
292}