Skip to main content

reth_rpc/eth/
pubsub.rs

1//! `eth_` `PubSub` RPC handler implementation
2
3use std::{future::ready, 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::{stream::BoxStream, FutureExt, StreamExt};
13use jsonrpsee::{
14    server::{PendingSubscriptionAcceptError, SharedResult, SubscriptionMessage},
15    types::ErrorObject,
16    PendingSubscriptionSink, SubscriptionSink,
17};
18use parking_lot::Mutex;
19use reth_chain_state::CanonStateSubscriptions;
20use reth_network_api::NetworkInfo;
21use reth_rpc_convert::RpcHeader;
22use reth_rpc_eth_api::{
23    helpers::EthSubscriptions, pubsub::EthPubSubApiServer, RpcConvert, RpcLog, RpcNodeCore,
24    RpcTransaction,
25};
26use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err};
27use reth_storage_api::BlockNumReader;
28use reth_tasks::Runtime;
29use reth_transaction_pool::{
30    pool::{NEW_TX_LISTENER_BUFFER_SIZE, PENDING_TX_LISTENER_BUFFER_SIZE},
31    NewTransactionEvent, TransactionPool,
32};
33use serde::Serialize;
34use tokio::sync::{
35    broadcast::{self, error::RecvError},
36    oneshot,
37};
38use tokio_stream::{
39    wrappers::{BroadcastStream, ReceiverStream},
40    Stream,
41};
42use tracing::{debug, error};
43
44/// Capacity of the shared feeds with one item per block. Like the canonical state notification
45/// channel, it lets a subscriber fall 256 blocks behind before it skips the oldest.
46const PER_BLOCK_FEED_CAPACITY: usize = 256;
47
48/// `Eth` pubsub RPC implementation.
49///
50/// This handles `eth_subscribe` RPC calls.
51#[derive(Clone)]
52pub struct EthPubSub<Eth> {
53    /// All nested fields bundled together.
54    inner: Arc<EthPubSubInner<Eth>>,
55}
56
57// === impl EthPubSub ===
58
59impl<Eth> EthPubSub<Eth> {
60    /// Creates a new, shareable instance.
61    pub fn new(eth_api: Eth, subscription_task_spawner: Runtime) -> Self {
62        let inner =
63            EthPubSubInner { eth_api, subscription_task_spawner, feeds: SharedFeeds::default() };
64        Self { inner: Arc::new(inner) }
65    }
66}
67
68impl<Eth> EthPubSub<Eth>
69where
70    Eth: EthSubscriptions,
71{
72    /// Returns the current sync status for the `syncing` subscription
73    pub fn sync_status(&self, is_syncing: bool) -> PubSubSyncStatus {
74        self.inner.sync_status(is_syncing)
75    }
76
77    /// Returns a stream that yields all transaction hashes emitted by the txpool.
78    pub fn pending_transaction_hashes_stream(&self) -> impl Stream<Item = TxHash> {
79        self.inner.pending_transaction_hashes_stream()
80    }
81
82    /// Returns a stream that yields all transactions emitted by the txpool.
83    pub fn full_pending_transaction_stream(
84        &self,
85    ) -> impl Stream<Item = NewTransactionEvent<<Eth::Pool as TransactionPool>::Transaction>> {
86        self.inner.full_pending_transaction_stream()
87    }
88
89    /// Returns a stream that yields new block headers.
90    pub fn new_headers_stream(&self) -> impl Stream<Item = RpcHeader<Eth::NetworkTypes>> {
91        self.inner.eth_api.header_stream()
92    }
93
94    /// Returns a stream that yields matching logs.
95    pub fn log_stream(&self, filter: Filter) -> impl Stream<Item = RpcLog<Eth::NetworkTypes>> {
96        self.inner.eth_api.log_stream(filter)
97    }
98
99    /// Forwards notifications to an already accepted sink. Invalid parameters and per-subscriber
100    /// serialization failures return an error. Shared feeds log failures and skip those items.
101    pub async fn handle_accepted(
102        &self,
103        accepted_sink: SubscriptionSink,
104        kind: SubscriptionKind,
105        params: Option<Params>,
106    ) -> Result<(), ErrorObject<'static>> {
107        self.run_subscription(ready(Ok(accepted_sink)), Subscription::from_params(kind, params)?)
108            .await
109    }
110
111    async fn run_subscription(
112        &self,
113        accepted_sink: impl Future<Output = Result<SubscriptionSink, PendingSubscriptionAcceptError>>,
114        subscription: Subscription,
115    ) -> Result<(), ErrorObject<'static>> {
116        match subscription {
117            Subscription::NewHeads => {
118                let results = self.subscribe_shared(
119                    |feeds| &feeds.new_heads,
120                    |pubsub| pubsub.new_headers_stream().boxed(),
121                );
122                pipe_from_shared(accepted_sink, results).await;
123                Ok(())
124            }
125            Subscription::Logs(filter) => {
126                pipe_from_stream(accepted_sink, self.log_stream(*filter)).await
127            }
128            Subscription::FullPendingTransactions => {
129                let results = self.subscribe_shared(
130                    |feeds| &feeds.full_pending_transactions,
131                    |pubsub| {
132                        let converter = pubsub.inner.eth_api.converter();
133                        pubsub
134                            .full_pending_transaction_stream()
135                            .filter_map(move |tx| {
136                                let tx_value =
137                                    match converter.fill_pending(tx.transaction.to_consensus()) {
138                                        Ok(tx) => Some(tx),
139                                        Err(err) => {
140                                            error!(target = "rpc",
141                                                %err,
142                                                "Failed to fill transaction with block context"
143                                            );
144                                            None
145                                        }
146                                    };
147                                ready(tx_value)
148                            })
149                            .boxed()
150                    },
151                );
152                pipe_from_shared(accepted_sink, results).await;
153                Ok(())
154            }
155            Subscription::PendingTransactionHashes => {
156                let results = self.subscribe_shared(
157                    |feeds| &feeds.pending_transaction_hashes,
158                    |pubsub| pubsub.pending_transaction_hashes_stream().boxed(),
159                );
160                pipe_from_shared(accepted_sink, results).await;
161                Ok(())
162            }
163            Subscription::Syncing => {
164                // get new block subscription
165                let mut canon_state = BroadcastStream::new(
166                    self.inner.eth_api.provider().subscribe_to_canonical_state(),
167                );
168                let Ok(accepted_sink) = accepted_sink.await else { return Ok(()) };
169                // get current sync status
170                let mut initial_sync_status = self.inner.eth_api.network().is_syncing();
171                let current_sub_res = self.sync_status(initial_sync_status);
172
173                // send the current status immediately
174                let msg = SubscriptionMessage::new(
175                    accepted_sink.method_name(),
176                    accepted_sink.subscription_id(),
177                    &current_sub_res,
178                )
179                .map_err(SubscriptionSerializeError::new)?;
180
181                if accepted_sink.send(msg).await.is_err() {
182                    return Ok(())
183                }
184
185                loop {
186                    // Sends only happen when the sync status changes, so a failed send cannot be
187                    // relied on to detect a closed subscription.
188                    tokio::select! {
189                        _ = accepted_sink.closed() => break,
190                        maybe_event = canon_state.next() => {
191                            if maybe_event.is_none() {
192                                break
193                            }
194                        }
195                    }
196
197                    let current_syncing = self.inner.eth_api.network().is_syncing();
198                    // Only send a new response if the sync status has changed
199                    if current_syncing != initial_sync_status {
200                        // Update the sync status on each new block
201                        initial_sync_status = current_syncing;
202
203                        // send a new message now that the status changed
204                        let sync_status = self.sync_status(current_syncing);
205                        let msg = SubscriptionMessage::new(
206                            accepted_sink.method_name(),
207                            accepted_sink.subscription_id(),
208                            &sync_status,
209                        )
210                        .map_err(SubscriptionSerializeError::new)?;
211
212                        if accepted_sink.send(msg).await.is_err() {
213                            break
214                        }
215                    }
216                }
217
218                Ok(())
219            }
220            Subscription::TransactionReceipts(filter) => {
221                if filter.transaction_hashes.as_ref().is_none_or(Vec::is_empty) {
222                    // Without hashes every receipt matches, so all such subscribers get the same.
223                    let results = self.subscribe_shared(
224                        |feeds| &feeds.transaction_receipts,
225                        |pubsub| {
226                            pubsub
227                                .inner
228                                .eth_api
229                                .transaction_receipts_stream(TransactionReceiptsParams::default())
230                                .boxed()
231                        },
232                    );
233                    pipe_from_shared(accepted_sink, results).await;
234                    return Ok(())
235                }
236
237                pipe_from_stream(
238                    accepted_sink,
239                    self.inner.eth_api.transaction_receipts_stream(filter),
240                )
241                .await
242            }
243        }
244    }
245
246    /// Subscribes to the shared feed that `feed` selects, starting a producer over the stream that
247    /// `items` returns if the feed has none.
248    fn subscribe_shared<T: Serialize + Send + 'static>(
249        &self,
250        feed: fn(&SharedFeeds) -> &SharedFeed,
251        items: for<'a> fn(&'a Self) -> BoxStream<'a, T>,
252    ) -> broadcast::Receiver<SharedResult> {
253        feed(&self.inner.feeds).subscribe(|sender| {
254            let pubsub = self.clone();
255            let mut producer = Box::pin(async move {
256                let items = items(&pubsub);
257                feed(&pubsub.inner.feeds).produce(sender, items).await;
258            });
259            let _guard = self.inner.subscription_task_spawner.handle().enter();
260            if producer.as_mut().now_or_never().is_none() {
261                self.inner.subscription_task_spawner.spawn_task(producer);
262            }
263        })
264    }
265}
266
267impl<Eth> EthPubSubApiServer<RpcTransaction<Eth::NetworkTypes>> for EthPubSub<Eth>
268where
269    Eth: EthSubscriptions,
270{
271    /// Rejects invalid subscription parameters before returning a subscription ID.
272    async fn subscribe(
273        &self,
274        pending: PendingSubscriptionSink,
275        kind: SubscriptionKind,
276        params: Option<Params>,
277    ) -> jsonrpsee::core::SubscriptionResult {
278        let subscription = match Subscription::from_params(kind, params) {
279            Ok(subscription) => subscription,
280            Err(err) => {
281                pending.reject(err).await;
282                return Ok(())
283            }
284        };
285        let (mut accepted, acknowledgement) = oneshot::channel();
286        let pubsub = self.clone();
287        self.inner.subscription_task_spawner.spawn_task(async move {
288            // Canceling the forwarder must also cancel an acknowledgement waiting for room.
289            let sink = async {
290                let sink = tokio::select! {
291                    biased;
292                    _ = accepted.closed() => return Err(PendingSubscriptionAcceptError),
293                    sink = pending.accept() => sink?,
294                };
295                accepted.send(()).map_err(|_| PendingSubscriptionAcceptError)?;
296                Ok(sink)
297            };
298            if let Err(err) = pubsub.run_subscription(sink, subscription).await {
299                error!(target: "rpc", %err, "Failed to forward subscription notification");
300            }
301        });
302        acknowledgement.await.map_err(|_| PendingSubscriptionAcceptError.into())
303    }
304}
305
306/// Helper to convert a serde error into an [`ErrorObject`]
307#[derive(Debug, thiserror::Error)]
308#[error("Failed to serialize subscription item: {0}")]
309pub struct SubscriptionSerializeError(#[from] serde_json::Error);
310
311impl SubscriptionSerializeError {
312    const fn new(err: serde_json::Error) -> Self {
313        Self(err)
314    }
315}
316
317impl From<SubscriptionSerializeError> for ErrorObject<'static> {
318    fn from(value: SubscriptionSerializeError) -> Self {
319        internal_rpc_err(value.to_string())
320    }
321}
322
323/// Pipes all stream items to the subscription sink.
324async fn pipe_from_stream<T, St>(
325    sink: impl Future<Output = Result<SubscriptionSink, PendingSubscriptionAcceptError>>,
326    mut stream: St,
327) -> Result<(), ErrorObject<'static>>
328where
329    St: Stream<Item = T> + Unpin,
330    T: Serialize,
331{
332    let Ok(sink) = sink.await else { return Ok(()) };
333    loop {
334        tokio::select! {
335            _ = sink.closed() => {
336                // connection dropped
337                break Ok(())
338            },
339            maybe_item = stream.next() => {
340                let item = match maybe_item {
341                    Some(item) => item,
342                    None => {
343                        // stream ended
344                        break  Ok(())
345                    },
346                };
347                let msg = SubscriptionMessage::new(
348                    sink.method_name(),
349                    sink.subscription_id(),
350                    &item
351                ).map_err(SubscriptionSerializeError::new)?;
352
353                if sink.send(msg).await.is_err() {
354                    break Ok(());
355                }
356            }
357        }
358    }
359}
360
361/// Sends the notifications of a shared feed to the subscription sink.
362async fn pipe_from_shared(
363    sink: impl Future<Output = Result<SubscriptionSink, PendingSubscriptionAcceptError>>,
364    mut results: broadcast::Receiver<SharedResult>,
365) {
366    let Ok(sink) = sink.await else { return };
367    let forward = async {
368        loop {
369            match results.recv().await {
370                Ok(result) => {
371                    if sink.send(SubscriptionMessage::from_shared(result)).await.is_err() {
372                        break
373                    }
374                }
375                Err(RecvError::Lagged(skipped)) => {
376                    debug!(target: "rpc", skipped, "subscription lagging behind its shared feed")
377                }
378                // the feed ended
379                Err(RecvError::Closed) => break,
380            }
381        }
382    };
383    // Also watched while a send waits for room, so an unsubscribed task drops its receiver and the
384    // feed can stop.
385    tokio::select! {
386        _ = sink.closed() => {}
387        _ = forward => {}
388    }
389}
390
391impl<Eth> std::fmt::Debug for EthPubSub<Eth> {
392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393        f.debug_struct("EthPubSub").finish_non_exhaustive()
394    }
395}
396
397/// Container type `EthPubSub`
398struct EthPubSubInner<EthApi> {
399    /// The `eth` API.
400    eth_api: EthApi,
401    /// The type that's used to spawn subscription tasks.
402    subscription_task_spawner: Runtime,
403    /// Feeds of the subscriptions whose notifications are the same for every subscriber.
404    feeds: SharedFeeds,
405}
406
407// == impl EthPubSubInner ===
408
409impl<Eth> EthPubSubInner<Eth>
410where
411    Eth: RpcNodeCore<Provider: BlockNumReader>,
412{
413    /// Returns the current sync status for the `syncing` subscription
414    fn sync_status(&self, is_syncing: bool) -> PubSubSyncStatus {
415        if is_syncing {
416            let current_block = self
417                .eth_api
418                .provider()
419                .chain_info()
420                .map(|info| info.best_number)
421                .unwrap_or_default();
422            PubSubSyncStatus::Detailed(SyncStatusMetadata {
423                syncing: true,
424                starting_block: 0,
425                current_block,
426                highest_block: Some(current_block),
427            })
428        } else {
429            PubSubSyncStatus::Simple(false)
430        }
431    }
432}
433
434impl<Eth> EthPubSubInner<Eth>
435where
436    Eth: RpcNodeCore<Pool: TransactionPool>,
437{
438    /// Returns a stream that yields all transaction hashes emitted by the txpool.
439    fn pending_transaction_hashes_stream(&self) -> impl Stream<Item = TxHash> {
440        ReceiverStream::new(self.eth_api.pool().pending_transactions_listener())
441    }
442
443    /// Returns a stream that yields all transactions emitted by the txpool.
444    fn full_pending_transaction_stream(
445        &self,
446    ) -> impl Stream<Item = NewTransactionEvent<<Eth::Pool as TransactionPool>::Transaction>> {
447        self.eth_api.pool().new_pending_pool_transactions_listener()
448    }
449}
450
451/// Feeds of the subscriptions whose notifications are the same for every subscriber.
452struct SharedFeeds {
453    /// `newHeads`.
454    new_heads: SharedFeed,
455    /// `newPendingTransactions` with full transaction objects.
456    full_pending_transactions: SharedFeed,
457    /// `newPendingTransactions` with transaction hashes.
458    pending_transaction_hashes: SharedFeed,
459    /// `transactionReceipts` without transaction hashes, which matches every receipt.
460    transaction_receipts: SharedFeed,
461}
462
463impl Default for SharedFeeds {
464    fn default() -> Self {
465        Self {
466            new_heads: SharedFeed::new(PER_BLOCK_FEED_CAPACITY),
467            // As many transactions as a subscriber's own pool listener used to buffer.
468            full_pending_transactions: SharedFeed::new(NEW_TX_LISTENER_BUFFER_SIZE),
469            pending_transaction_hashes: SharedFeed::new(PENDING_TX_LISTENER_BUFFER_SIZE),
470            transaction_receipts: SharedFeed::new(PER_BLOCK_FEED_CAPACITY),
471        }
472    }
473}
474
475/// Serializes the notifications of one subscription kind once and broadcasts them to all of its
476/// subscribers.
477///
478/// The producer starts with the first subscriber and stops when the last one leaves, so nothing
479/// is converted or serialized while the kind has no subscribers.
480struct SharedFeed {
481    /// Capacity of the broadcast channel.
482    capacity: usize,
483    /// The running producer's sender, if any.
484    ///
485    /// The producer holds the only strong sender, so if it dies its subscriptions end and the
486    /// next subscriber starts a new one.
487    sender: Mutex<Option<broadcast::WeakSender<SharedResult>>>,
488}
489
490impl SharedFeed {
491    /// Creates a feed without a producer.
492    const fn new(capacity: usize) -> Self {
493        Self { capacity, sender: Mutex::new(None) }
494    }
495
496    /// Starts the producer under the feed lock so concurrent subscribers join after the
497    /// upstream listener is attached.
498    fn subscribe(
499        &self,
500        start: impl FnOnce(broadcast::Sender<SharedResult>),
501    ) -> broadcast::Receiver<SharedResult> {
502        let mut slot = self.sender.lock();
503        if let Some(sender) = slot.as_ref().and_then(broadcast::WeakSender::upgrade) {
504            return sender.subscribe()
505        }
506        let (sender, receiver) = broadcast::channel(self.capacity);
507        *slot = Some(sender.downgrade());
508        start(sender);
509        receiver
510    }
511
512    /// Serializes the items of `items` once and broadcasts them until the feed has no subscribers
513    /// left or `items` ends.
514    async fn produce<T: Serialize>(
515        &self,
516        sender: broadcast::Sender<SharedResult>,
517        mut items: BoxStream<'_, T>,
518    ) {
519        // The listener is attached. Poll its items in the spawned task, outside the feed lock.
520        tokio::task::yield_now().await;
521        loop {
522            tokio::select! {
523                _ = sender.closed() => {
524                    if self.stop_if_unused(&sender) {
525                        break
526                    }
527                }
528                item = items.next() => {
529                    let Some(item) = item else {
530                        // Dropping the sender ends all subscriptions, like the end of their own
531                        // streams did.
532                        *self.sender.lock() = None;
533                        break
534                    };
535                    match SharedResult::new(&item) {
536                        Ok(result) => {
537                            if sender.send(result).is_err() && self.stop_if_unused(&sender) {
538                                break
539                            }
540                        }
541                        Err(err) => error!(target: "rpc", %err, "Failed to serialize subscription item"),
542                    }
543                }
544            }
545            // A source that stays ready, like the blocks of one canonical update, never makes the
546            // loop wait, so this lets the subscribers run before a whole burst is broadcast.
547            tokio::task::consume_budget().await;
548        }
549        debug!(target: "rpc", "shared subscription feed stopped");
550    }
551
552    /// Removes the producer behind `sender` from the feed if it has no subscribers left, and
553    /// returns whether it did.
554    ///
555    /// Subscribing holds the same lock, so a new subscriber either joins before this check or
556    /// starts a new producer after it.
557    fn stop_if_unused(&self, sender: &broadcast::Sender<SharedResult>) -> bool {
558        let mut slot = self.sender.lock();
559        if sender.receiver_count() > 0 {
560            return false
561        }
562        *slot = None;
563        true
564    }
565}
566
567/// An `eth_subscribe` request with its parameters resolved for the requested kind.
568enum Subscription {
569    NewHeads,
570    Logs(Box<Filter>),
571    FullPendingTransactions,
572    PendingTransactionHashes,
573    Syncing,
574    TransactionReceipts(TransactionReceiptsParams),
575}
576
577impl Subscription {
578    fn from_params(
579        kind: SubscriptionKind,
580        params: Option<Params>,
581    ) -> Result<Self, ErrorObject<'static>> {
582        match (kind, params.unwrap_or_default()) {
583            (SubscriptionKind::NewHeads, _) => Ok(Self::NewHeads),
584            // Alloy decodes an object with `transactionHashes` as receipt params and drops its
585            // `address` and `topics`, so it is rejected instead of being served as every log.
586            (SubscriptionKind::Logs, Params::Logs(filter)) => Ok(Self::Logs(filter)),
587            (SubscriptionKind::Logs, Params::None) => Ok(Self::Logs(Box::default())),
588            (SubscriptionKind::NewPendingTransactions, Params::Bool(true)) => {
589                Ok(Self::FullPendingTransactions)
590            }
591            (SubscriptionKind::NewPendingTransactions, Params::Bool(false) | Params::None) => {
592                Ok(Self::PendingTransactionHashes)
593            }
594            (SubscriptionKind::Syncing, _) => Ok(Self::Syncing),
595            (SubscriptionKind::TransactionReceipts, Params::TransactionReceipts(filter)) => {
596                Ok(Self::TransactionReceipts(filter))
597            }
598            // Alloy decodes objects without transactionHashes as log filters. Like geth, ignore
599            // log filter fields for receipt subscriptions.
600            (SubscriptionKind::TransactionReceipts, Params::None | Params::Logs(_)) => {
601                Ok(Self::TransactionReceipts(Default::default()))
602            }
603            _ => Err(invalid_params_rpc_err(format!("Invalid params for {kind}"))),
604        }
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611    use crate::EthApiBuilder;
612    use alloy_consensus::Transaction as _;
613    use futures::stream;
614    use jsonrpsee::{
615        server::{
616            BoundedSubscriptions, ConnectionId, MethodCallback, MethodSink,
617            RandomIntegerIdProvider, SubscriptionState,
618        },
619        RpcModule,
620    };
621    use jsonrpsee_types::{
622        error::ErrorCode, Id, SubscriptionId, SubscriptionPayload, SubscriptionResponse,
623    };
624    use reth_chain_state::{CanonStateNotification, CanonicalInMemoryStateWriter};
625    use reth_chainspec::{ChainSpecProvider, MAINNET};
626    use reth_db_common::init::init_genesis;
627    use reth_ethereum_primitives::Receipt;
628    use reth_evm_ethereum::EthEvmConfig;
629    use reth_execution_types::{Chain, ExecutionOutcome};
630    use reth_network_api::noop::NoopNetwork;
631    use reth_provider::{
632        providers::BlockchainProvider,
633        test_utils::{
634            create_test_provider_factory_with_in_memory_state_writer, MockNodeTypesWithDB,
635        },
636    };
637    use reth_rpc_eth_api::EthApiTypes;
638    use reth_testing_utils::generators::{self, BlockParams};
639    use reth_transaction_pool::{
640        test_utils::{testing_pool, MockTransaction, TestPool},
641        TransactionOrigin,
642    };
643    use serde_json::Value;
644    use std::{future::pending, pin::pin, sync::mpsc::channel, thread, time::Duration};
645    use tokio::{
646        runtime::{Builder, Handle},
647        sync::mpsc,
648    };
649
650    type TestProvider = BlockchainProvider<MockNodeTypesWithDB>;
651
652    /// How long a test waits for a notification or a feed to change.
653    const TIMEOUT: Duration = Duration::from_secs(5);
654
655    /// Capacity of a test subscription's connection channel.
656    const NOTIFICATION_BUFFER: usize = 16;
657
658    fn test_provider() -> (TestProvider, CanonicalInMemoryStateWriter) {
659        let (factory, in_memory_state_writer) =
660            create_test_provider_factory_with_in_memory_state_writer(MAINNET.clone());
661        init_genesis(&factory).unwrap();
662        let canonical_in_memory_state_writer = CanonicalInMemoryStateWriter::new(
663            factory.chain_info_headers().unwrap(),
664            in_memory_state_writer,
665        );
666        let provider = BlockchainProvider::with_canonical_in_memory_state(
667            factory,
668            canonical_in_memory_state_writer.canonical_in_memory_state().clone(),
669        );
670        (provider, canonical_in_memory_state_writer)
671    }
672
673    fn test_pubsub(provider: TestProvider, pool: TestPool) -> EthPubSub<impl EthSubscriptions> {
674        let evm_config = EthEvmConfig::new(provider.chain_spec());
675        let eth_api =
676            EthApiBuilder::new(provider, pool, NoopNetwork::default(), evm_config).build();
677        EthPubSub::new(eth_api, Runtime::test())
678    }
679
680    /// Returns a chain of one block with transactions whose receipts have logs.
681    fn chain_with_logs(number: u64) -> Chain {
682        let mut rng = generators::rng();
683        let block = generators::random_block(
684            &mut rng,
685            number,
686            BlockParams { tx_count: Some(3), ommers_count: Some(0), ..Default::default() },
687        );
688        let mut cumulative_gas_used = 0;
689        let receipts = block
690            .body()
691            .transactions
692            .iter()
693            .map(|tx| {
694                cumulative_gas_used += tx.gas_limit();
695                Receipt {
696                    tx_type: tx.tx_type(),
697                    success: true,
698                    cumulative_gas_used,
699                    logs: (0..2).map(|_| generators::random_log(&mut rng, None, Some(2))).collect(),
700                }
701            })
702            .collect();
703        Chain::new(
704            [block.try_recover().unwrap()],
705            ExecutionOutcome {
706                receipts: vec![receipts],
707                first_block: number,
708                ..Default::default()
709            },
710            Default::default(),
711        )
712    }
713
714    fn commit(canonical_in_memory_state_writer: &mut CanonicalInMemoryStateWriter, chain: Chain) {
715        canonical_in_memory_state_writer
716            .notify_canon_state(CanonStateNotification::Commit { new: Arc::new(chain) });
717    }
718
719    /// Subscribes with `params` and returns the subscription id and its notifications.
720    async fn subscribe(
721        module: &RpcModule<()>,
722        params: &str,
723    ) -> (SubscriptionId<'static>, mpsc::Receiver<String>) {
724        let request =
725            format!(r#"{{"jsonrpc":"2.0","id":1,"method":"eth_subscribe","params":{params}}}"#);
726        let (response, notifications) =
727            module.raw_json_request(&request, NOTIFICATION_BUFFER).await.unwrap();
728        let response: Value = serde_json::from_str(&response).unwrap();
729        let id = response["result"].as_u64().unwrap_or_else(|| panic!("{response}"));
730        (SubscriptionId::Num(id), notifications)
731    }
732
733    async fn unsubscribe(module: &RpcModule<()>, id: &SubscriptionId<'static>) {
734        let request = format!(
735            r#"{{"jsonrpc":"2.0","id":2,"method":"eth_unsubscribe","params":[{}]}}"#,
736            serde_json::to_string(id).unwrap()
737        );
738        let (response, _) = module.raw_json_request(&request, 1).await.unwrap();
739        assert_eq!(response, r#"{"jsonrpc":"2.0","id":2,"result":true}"#);
740    }
741
742    async fn next_notification(notifications: &mut mpsc::Receiver<String>) -> String {
743        tokio::time::timeout(TIMEOUT, notifications.recv()).await.unwrap().unwrap()
744    }
745
746    /// The notification as subscription tasks built it before results were shared: serialized
747    /// per subscriber by `SubscriptionMessage::new`.
748    fn serialized_notification(id: &SubscriptionId<'static>, result: &impl Serialize) -> String {
749        serde_json::to_string(&SubscriptionResponse::new(
750            "eth_subscription".into(),
751            SubscriptionPayload { subscription: id.clone(), result },
752        ))
753        .unwrap()
754    }
755
756    /// Returns how many subscribers the feed's running producer has, or `None` without one.
757    fn feed_subscribers(feed: &SharedFeed) -> Option<usize> {
758        feed.sender.lock().as_ref()?.upgrade().map(|sender| sender.receiver_count())
759    }
760
761    /// Waits until each feed has a running producer with the given number of subscribers.
762    async fn wait_for_producers(feeds: &[(&SharedFeed, usize)]) {
763        tokio::time::timeout(TIMEOUT, async {
764            while !feeds.iter().all(|(feed, count)| feed_subscribers(feed) == Some(*count)) {
765                tokio::task::yield_now().await;
766            }
767        })
768        .await
769        .unwrap();
770    }
771
772    /// Waits until the producer behind `sender` has exited.
773    async fn wait_until_stopped(sender: &broadcast::WeakSender<SharedResult>) {
774        tokio::time::timeout(TIMEOUT, async {
775            while sender.upgrade().is_some() {
776                tokio::task::yield_now().await;
777            }
778        })
779        .await
780        .unwrap();
781    }
782
783    #[tokio::test]
784    async fn shared_notifications_match_serialized_notifications() {
785        let (provider, mut canonical_in_memory_state_writer) = test_provider();
786        let pool = testing_pool();
787        let pubsub = test_pubsub(provider.clone(), pool.clone());
788        let module = pubsub.clone().into_rpc().remove_context();
789
790        let (heads_id, mut heads) = subscribe(&module, r#"["newHeads"]"#).await;
791        // Unfiltered receipt subscriptions share a feed.
792        let mut receipts = Vec::new();
793        for params in [
794            r#"["transactionReceipts"]"#,
795            r#"["transactionReceipts", {}]"#,
796            r#"["transactionReceipts", {"address": "0x0000000000000000000000000000000000000001"}]"#,
797            r#"["transactionReceipts", {"transactionHashes": null}]"#,
798            r#"["transactionReceipts", {"transactionHashes": []}]"#,
799        ] {
800            receipts.push(subscribe(&module, params).await);
801        }
802        let (hashes_id, mut hashes) = subscribe(&module, r#"["newPendingTransactions"]"#).await;
803        let (full_id, mut full) = subscribe(&module, r#"["newPendingTransactions", true]"#).await;
804        let feeds = &pubsub.inner.feeds;
805        wait_for_producers(&[
806            (&feeds.new_heads, 1),
807            (&feeds.transaction_receipts, receipts.len()),
808            (&feeds.pending_transaction_hashes, 1),
809            (&feeds.full_pending_transactions, 1),
810        ])
811        .await;
812
813        // The items subscription tasks used to serialize, from the same sources.
814        let mut expected_heads = pubsub.new_headers_stream().boxed();
815        let mut expected_receipts =
816            pubsub.inner.eth_api.transaction_receipts_stream(Default::default()).boxed();
817        let mut expected_hashes = pubsub.pending_transaction_hashes_stream().boxed();
818        let mut expected_full = pubsub.full_pending_transaction_stream().boxed();
819
820        commit(&mut canonical_in_memory_state_writer, chain_with_logs(1));
821
822        let header = expected_heads.next().await.unwrap();
823        assert_eq!(
824            next_notification(&mut heads).await,
825            serialized_notification(&heads_id, &header)
826        );
827
828        let block_receipts = expected_receipts.next().await.unwrap();
829        for (id, notifications) in &mut receipts {
830            assert_eq!(
831                next_notification(notifications).await,
832                serialized_notification(id, &block_receipts)
833            );
834        }
835
836        pool.add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
837            .await
838            .unwrap();
839
840        let hash = expected_hashes.next().await.unwrap();
841        assert_eq!(
842            next_notification(&mut hashes).await,
843            serialized_notification(&hashes_id, &hash)
844        );
845
846        let tx = expected_full.next().await.unwrap();
847        let tx =
848            pubsub.inner.eth_api.converter().fill_pending(tx.transaction.to_consensus()).unwrap();
849        assert_eq!(next_notification(&mut full).await, serialized_notification(&full_id, &tx));
850
851        // Nothing else was sent.
852        let receipts = receipts.iter_mut().map(|(_, notifications)| notifications);
853        for notifications in receipts.chain([&mut heads, &mut hashes, &mut full]) {
854            assert!(notifications.try_recv().is_err());
855        }
856    }
857
858    #[test]
859    fn receipt_subscription_preserves_transaction_hashes() {
860        let hash = TxHash::repeat_byte(1);
861        let params =
862            serde_json::from_value(serde_json::json!({"transactionHashes": [hash], "foo": 1}))
863                .unwrap();
864        let Subscription::TransactionReceipts(filter) =
865            Subscription::from_params(SubscriptionKind::TransactionReceipts, Some(params)).unwrap()
866        else {
867            panic!("expected a transaction receipts subscription");
868        };
869        assert_eq!(filter.transaction_hashes, Some(vec![hash]));
870    }
871
872    #[tokio::test]
873    async fn shared_feed_runs_only_while_subscribed() {
874        let (provider, mut canonical_in_memory_state_writer) = test_provider();
875        let pubsub = test_pubsub(provider.clone(), testing_pool());
876        let module = pubsub.clone().into_rpc().remove_context();
877        let feed = &pubsub.inner.feeds.new_heads;
878
879        // Nothing runs before the first subscriber, even when blocks arrive.
880        commit(&mut canonical_in_memory_state_writer, chain_with_logs(1));
881        tokio::task::yield_now().await;
882        assert!(feed.sender.lock().is_none());
883
884        // Two subscribers share one producer.
885        let (first_id, mut first) = subscribe(&module, r#"["newHeads"]"#).await;
886        let (second_id, mut second) = subscribe(&module, r#"["newHeads"]"#).await;
887        wait_for_producers(&[(feed, 2)]).await;
888        let producer = feed.sender.lock().clone().unwrap();
889        commit(&mut canonical_in_memory_state_writer, chain_with_logs(2));
890        let notification = next_notification(&mut first).await;
891        assert_eq!(
892            next_notification(&mut second).await,
893            notification.replace(
894                &serde_json::to_string(&first_id).unwrap(),
895                &serde_json::to_string(&second_id).unwrap()
896            )
897        );
898
899        // It keeps running while one subscriber is left.
900        unsubscribe(&module, &first_id).await;
901        wait_for_producers(&[(feed, 1)]).await;
902        commit(&mut canonical_in_memory_state_writer, chain_with_logs(3));
903        next_notification(&mut second).await;
904        assert!(producer.upgrade().is_some());
905
906        // It stops when the last one leaves.
907        unsubscribe(&module, &second_id).await;
908        wait_until_stopped(&producer).await;
909        assert!(feed.sender.lock().is_none());
910
911        // The next subscriber starts a new one.
912        let (_, mut third) = subscribe(&module, r#"["newHeads"]"#).await;
913        wait_for_producers(&[(feed, 1)]).await;
914        commit(&mut canonical_in_memory_state_writer, chain_with_logs(4));
915        next_notification(&mut third).await;
916    }
917
918    #[tokio::test]
919    async fn lagging_subscriber_skips_oldest_notifications() {
920        const BLOCKS: u64 = PER_BLOCK_FEED_CAPACITY as u64 + 64;
921
922        let (provider, mut canonical_in_memory_state_writer) = test_provider();
923        let pubsub = test_pubsub(provider.clone(), testing_pool());
924        let module = pubsub.clone().into_rpc().remove_context();
925        let (_, mut heads) = subscribe(&module, r#"["newHeads"]"#).await;
926        wait_for_producers(&[(&pubsub.inner.feeds.new_heads, 1)]).await;
927
928        // The test doesn't read yet, so the subscriber blocks on its full connection channel
929        // while the producer keeps broadcasting.
930        for number in 1..=BLOCKS {
931            commit(&mut canonical_in_memory_state_writer, chain_with_logs(number));
932            tokio::task::yield_now().await;
933        }
934
935        let mut received = Vec::new();
936        while received.last() != Some(&BLOCKS) {
937            let notification: Value =
938                serde_json::from_str(&next_notification(&mut heads).await).unwrap();
939            let header: alloy_rpc_types_eth::Header =
940                serde_json::from_value(notification["params"]["result"].clone()).unwrap();
941            received.push(header.number);
942        }
943        assert!(received.len() < BLOCKS as usize, "nothing was skipped: {received:?}");
944        assert!(received.is_sorted_by(|a, b| a < b), "{received:?}");
945    }
946
947    #[test]
948    fn subscriptions_receive_the_first_block_after_acknowledgement() {
949        let rpc = Builder::new_current_thread().enable_time().start_paused(true).build().unwrap();
950        let forward = Builder::new_current_thread().enable_all().build().unwrap();
951        let (pubsub, mut writer) = forward.block_on(async {
952            let (provider, writer) = test_provider();
953            (test_pubsub(provider, testing_pool()), writer)
954        });
955        let module = pubsub.clone().into_rpc().remove_context();
956        let chain = chain_with_logs(1);
957        let hash = *chain.transaction_hashes().nth(1).unwrap();
958        let params =
959            serde_json::json!(["transactionReceipts", { "transactionHashes": [hash] }]).to_string();
960        let mut request = pin!(subscribe(&module, &params));
961        // The paused RPC clock advances to the timeout once its tasks are idle.
962        rpc.block_on(async {
963            assert!(
964                tokio::time::timeout(TIMEOUT, &mut request).await.is_err(),
965                "acknowledged before the source could attach"
966            );
967        });
968        let (_, mut notifications) =
969            forward.block_on(async { tokio::time::timeout(TIMEOUT, request).await.unwrap() });
970
971        let mut results = {
972            let _guard = rpc.enter();
973            pubsub.subscribe_shared(
974                |feeds| &feeds.new_heads,
975                |pubsub| {
976                    assert_eq!(
977                        Handle::current().id(),
978                        pubsub.inner.subscription_task_spawner.handle().id()
979                    );
980                    pubsub.new_headers_stream().boxed()
981                },
982            )
983        };
984
985        // Commit once after the receipt acknowledgement, before the new header producer runs.
986        commit(&mut writer, chain);
987        forward.block_on(async {
988            tokio::time::timeout(TIMEOUT, results.recv()).await.unwrap().unwrap();
989            let msg = next_notification(&mut notifications).await;
990            let notification: Value = serde_json::from_str(&msg).unwrap();
991            let receipts = notification["params"]["result"].as_array().unwrap();
992            assert_eq!(receipts.len(), 1);
993            assert_eq!(receipts[0]["transactionHash"], serde_json::json!(hash));
994        });
995    }
996
997    #[tokio::test]
998    async fn unsubscribing_while_a_send_waits_stops_the_feed() {
999        let (provider, mut canonical_in_memory_state_writer) = test_provider();
1000        let pubsub = test_pubsub(provider.clone(), testing_pool());
1001        let module = pubsub.clone().into_rpc().remove_context();
1002        let feed = &pubsub.inner.feeds.new_heads;
1003        let (id, _notifications) = subscribe(&module, r#"["newHeads"]"#).await;
1004        wait_for_producers(&[(feed, 1)]).await;
1005        let producer = feed.sender.lock().clone().unwrap();
1006
1007        // The test doesn't read, so the subscription task ends up waiting for room to send.
1008        for number in 0..=NOTIFICATION_BUFFER as u64 {
1009            commit(&mut canonical_in_memory_state_writer, chain_with_logs(number));
1010            tokio::task::yield_now().await;
1011        }
1012        unsubscribe(&module, &id).await;
1013        wait_until_stopped(&producer).await;
1014    }
1015
1016    #[tokio::test]
1017    async fn producer_yields_while_its_source_stays_ready() {
1018        // More than the feed holds, all ready at once.
1019        const ITEMS: usize = 4 * PER_BLOCK_FEED_CAPACITY;
1020
1021        let pubsub = test_pubsub(test_provider().0, testing_pool());
1022        let mut results =
1023            pubsub.subscribe_shared(|feeds| &feeds.new_heads, |_| stream::iter(0..ITEMS).boxed());
1024
1025        // The subscriber gets to read during the burst, so it skips nothing.
1026        for _ in 0..ITEMS {
1027            tokio::time::timeout(TIMEOUT, results.recv()).await.unwrap().unwrap();
1028        }
1029        // The end of the source ends the feed.
1030        assert!(matches!(results.recv().await, Err(RecvError::Closed)));
1031        assert!(pubsub.inner.feeds.new_heads.sender.lock().is_none());
1032    }
1033
1034    #[test]
1035    fn joining_subscriber_waits_for_source_startup() {
1036        let feed = &SharedFeed::new(1);
1037        let (started, starting) = channel();
1038        let (resume, paused) = channel();
1039        thread::scope(|scope| {
1040            let first = scope.spawn(move || {
1041                feed.subscribe(|sender| {
1042                    started.send(sender).unwrap();
1043                    paused.recv_timeout(TIMEOUT).unwrap();
1044                })
1045            });
1046            let producer = starting.recv_timeout(TIMEOUT).unwrap();
1047            assert!(feed.sender.try_lock().is_none(), "feed exposed during source startup");
1048            resume.send(()).unwrap();
1049            let second = feed.subscribe(|_| panic!("expected to share the first producer"));
1050            let first = first.join().unwrap();
1051            assert!(first.same_channel(&second));
1052            assert_eq!(producer.receiver_count(), 2);
1053        });
1054    }
1055
1056    #[test]
1057    fn direct_subscription_waits_for_acknowledgement_before_polling() {
1058        let stream = stream::iter([42]).inspect(|_| panic!("polled before acknowledgement"));
1059        assert!(pipe_from_stream(pending(), stream).now_or_never().is_none());
1060    }
1061
1062    #[tokio::test]
1063    async fn canceled_subscription_startup_answers_in_process_request() {
1064        let pubsub = test_pubsub(test_provider().0, testing_pool());
1065        let runtime = &pubsub.inner.subscription_task_spawner;
1066        runtime.graceful_shutdown();
1067        tokio::time::timeout(TIMEOUT, runtime.on_shutdown_signal().clone()).await.unwrap();
1068
1069        let module = pubsub.into_rpc();
1070        let request = r#"{"jsonrpc":"2.0","id":1,"method":"eth_subscribe","params":["newHeads"]}"#;
1071        let (response, _) = tokio::time::timeout(TIMEOUT, module.raw_json_request(request, 1))
1072            .await
1073            .unwrap()
1074            .unwrap();
1075        assert_eq!(
1076            response,
1077            r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Internal error"}}"#
1078        );
1079    }
1080
1081    #[tokio::test]
1082    async fn canceled_subscriptions_cannot_send_blocked_ack() {
1083        let pubsub = test_pubsub(test_provider().0, testing_pool());
1084        let module = pubsub.clone().into_rpc();
1085        let Some(MethodCallback::Subscription(subscribe)) = module.method("eth_subscribe") else {
1086            panic!("expected a subscription")
1087        };
1088        let feed = &pubsub.inner.feeds.new_heads;
1089        let start = async |id| {
1090            let (tx, messages) = mpsc::channel(1);
1091            let full = tx.clone().try_reserve_owned().unwrap();
1092            let response = subscribe(
1093                Id::Number(id),
1094                jsonrpsee_types::Params::new(Some(r#"["newHeads"]"#)),
1095                MethodSink::new(tx),
1096                SubscriptionState {
1097                    conn_id: ConnectionId::IN_PROCESS,
1098                    id_provider: &RandomIntegerIdProvider,
1099                    subscription_permit: BoundedSubscriptions::new(1).acquire().unwrap(),
1100                },
1101            );
1102            wait_for_producers(&[(feed, 1)]).await;
1103            (response, feed.sender.lock().clone().unwrap(), full, messages)
1104        };
1105
1106        let (canceled, producer, full, mut messages) = start(1).await;
1107        drop(canceled);
1108        wait_until_stopped(&producer).await;
1109        drop(full);
1110        assert_eq!(tokio::time::timeout(TIMEOUT, messages.recv()).await.unwrap(), None);
1111
1112        let (active, producer, full, mut messages) = start(2).await;
1113        pubsub.inner.subscription_task_spawner.graceful_shutdown();
1114        wait_until_stopped(&producer).await;
1115        drop(full);
1116
1117        let response = tokio::time::timeout(TIMEOUT, active).await.unwrap();
1118        assert_eq!(response.as_error_code(), Some(ErrorCode::InternalError.code()));
1119        assert_eq!(tokio::time::timeout(TIMEOUT, messages.recv()).await.unwrap(), None);
1120    }
1121}