Skip to main content

reth_rpc/eth/helpers/
transaction.rs

1//! Contains RPC handler implementations specific to transactions
2
3use std::time::Duration;
4
5use crate::EthApi;
6use alloy_consensus::BlobTransactionValidationError;
7use alloy_eips::{eip7594::BlobTransactionSidecarVariant, BlockId, Typed2718};
8use alloy_primitives::{hex, B256};
9use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
10use reth_primitives_traits::{AlloyBlockHeader, WithEncoded};
11use reth_rpc_convert::RpcConvert;
12use reth_rpc_eth_api::{
13    helpers::{spec::SignersForRpc, EthTransactions, LoadTransaction},
14    FromEvmError, RpcNodeCore,
15};
16use reth_rpc_eth_types::{error::RpcPoolError, EthApiError};
17use reth_storage_api::BlockReaderIdExt;
18use reth_transaction_pool::{
19    error::Eip4844PoolTransactionError, AddedTransactionOutcome, EthBlobTransactionSidecar,
20    EthPoolTransaction, PoolTransaction, PoolTx,
21};
22
23impl<N, Rpc> EthTransactions for EthApi<N, Rpc>
24where
25    N: RpcNodeCore,
26    EthApiError: FromEvmError<N::Evm>,
27    Rpc: RpcConvert<Primitives = N::Primitives, Error = EthApiError>,
28{
29    #[inline]
30    fn signers(&self) -> &SignersForRpc<Self::Provider, Self::NetworkTypes> {
31        self.inner.signers()
32    }
33
34    #[inline]
35    fn send_raw_transaction_sync_timeout(&self) -> Duration {
36        self.inner.send_raw_transaction_sync_timeout()
37    }
38
39    async fn send_pool_transaction(
40        &self,
41        origin: reth_transaction_pool::TransactionOrigin,
42        tx: WithEncoded<PoolTx<Self::Pool>>,
43    ) -> Result<B256, Self::Error> {
44        let (tx, mut pool_transaction) = tx.split();
45
46        // Optionally convert legacy blob sidecars to EIP-7594 format when Osaka is active
47        // This is opt-in via --rpc.force-blob-sidecar-upcasting
48        if self.inner.force_blob_sidecar_upcasting() && pool_transaction.is_eip4844() {
49            let EthBlobTransactionSidecar::Present(sidecar) = pool_transaction.take_blob() else {
50                return Err(EthApiError::PoolError(RpcPoolError::Eip4844(
51                    Eip4844PoolTransactionError::MissingEip4844BlobSidecar,
52                )));
53            };
54            let sidecar = sidecar.into_sidecar();
55
56            let sidecar = match sidecar {
57                BlobTransactionSidecarVariant::Eip4844(sidecar) => {
58                    let latest = self
59                        .provider()
60                        .latest_header()?
61                        .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?;
62                    // Convert to EIP-7594 if next block is Osaka
63                    if self
64                        .provider()
65                        .chain_spec()
66                        .is_osaka_active_at_timestamp(latest.timestamp().saturating_add(12))
67                    {
68                        BlobTransactionSidecarVariant::Eip7594(
69                            self.blob_sidecar_converter().convert(sidecar).await.ok_or_else(
70                                || {
71                                    RpcPoolError::Eip4844(
72                                        Eip4844PoolTransactionError::InvalidEip4844Blob(
73                                            BlobTransactionValidationError::InvalidProof,
74                                        ),
75                                    )
76                                },
77                            )?,
78                        )
79                    } else {
80                        BlobTransactionSidecarVariant::Eip4844(sidecar)
81                    }
82                }
83                sidecar => sidecar,
84            };
85
86            pool_transaction =
87                EthPoolTransaction::try_from_eip4844(pool_transaction.into_consensus(), sidecar)
88                    .ok_or_else(|| {
89                        RpcPoolError::Eip4844(
90                            Eip4844PoolTransactionError::MissingEip4844BlobSidecar,
91                        )
92                    })?;
93        }
94
95        // forward the transaction to the specific endpoint if configured.
96        if let Some(client) = self.raw_tx_forwarder() {
97            tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to forwarder");
98            let rlp_hex = hex::encode_prefixed(&tx);
99
100            // broadcast raw transaction to subscribers if there is any.
101            self.broadcast_raw_transaction(tx);
102
103            let hash =
104                client.request("eth_sendRawTransaction", (rlp_hex,)).await.inspect_err(|err| {
105                    tracing::debug!(target: "rpc::eth", %err, hash=% *pool_transaction.hash(), "failed to forward raw transaction");
106                }).map_err(EthApiError::other)?;
107
108            // Retain tx in local tx pool after forwarding, for local RPC usage.
109            let _ = self.inner.add_pool_transaction(origin, pool_transaction).await;
110
111            return Ok(hash);
112        }
113
114        // broadcast raw transaction to subscribers if there is any.
115        self.broadcast_raw_transaction(tx);
116
117        let AddedTransactionOutcome { hash, .. } =
118            self.inner.add_pool_transaction(origin, pool_transaction).await?;
119
120        Ok(hash)
121    }
122}
123
124impl<N, Rpc> LoadTransaction for EthApi<N, Rpc>
125where
126    N: RpcNodeCore,
127    EthApiError: FromEvmError<N::Evm>,
128    Rpc: RpcConvert<Primitives = N::Primitives, Error = EthApiError>,
129{
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::eth::helpers::types::EthRpcConverter;
136    use alloy_consensus::{
137        BlobTransactionSidecar, Block, Header, SidecarBuilder, SimpleCoder, Transaction,
138    };
139    use alloy_primitives::{map::AddressMap, Address, Bytes, U256};
140    use alloy_rpc_types_eth::request::TransactionRequest;
141    use reth_chainspec::{ChainSpec, ChainSpecBuilder};
142    use reth_evm_ethereum::EthEvmConfig;
143    use reth_network_api::noop::NoopNetwork;
144    use reth_provider::{
145        test_utils::{ExtendedAccount, MockEthProvider},
146        ChainSpecProvider,
147    };
148    use reth_rpc_eth_api::node::RpcNodeCoreAdapter;
149    use reth_transaction_pool::{
150        test_utils::{testing_pool, TestPool},
151        TransactionOrigin, TransactionPool,
152    };
153
154    fn mock_eth_api(
155        accounts: AddressMap<ExtendedAccount>,
156    ) -> EthApi<
157        RpcNodeCoreAdapter<MockEthProvider, TestPool, NoopNetwork, EthEvmConfig>,
158        EthRpcConverter<ChainSpec>,
159    > {
160        mock_eth_api_with_sync_timeout(accounts, Duration::from_secs(30))
161    }
162
163    fn mock_eth_api_with_sync_timeout(
164        accounts: AddressMap<ExtendedAccount>,
165        send_raw_transaction_sync_timeout: Duration,
166    ) -> EthApi<
167        RpcNodeCoreAdapter<MockEthProvider, TestPool, NoopNetwork, EthEvmConfig>,
168        EthRpcConverter<ChainSpec>,
169    > {
170        let mock_provider = MockEthProvider::default()
171            .with_chain_spec(ChainSpecBuilder::mainnet().cancun_activated().build());
172        mock_provider.extend_accounts(accounts);
173
174        let evm_config = EthEvmConfig::new(mock_provider.chain_spec());
175        let pool = testing_pool();
176
177        let genesis_header = Header {
178            number: 0,
179            gas_limit: 30_000_000,
180            timestamp: 1,
181            excess_blob_gas: Some(0),
182            base_fee_per_gas: Some(1000000000),
183            blob_gas_used: Some(0),
184            ..Default::default()
185        };
186
187        let genesis_hash = B256::ZERO;
188        mock_provider.add_block(genesis_hash, Block::new(genesis_header, Default::default()));
189
190        EthApi::builder(mock_provider, pool, NoopNetwork::default(), evm_config)
191            .send_raw_transaction_sync_timeout(send_raw_transaction_sync_timeout)
192            .build()
193    }
194
195    fn raw_transfer_tx() -> Bytes {
196        // https://etherscan.io/tx/0xa694b71e6c128a2ed8e2e0f6770bddbe52e3bb8f10e8472f9a79ab81497a8b5d
197        Bytes::from(hex!(
198            "02f871018303579880850555633d1b82520894eee27662c2b8eba3cd936a23f039f3189633e4c887ad591c62bdaeb180c080a07ea72c68abfb8fca1bd964f0f99132ed9280261bdca3e549546c0205e800f7d0a05b4ef3039e9c9b9babc179a1878fb825b5aaf5aed2fa8744854150157b08d6f3"
199        ))
200    }
201
202    #[tokio::test]
203    async fn send_raw_transaction() {
204        let eth_api = mock_eth_api(Default::default());
205        let pool = eth_api.pool();
206
207        let tx_1 = raw_transfer_tx();
208
209        let tx_1_result = eth_api.send_raw_transaction(tx_1).await.unwrap();
210        assert_eq!(
211            pool.len(),
212            1,
213            "expect 1 transaction in the pool, but pool size is {}",
214            pool.len()
215        );
216
217        // https://etherscan.io/tx/0x48816c2f32c29d152b0d86ff706f39869e6c1f01dc2fe59a3c1f9ecf39384694
218        let tx_2 = Bytes::from(hex!(
219            "02f9043c018202b7843b9aca00850c807d37a08304d21d94ef1c6e67703c7bd7107eed8303fbe6ec2554bf6b881bc16d674ec80000b903c43593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000063e2d99f00000000000000000000000000000000000000000000000000000000000000030b000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001e0000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000001bc16d674ec80000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000065717fe021ea67801d1088cc80099004b05b64600000000000000000000000000000000000000000000000001bc16d674ec80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002bc02aaa39b223fe8d0a0e5c4f27ead9083c756cc20001f4a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e95fd5965fd1f1a6f0d4600000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48000000000000000000000000428dca9537116148616a5a3e44035af17238fe9dc080a0c6ec1e41f5c0b9511c49b171ad4e04c6bb419c74d99fe9891d74126ec6e4e879a032069a753d7a2cfa158df95421724d24c0e9501593c09905abf3699b4a4405ce"
220        ));
221
222        let tx_2_result = eth_api.send_raw_transaction(tx_2).await.unwrap();
223        assert_eq!(
224            pool.len(),
225            2,
226            "expect 2 transactions in the pool, but pool size is {}",
227            pool.len()
228        );
229
230        assert!(pool.get(&tx_1_result).is_some(), "tx1 not found in the pool");
231        assert!(pool.get(&tx_2_result).is_some(), "tx2 not found in the pool");
232        assert_eq!(pool.get(&tx_1_result).unwrap().origin, TransactionOrigin::Local);
233        assert_eq!(pool.get(&tx_2_result).unwrap().origin, TransactionOrigin::Local);
234    }
235
236    #[tokio::test]
237    async fn send_raw_transaction_sync_uses_request_timeout() {
238        let eth_api = mock_eth_api(Default::default());
239
240        let err = eth_api.send_raw_transaction_sync(raw_transfer_tx(), Some(1)).await.unwrap_err();
241
242        assert!(matches!(
243            err,
244            EthApiError::TransactionConfirmationTimeout { duration, .. }
245                if duration == Duration::from_millis(1)
246        ));
247        assert_eq!(eth_api.pool().len(), 1);
248    }
249
250    #[tokio::test]
251    async fn send_raw_transaction_sync_uses_configured_timeout_when_omitted() {
252        let eth_api = mock_eth_api_with_sync_timeout(Default::default(), Duration::from_millis(1));
253
254        let err = eth_api.send_raw_transaction_sync(raw_transfer_tx(), None).await.unwrap_err();
255
256        assert!(matches!(
257            err,
258            EthApiError::TransactionConfirmationTimeout { duration, .. }
259                if duration == Duration::from_millis(1)
260        ));
261        assert_eq!(eth_api.pool().len(), 1);
262    }
263
264    #[tokio::test]
265    async fn send_raw_transaction_sync_uses_configured_timeout_when_zero() {
266        let eth_api = mock_eth_api_with_sync_timeout(Default::default(), Duration::from_millis(1));
267
268        let err = eth_api.send_raw_transaction_sync(raw_transfer_tx(), Some(0)).await.unwrap_err();
269
270        assert!(matches!(
271            err,
272            EthApiError::TransactionConfirmationTimeout { duration, .. }
273                if duration == Duration::from_millis(1)
274        ));
275        assert_eq!(eth_api.pool().len(), 1);
276    }
277
278    #[tokio::test]
279    async fn send_raw_transaction_sync_caps_request_timeout() {
280        let eth_api = mock_eth_api_with_sync_timeout(Default::default(), Duration::from_millis(1));
281
282        let err = eth_api.send_raw_transaction_sync(raw_transfer_tx(), Some(50)).await.unwrap_err();
283
284        assert!(matches!(
285            err,
286            EthApiError::TransactionConfirmationTimeout { duration, .. }
287                if duration == Duration::from_millis(1)
288        ));
289        assert_eq!(eth_api.pool().len(), 1);
290    }
291
292    #[tokio::test]
293    async fn test_fill_transaction_fills_chain_id() {
294        let address = Address::random();
295        let accounts = AddressMap::from_iter([(
296            address,
297            ExtendedAccount::new(0, U256::from(10_000_000_000_000_000_000u64)), // 10 ETH
298        )]);
299
300        let eth_api = mock_eth_api(accounts);
301
302        let tx_req = TransactionRequest {
303            from: Some(address),
304            to: Some(Address::random().into()),
305            gas: Some(21_000),
306            ..Default::default()
307        };
308
309        let filled =
310            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
311
312        // Should fill with the chain id from provider
313        assert!(filled.tx.chain_id().is_some());
314    }
315
316    #[tokio::test]
317    async fn test_fill_transaction_fills_nonce() {
318        let address = Address::random();
319        let nonce = 42u64;
320
321        let accounts = AddressMap::from_iter([(
322            address,
323            ExtendedAccount::new(nonce, U256::from(1_000_000_000_000_000_000u64)), // 1 ETH
324        )]);
325
326        let eth_api = mock_eth_api(accounts);
327
328        let tx_req = TransactionRequest {
329            from: Some(address),
330            to: Some(Address::random().into()),
331            value: Some(U256::from(1000)),
332            gas: Some(21_000),
333            ..Default::default()
334        };
335
336        let filled =
337            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
338
339        assert_eq!(filled.tx.nonce(), nonce);
340    }
341
342    #[tokio::test]
343    async fn test_fill_transaction_preserves_provided_fields() {
344        let address = Address::random();
345        let provided_nonce = 100u64;
346        let provided_gas_limit = 50_000u64;
347
348        let accounts = AddressMap::from_iter([(
349            address,
350            ExtendedAccount::new(42, U256::from(10_000_000_000_000_000_000u64)),
351        )]);
352
353        let eth_api = mock_eth_api(accounts);
354
355        let tx_req = TransactionRequest {
356            from: Some(address),
357            to: Some(Address::random().into()),
358            value: Some(U256::from(1000)),
359            nonce: Some(provided_nonce),
360            gas: Some(provided_gas_limit),
361            ..Default::default()
362        };
363
364        let filled =
365            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
366
367        // Should preserve the provided nonce and gas limit
368        assert_eq!(filled.tx.nonce(), provided_nonce);
369        assert_eq!(filled.tx.gas_limit(), provided_gas_limit);
370    }
371
372    #[tokio::test]
373    async fn test_fill_transaction_fills_all_missing_fields() {
374        let address = Address::random();
375
376        let balance = U256::from(100u128) * U256::from(1_000_000_000_000_000_000u128);
377        let accounts = AddressMap::from_iter([(address, ExtendedAccount::new(5, balance))]);
378
379        let eth_api = mock_eth_api(accounts);
380
381        // Create a simple transfer transaction
382        let tx_req = TransactionRequest {
383            from: Some(address),
384            to: Some(Address::random().into()),
385            ..Default::default()
386        };
387
388        let filled =
389            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
390
391        assert!(filled.tx.is_eip1559());
392    }
393
394    #[tokio::test]
395    async fn test_fill_transaction_eip4844_blob_fee() {
396        let address = Address::random();
397        let accounts = AddressMap::from_iter([(
398            address,
399            ExtendedAccount::new(0, U256::from(10_000_000_000_000_000_000u64)),
400        )]);
401
402        let eth_api = mock_eth_api(accounts);
403
404        let mut builder = SidecarBuilder::<SimpleCoder>::new();
405        builder.ingest(b"dummy blob");
406
407        // EIP-4844 blob transaction with versioned hashes but no blob fee
408        let tx_req = TransactionRequest {
409            from: Some(address),
410            to: Some(Address::random().into()),
411            sidecar: Some(BlobTransactionSidecarVariant::from(
412                builder.build::<BlobTransactionSidecar>().unwrap(),
413            )),
414            ..Default::default()
415        };
416
417        let filled =
418            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
419
420        // Blob transaction should have max_fee_per_blob_gas filled
421        assert!(
422            filled.tx.max_fee_per_blob_gas().is_some(),
423            "max_fee_per_blob_gas should be filled for blob tx"
424        );
425        assert!(
426            filled.tx.blob_versioned_hashes().is_some(),
427            "blob_versioned_hashes should be preserved"
428        );
429    }
430
431    #[tokio::test]
432    async fn test_fill_transaction_eip4844_preserves_blob_fee() {
433        let address = Address::random();
434        let accounts = AddressMap::from_iter([(
435            address,
436            ExtendedAccount::new(0, U256::from(10_000_000_000_000_000_000u64)),
437        )]);
438
439        let eth_api = mock_eth_api(accounts);
440
441        let provided_blob_fee = 5000000u128;
442
443        let mut builder = SidecarBuilder::<SimpleCoder>::new();
444        builder.ingest(b"dummy blob");
445
446        // EIP-4844 blob transaction with blob fee already set
447        let tx_req = TransactionRequest {
448            from: Some(address),
449            to: Some(Address::random().into()),
450            transaction_type: Some(3), // EIP-4844
451            sidecar: Some(BlobTransactionSidecarVariant::from(
452                builder.build::<BlobTransactionSidecar>().unwrap(),
453            )),
454            max_fee_per_blob_gas: Some(provided_blob_fee), // Already set
455            ..Default::default()
456        };
457
458        let filled =
459            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
460
461        // Should preserve the provided blob fee
462        assert_eq!(
463            filled.tx.max_fee_per_blob_gas(),
464            Some(provided_blob_fee),
465            "should preserve provided max_fee_per_blob_gas"
466        );
467    }
468
469    #[tokio::test]
470    async fn test_fill_transaction_non_blob_tx_no_blob_fee() {
471        let address = Address::random();
472        let accounts = AddressMap::from_iter([(
473            address,
474            ExtendedAccount::new(0, U256::from(10_000_000_000_000_000_000u64)),
475        )]);
476
477        let eth_api = mock_eth_api(accounts);
478
479        // EIP-1559 transaction without blob fields
480        let tx_req = TransactionRequest {
481            from: Some(address),
482            to: Some(Address::random().into()),
483            transaction_type: Some(2), // EIP-1559
484            ..Default::default()
485        };
486
487        let filled =
488            eth_api.fill_transaction(tx_req).await.expect("fill_transaction should succeed");
489
490        // Non-blob transaction should NOT have blob fee filled
491        assert!(
492            filled.tx.max_fee_per_blob_gas().is_none(),
493            "max_fee_per_blob_gas should not be set for non-blob tx"
494        );
495    }
496}