Skip to main content

reth_rpc/eth/
pubsub.rs

1//! `eth_` `PubSub` RPC handler implementation
2
3use std::sync::Arc;
4
5use alloy_primitives::TxHash;
6use alloy_rpc_types_eth::{
7    pubsub::{
8        Params, PubSubSyncStatus, SubscriptionKind, SyncStatusMetadata, TransactionReceiptsParams,
9    },
10    Filter,
11};
12use futures::StreamExt;
13use jsonrpsee::{
14    server::SubscriptionMessage, types::ErrorObject, PendingSubscriptionSink, SubscriptionSink,
15};
16use reth_chain_state::CanonStateSubscriptions;
17use reth_network_api::NetworkInfo;
18use reth_rpc_convert::RpcHeader;
19use reth_rpc_eth_api::{
20    helpers::EthSubscriptions, pubsub::EthPubSubApiServer, RpcConvert, RpcLog, RpcNodeCore,
21    RpcTransaction,
22};
23use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err};
24use reth_storage_api::BlockNumReader;
25use reth_tasks::Runtime;
26use reth_transaction_pool::{NewTransactionEvent, TransactionPool};
27use serde::Serialize;
28use tokio_stream::{
29    wrappers::{BroadcastStream, ReceiverStream},
30    Stream,
31};
32use tracing::error;
33
34/// `Eth` pubsub RPC implementation.
35///
36/// This handles `eth_subscribe` RPC calls.
37#[derive(Clone)]
38pub struct EthPubSub<Eth> {
39    /// All nested fields bundled together.
40    inner: Arc<EthPubSubInner<Eth>>,
41}
42
43// === impl EthPubSub ===
44
45impl<Eth> EthPubSub<Eth> {
46    /// Creates a new, shareable instance.
47    pub fn new(eth_api: Eth, subscription_task_spawner: Runtime) -> Self {
48        let inner = EthPubSubInner { eth_api, subscription_task_spawner };
49        Self { inner: Arc::new(inner) }
50    }
51}
52
53impl<Eth> EthPubSub<Eth>
54where
55    Eth: EthSubscriptions,
56{
57    /// Returns the current sync status for the `syncing` subscription
58    pub fn sync_status(&self, is_syncing: bool) -> PubSubSyncStatus {
59        self.inner.sync_status(is_syncing)
60    }
61
62    /// Returns a stream that yields all transaction hashes emitted by the txpool.
63    pub fn pending_transaction_hashes_stream(&self) -> impl Stream<Item = TxHash> {
64        self.inner.pending_transaction_hashes_stream()
65    }
66
67    /// Returns a stream that yields all transactions emitted by the txpool.
68    pub fn full_pending_transaction_stream(
69        &self,
70    ) -> impl Stream<Item = NewTransactionEvent<<Eth::Pool as TransactionPool>::Transaction>> {
71        self.inner.full_pending_transaction_stream()
72    }
73
74    /// Returns a stream that yields new block headers.
75    pub fn new_headers_stream(&self) -> impl Stream<Item = RpcHeader<Eth::NetworkTypes>> {
76        self.inner.eth_api.header_stream()
77    }
78
79    /// Returns a stream that yields matching logs.
80    pub fn log_stream(&self, filter: Filter) -> impl Stream<Item = RpcLog<Eth::NetworkTypes>> {
81        self.inner.eth_api.log_stream(filter)
82    }
83
84    /// The actual handler for an accepted [`EthPubSub::subscribe`] call.
85    pub async fn handle_accepted(
86        &self,
87        accepted_sink: SubscriptionSink,
88        kind: SubscriptionKind,
89        params: Option<Params>,
90    ) -> Result<(), ErrorObject<'static>> {
91        #[allow(unreachable_patterns)]
92        match kind {
93            SubscriptionKind::NewHeads => {
94                pipe_from_stream(accepted_sink, self.new_headers_stream()).await
95            }
96            SubscriptionKind::Logs => {
97                // if no params are provided, used default filter params
98                let filter = match params {
99                    Some(Params::Logs(filter)) => *filter,
100                    Some(Params::Bool(_)) => {
101                        return Err(invalid_params_rpc_err("Invalid params for logs"))
102                    }
103                    _ => Default::default(),
104                };
105                pipe_from_stream(accepted_sink, self.log_stream(filter)).await
106            }
107            SubscriptionKind::NewPendingTransactions => {
108                if let Some(params) = params {
109                    match params {
110                        Params::Bool(true) => {
111                            // full transaction objects requested
112                            let stream = self.full_pending_transaction_stream().filter_map(|tx| {
113                                let tx_value = match self
114                                    .inner
115                                    .eth_api
116                                    .converter()
117                                    .fill_pending(tx.transaction.to_consensus())
118                                {
119                                    Ok(tx) => Some(tx),
120                                    Err(err) => {
121                                        error!(target = "rpc",
122                                            %err,
123                                            "Failed to fill transaction with block context"
124                                        );
125                                        None
126                                    }
127                                };
128                                std::future::ready(tx_value)
129                            });
130                            return pipe_from_stream(accepted_sink, stream).await
131                        }
132                        Params::Bool(false) | Params::None => {
133                            // only hashes requested
134                        }
135                        _ => {
136                            return Err(invalid_params_rpc_err(
137                                "Invalid params for newPendingTransactions",
138                            ))
139                        }
140                    }
141                }
142
143                pipe_from_stream(accepted_sink, self.pending_transaction_hashes_stream()).await
144            }
145            SubscriptionKind::Syncing => {
146                // get new block subscription
147                let mut canon_state = BroadcastStream::new(
148                    self.inner.eth_api.provider().subscribe_to_canonical_state(),
149                );
150                // get current sync status
151                let mut initial_sync_status = self.inner.eth_api.network().is_syncing();
152                let current_sub_res = self.sync_status(initial_sync_status);
153
154                // send the current status immediately
155                let msg = SubscriptionMessage::new(
156                    accepted_sink.method_name(),
157                    accepted_sink.subscription_id(),
158                    &current_sub_res,
159                )
160                .map_err(SubscriptionSerializeError::new)?;
161
162                if accepted_sink.send(msg).await.is_err() {
163                    return Ok(())
164                }
165
166                while canon_state.next().await.is_some() {
167                    let current_syncing = self.inner.eth_api.network().is_syncing();
168                    // Only send a new response if the sync status has changed
169                    if current_syncing != initial_sync_status {
170                        // Update the sync status on each new block
171                        initial_sync_status = current_syncing;
172
173                        // send a new message now that the status changed
174                        let sync_status = self.sync_status(current_syncing);
175                        let msg = SubscriptionMessage::new(
176                            accepted_sink.method_name(),
177                            accepted_sink.subscription_id(),
178                            &sync_status,
179                        )
180                        .map_err(SubscriptionSerializeError::new)?;
181
182                        if accepted_sink.send(msg).await.is_err() {
183                            break
184                        }
185                    }
186                }
187
188                Ok(())
189            }
190            SubscriptionKind::TransactionReceipts => {
191                let filter = match params {
192                    Some(Params::TransactionReceipts(filter)) => filter,
193                    None | Some(Params::None) => TransactionReceiptsParams::default(),
194                    _ => {
195                        return Err(invalid_params_rpc_err("Invalid params for transactionReceipts"))
196                    }
197                };
198
199                pipe_from_stream(
200                    accepted_sink,
201                    self.inner.eth_api.transaction_receipts_stream(filter),
202                )
203                .await
204            }
205            _ => Err(invalid_params_rpc_err("Unsupported subscription kind")),
206        }
207    }
208}
209
210#[async_trait::async_trait]
211impl<Eth> EthPubSubApiServer<RpcTransaction<Eth::NetworkTypes>> for EthPubSub<Eth>
212where
213    Eth: EthSubscriptions,
214{
215    /// Handler for `eth_subscribe`
216    async fn subscribe(
217        &self,
218        pending: PendingSubscriptionSink,
219        kind: SubscriptionKind,
220        params: Option<Params>,
221    ) -> jsonrpsee::core::SubscriptionResult {
222        let sink = pending.accept().await?;
223        let pubsub = self.clone();
224        self.inner.subscription_task_spawner.spawn_task(async move {
225            let _ = pubsub.handle_accepted(sink, kind, params).await;
226        });
227
228        Ok(())
229    }
230}
231
232/// Helper to convert a serde error into an [`ErrorObject`]
233#[derive(Debug, thiserror::Error)]
234#[error("Failed to serialize subscription item: {0}")]
235pub struct SubscriptionSerializeError(#[from] serde_json::Error);
236
237impl SubscriptionSerializeError {
238    const fn new(err: serde_json::Error) -> Self {
239        Self(err)
240    }
241}
242
243impl From<SubscriptionSerializeError> for ErrorObject<'static> {
244    fn from(value: SubscriptionSerializeError) -> Self {
245        internal_rpc_err(value.to_string())
246    }
247}
248
249/// Pipes all stream items to the subscription sink.
250async fn pipe_from_stream<T, St>(
251    sink: SubscriptionSink,
252    mut stream: St,
253) -> Result<(), ErrorObject<'static>>
254where
255    St: Stream<Item = T> + Unpin,
256    T: Serialize,
257{
258    loop {
259        tokio::select! {
260            _ = sink.closed() => {
261                // connection dropped
262                break Ok(())
263            },
264            maybe_item = stream.next() => {
265                let item = match maybe_item {
266                    Some(item) => item,
267                    None => {
268                        // stream ended
269                        break  Ok(())
270                    },
271                };
272                let msg = SubscriptionMessage::new(
273                    sink.method_name(),
274                    sink.subscription_id(),
275                    &item
276                ).map_err(SubscriptionSerializeError::new)?;
277
278                if sink.send(msg).await.is_err() {
279                    break Ok(());
280                }
281            }
282        }
283    }
284}
285
286impl<Eth> std::fmt::Debug for EthPubSub<Eth> {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        f.debug_struct("EthPubSub").finish_non_exhaustive()
289    }
290}
291
292/// Container type `EthPubSub`
293#[derive(Clone)]
294struct EthPubSubInner<EthApi> {
295    /// The `eth` API.
296    eth_api: EthApi,
297    /// The type that's used to spawn subscription tasks.
298    subscription_task_spawner: Runtime,
299}
300
301// == impl EthPubSubInner ===
302
303impl<Eth> EthPubSubInner<Eth>
304where
305    Eth: RpcNodeCore<Provider: BlockNumReader>,
306{
307    /// Returns the current sync status for the `syncing` subscription
308    fn sync_status(&self, is_syncing: bool) -> PubSubSyncStatus {
309        if is_syncing {
310            let current_block = self
311                .eth_api
312                .provider()
313                .chain_info()
314                .map(|info| info.best_number)
315                .unwrap_or_default();
316            PubSubSyncStatus::Detailed(SyncStatusMetadata {
317                syncing: true,
318                starting_block: 0,
319                current_block,
320                highest_block: Some(current_block),
321            })
322        } else {
323            PubSubSyncStatus::Simple(false)
324        }
325    }
326}
327
328impl<Eth> EthPubSubInner<Eth>
329where
330    Eth: RpcNodeCore<Pool: TransactionPool>,
331{
332    /// Returns a stream that yields all transaction hashes emitted by the txpool.
333    fn pending_transaction_hashes_stream(&self) -> impl Stream<Item = TxHash> {
334        ReceiverStream::new(self.eth_api.pool().pending_transactions_listener())
335    }
336
337    /// Returns a stream that yields all transactions emitted by the txpool.
338    fn full_pending_transaction_stream(
339        &self,
340    ) -> impl Stream<Item = NewTransactionEvent<<Eth::Pool as TransactionPool>::Transaction>> {
341        self.eth_api.pool().new_pending_pool_transactions_listener()
342    }
343}