Skip to main content

reth_network/test_utils/
testnet.rs

1//! A network implementation for testing purposes.
2
3use crate::{
4    builder::ETH_REQUEST_CHANNEL_CAPACITY,
5    error::NetworkError,
6    eth_requests::EthRequestHandler,
7    protocol::IntoRlpxSubProtocol,
8    transactions::{
9        config::{StrictEthAnnouncementFilter, TransactionPropagationKind},
10        policy::NetworkPolicies,
11        TransactionsHandle, TransactionsManager, TransactionsManagerConfig,
12    },
13    NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,
14};
15use futures::{FutureExt, StreamExt};
16use pin_project::pin_project;
17use reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};
18use reth_eth_wire::{
19    protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,
20};
21use reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};
22use reth_evm_ethereum::EthEvmConfig;
23use reth_metrics::common::mpsc::memory_bounded_channel;
24use reth_network_api::{
25    events::{PeerEvent, SessionInfo},
26    test_utils::{PeersHandle, PeersHandleProvider},
27    NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,
28};
29use reth_network_peers::PeerId;
30use reth_storage_api::{
31    noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,
32    StateProviderFactory, StateRangeProviderFactory,
33};
34use reth_tasks::Runtime;
35use reth_tokio_util::EventStream;
36use reth_transaction_pool::{
37    blobstore::InMemoryBlobStore,
38    test_utils::{TestPool, TestPoolBuilder},
39    EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,
40};
41use secp256k1::SecretKey;
42use std::{
43    fmt,
44    future::Future,
45    net::{Ipv4Addr, SocketAddr, SocketAddrV4},
46    pin::Pin,
47    task::{Context, Poll},
48};
49use tokio::{
50    sync::{mpsc::channel, oneshot},
51    task::JoinHandle,
52};
53
54use crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;
55
56/// A test network consisting of multiple peers.
57pub struct Testnet<C, Pool> {
58    /// All running peers in the network.
59    peers: Vec<Peer<C, Pool>>,
60}
61
62// === impl Testnet ===
63
64impl<C> Testnet<C, TestPool>
65where
66    C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider<ChainSpec: Hardforks>,
67{
68    /// Same as [`Self::try_create_with`] but panics on error
69    pub async fn create_with(num_peers: usize, provider: C) -> Self {
70        Self::try_create_with(num_peers, provider).await.unwrap()
71    }
72
73    /// Creates a new [`Testnet`] with the given number of peers and the provider.
74    pub async fn try_create_with(num_peers: usize, provider: C) -> Result<Self, NetworkError> {
75        let mut this = Self { peers: Vec::with_capacity(num_peers) };
76        for _ in 0..num_peers {
77            let config = PeerConfig::new(provider.clone());
78            this.add_peer_with_config(config).await?;
79        }
80        Ok(this)
81    }
82
83    /// Extend the list of peers with new peers that are configured with each of the given
84    /// [`PeerConfig`]s.
85    pub async fn extend_peer_with_config(
86        &mut self,
87        configs: impl IntoIterator<Item = PeerConfig<C>>,
88    ) -> Result<(), NetworkError> {
89        let peers = configs.into_iter().map(|c| c.launch()).collect::<Vec<_>>();
90        let peers = futures::future::join_all(peers).await;
91        for peer in peers {
92            self.peers.push(peer?);
93        }
94        Ok(())
95    }
96}
97
98impl<C, Pool> Testnet<C, Pool>
99where
100    C: BlockReader + HeaderProvider + Clone + 'static,
101    Pool: TransactionPool,
102{
103    /// Return a mutable slice of all peers.
104    pub fn peers_mut(&mut self) -> &mut [Peer<C, Pool>] {
105        &mut self.peers
106    }
107
108    /// Return a slice of all peers.
109    pub fn peers(&self) -> &[Peer<C, Pool>] {
110        &self.peers
111    }
112
113    /// Remove a peer from the [`Testnet`] and return it.
114    ///
115    /// # Panics
116    /// If the index is out of bounds.
117    pub fn remove_peer(&mut self, index: usize) -> Peer<C, Pool> {
118        self.peers.remove(index)
119    }
120
121    /// Return a mutable iterator over all peers.
122    pub fn peers_iter_mut(&mut self) -> impl Iterator<Item = &mut Peer<C, Pool>> + '_ {
123        self.peers.iter_mut()
124    }
125
126    /// Return an iterator over all peers.
127    pub fn peers_iter(&self) -> impl Iterator<Item = &Peer<C, Pool>> + '_ {
128        self.peers.iter()
129    }
130
131    /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].
132    pub async fn add_peer_with_config(
133        &mut self,
134        config: PeerConfig<C>,
135    ) -> Result<(), NetworkError> {
136        let PeerConfig { config, client, secret_key } = config;
137
138        let network = NetworkManager::new(config).await?;
139        let peer = Peer {
140            network,
141            client,
142            secret_key,
143            request_handler: None,
144            transactions_manager: None,
145            pool: None,
146        };
147        self.peers.push(peer);
148        Ok(())
149    }
150
151    /// Returns all handles to the networks
152    pub fn handles(&self) -> impl Iterator<Item = NetworkHandle<EthNetworkPrimitives>> + '_ {
153        self.peers.iter().map(|p| p.handle())
154    }
155
156    /// Maps the pool of each peer with the given closure
157    pub fn map_pool<F, P>(self, f: F) -> Testnet<C, P>
158    where
159        F: Fn(Peer<C, Pool>) -> Peer<C, P>,
160        P: TransactionPool,
161    {
162        Testnet { peers: self.peers.into_iter().map(f).collect() }
163    }
164
165    /// Apply a closure on each peer
166    pub fn for_each<F>(&self, f: F)
167    where
168        F: Fn(&Peer<C, Pool>),
169    {
170        self.peers.iter().for_each(f)
171    }
172
173    /// Apply a closure on each peer
174    pub fn for_each_mut<F>(&mut self, f: F)
175    where
176        F: FnMut(&mut Peer<C, Pool>),
177    {
178        self.peers.iter_mut().for_each(f)
179    }
180}
181
182impl<C, Pool> Testnet<C, Pool>
183where
184    C: ChainSpecProvider<ChainSpec: EthereumHardforks>
185        + StateProviderFactory
186        + BlockReaderIdExt
187        + HeaderProvider<Header = alloy_consensus::Header>
188        + Clone
189        + 'static,
190    Pool: TransactionPool,
191{
192    /// Installs an eth pool on each peer
193    pub fn with_eth_pool(
194        self,
195    ) -> Testnet<C, EthTransactionPool<C, InMemoryBlobStore, EthEvmConfig>> {
196        self.map_pool(|peer| {
197            let blob_store = InMemoryBlobStore::default();
198            let pool = TransactionValidationTaskExecutor::eth(
199                peer.client.clone(),
200                EthEvmConfig::mainnet(),
201                blob_store.clone(),
202                Runtime::test(),
203            );
204            peer.map_transactions_manager(EthTransactionPool::eth_pool(
205                pool,
206                blob_store,
207                Default::default(),
208            ))
209        })
210    }
211
212    /// Installs an eth pool on each peer with custom transaction manager config
213    pub fn with_eth_pool_config(
214        self,
215        tx_manager_config: TransactionsManagerConfig,
216    ) -> Testnet<C, EthTransactionPool<C, InMemoryBlobStore, EthEvmConfig>> {
217        self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())
218    }
219
220    /// Installs an eth pool on each peer with custom transaction manager config and policy.
221    pub fn with_eth_pool_config_and_policy(
222        self,
223        tx_manager_config: TransactionsManagerConfig,
224        policy: TransactionPropagationKind,
225    ) -> Testnet<C, EthTransactionPool<C, InMemoryBlobStore, EthEvmConfig>> {
226        self.map_pool(|peer| {
227            let blob_store = InMemoryBlobStore::default();
228            let pool = TransactionValidationTaskExecutor::eth(
229                peer.client.clone(),
230                EthEvmConfig::mainnet(),
231                blob_store.clone(),
232                Runtime::test(),
233            );
234
235            peer.map_transactions_manager_with(
236                EthTransactionPool::eth_pool(pool, blob_store, Default::default()),
237                tx_manager_config.clone(),
238                policy,
239            )
240        })
241    }
242}
243
244impl<C, Pool> Testnet<C, Pool>
245where
246    C: BlockReader<
247            Block = reth_ethereum_primitives::Block,
248            Receipt = reth_ethereum_primitives::Receipt,
249            Header = alloy_consensus::Header,
250        > + HeaderProvider
251        + BalProvider
252        + StateProviderFactory
253        + StateRangeProviderFactory
254        + Clone
255        + Unpin
256        + 'static,
257    Pool: TransactionPool<
258            Transaction: PoolTransaction<
259                Consensus = TransactionSigned,
260                Pooled = PooledTransactionVariant,
261            >,
262        > + Unpin
263        + 'static,
264{
265    /// Spawns the testnet to a separate task
266    pub fn spawn(self) -> TestnetHandle<C, Pool> {
267        let (tx, rx) = oneshot::channel::<oneshot::Sender<Self>>();
268        let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::<Vec<_>>();
269        let mut net = self;
270        let handle = tokio::task::spawn(async move {
271            let mut tx = None;
272            tokio::select! {
273                _ = &mut net => {}
274                inc = rx => {
275                    tx = inc.ok();
276                }
277            }
278            if let Some(tx) = tx {
279                let _ = tx.send(net);
280            }
281        });
282
283        TestnetHandle { _handle: handle, peers, terminate: tx }
284    }
285}
286
287impl Testnet<NoopProvider, TestPool> {
288    /// Same as [`Self::try_create`] but panics on error
289    pub async fn create(num_peers: usize) -> Self {
290        Self::try_create(num_peers).await.unwrap()
291    }
292
293    /// Creates a new [`Testnet`] with the given number of peers
294    pub async fn try_create(num_peers: usize) -> Result<Self, NetworkError> {
295        let mut this = Self::default();
296
297        this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;
298        Ok(this)
299    }
300
301    /// Add a peer to the [`Testnet`]
302    pub async fn add_peer(&mut self) -> Result<(), NetworkError> {
303        self.add_peer_with_config(Default::default()).await
304    }
305}
306
307impl<C, Pool> Default for Testnet<C, Pool> {
308    fn default() -> Self {
309        Self { peers: Vec::new() }
310    }
311}
312
313impl<C, Pool> fmt::Debug for Testnet<C, Pool> {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        f.debug_struct("Testnet {{}}").finish_non_exhaustive()
316    }
317}
318
319impl<C, Pool> Future for Testnet<C, Pool>
320where
321    C: BlockReader<
322            Block = reth_ethereum_primitives::Block,
323            Receipt = reth_ethereum_primitives::Receipt,
324            Header = alloy_consensus::Header,
325        > + HeaderProvider
326        + BalProvider
327        + StateProviderFactory
328        + StateRangeProviderFactory
329        + Unpin
330        + 'static,
331    Pool: TransactionPool<
332            Transaction: PoolTransaction<
333                Consensus = TransactionSigned,
334                Pooled = PooledTransactionVariant,
335            >,
336        > + Unpin
337        + 'static,
338{
339    type Output = ();
340
341    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
342        let this = self.get_mut();
343        for peer in &mut this.peers {
344            let _ = peer.poll_unpin(cx);
345        }
346        Poll::Pending
347    }
348}
349
350/// A handle to a [`Testnet`] that can be shared.
351#[derive(Debug)]
352pub struct TestnetHandle<C, Pool> {
353    _handle: JoinHandle<()>,
354    peers: Vec<PeerHandle<Pool>>,
355    terminate: oneshot::Sender<oneshot::Sender<Testnet<C, Pool>>>,
356}
357
358// === impl TestnetHandle ===
359
360impl<C, Pool> TestnetHandle<C, Pool> {
361    /// Terminates the task and returns the [`Testnet`] back.
362    pub async fn terminate(self) -> Testnet<C, Pool> {
363        let (tx, rx) = oneshot::channel();
364        self.terminate.send(tx).unwrap();
365        rx.await.unwrap()
366    }
367
368    /// Returns the [`PeerHandle`]s of this [`Testnet`].
369    pub fn peers(&self) -> &[PeerHandle<Pool>] {
370        &self.peers
371    }
372
373    /// Connects all peers with each other.
374    ///
375    /// This establishes sessions concurrently between all peers.
376    ///
377    /// Returns once all sessions are established.
378    pub async fn connect_peers(&self) {
379        if self.peers.len() < 2 {
380            return
381        }
382
383        // add an event stream for _each_ peer
384        let streams =
385            self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));
386
387        // add all peers to each other
388        for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {
389            for neighbour in &self.peers[idx + 1..] {
390                handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());
391            }
392        }
393
394        // await all sessions to be established
395        let num_sessions_per_peer = self.peers.len() - 1;
396        let fut = streams.into_iter().map(|mut stream| async move {
397            stream.take_session_established(num_sessions_per_peer).await
398        });
399
400        futures::future::join_all(fut).await;
401    }
402}
403
404/// A peer in the [`Testnet`].
405#[pin_project]
406#[derive(Debug)]
407pub struct Peer<C, Pool = TestPool> {
408    #[pin]
409    network: NetworkManager<EthNetworkPrimitives>,
410    #[pin]
411    request_handler: Option<EthRequestHandler<C, EthNetworkPrimitives>>,
412    #[pin]
413    transactions_manager: Option<TransactionsManager<Pool, EthNetworkPrimitives>>,
414    pool: Option<Pool>,
415    client: C,
416    secret_key: SecretKey,
417}
418
419// === impl Peer ===
420
421impl<C, Pool> Peer<C, Pool>
422where
423    C: BlockReader + HeaderProvider + Clone + 'static,
424    Pool: TransactionPool,
425{
426    /// Returns the number of connected peers.
427    pub fn num_peers(&self) -> usize {
428        self.network.num_connected_peers()
429    }
430
431    /// Adds an additional protocol handler to the peer.
432    pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {
433        self.network.add_rlpx_sub_protocol(protocol);
434    }
435
436    /// Returns a handle to the peer's network.
437    pub fn peer_handle(&self) -> PeerHandle<Pool> {
438        PeerHandle {
439            network: self.network.handle().clone(),
440            pool: self.pool.clone(),
441            transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),
442        }
443    }
444
445    /// The address that listens for incoming connections.
446    pub const fn local_addr(&self) -> SocketAddr {
447        self.network.local_addr()
448    }
449
450    /// The [`PeerId`] of this peer.
451    pub fn peer_id(&self) -> PeerId {
452        *self.network.peer_id()
453    }
454
455    /// Returns mutable access to the network.
456    pub const fn network_mut(&mut self) -> &mut NetworkManager<EthNetworkPrimitives> {
457        &mut self.network
458    }
459
460    /// Returns the [`NetworkHandle`] of this peer.
461    pub fn handle(&self) -> NetworkHandle<EthNetworkPrimitives> {
462        self.network.handle().clone()
463    }
464
465    /// Returns the [`TestPool`] of this peer.
466    pub const fn pool(&self) -> Option<&Pool> {
467        self.pool.as_ref()
468    }
469
470    /// Set a new request handler that's connected to the peer's network
471    pub fn install_request_handler(&mut self)
472    where
473        C: BalProvider,
474    {
475        let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);
476        self.network.set_eth_request_handler(tx);
477        let peers = self.network.peers_handle();
478        let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);
479        self.request_handler = Some(request_handler);
480    }
481
482    /// Set a new transactions manager that's connected to the peer's network
483    pub fn install_transactions_manager(&mut self, pool: Pool) {
484        let (tx, rx) = memory_bounded_channel(
485            DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
486            "test_tx_channel",
487        );
488        self.network.set_transactions(tx);
489        let transactions_manager = TransactionsManager::new(
490            self.handle(),
491            pool.clone(),
492            rx,
493            TransactionsManagerConfig::default(),
494        );
495        self.transactions_manager = Some(transactions_manager);
496        self.pool = Some(pool);
497    }
498
499    /// Set a new transactions manager that's connected to the peer's network
500    pub fn map_transactions_manager<P>(self, pool: P) -> Peer<C, P>
501    where
502        P: TransactionPool,
503    {
504        let Self { mut network, request_handler, client, secret_key, .. } = self;
505        let (tx, rx) = memory_bounded_channel(
506            DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
507            "test_tx_channel",
508        );
509        network.set_transactions(tx);
510        let transactions_manager = TransactionsManager::new(
511            network.handle().clone(),
512            pool.clone(),
513            rx,
514            TransactionsManagerConfig::default(),
515        );
516        Peer {
517            network,
518            request_handler,
519            transactions_manager: Some(transactions_manager),
520            pool: Some(pool),
521            client,
522            secret_key,
523        }
524    }
525
526    /// Map transactions manager with custom config
527    pub fn map_transactions_manager_with_config<P>(
528        self,
529        pool: P,
530        config: TransactionsManagerConfig,
531    ) -> Peer<C, P>
532    where
533        P: TransactionPool,
534    {
535        self.map_transactions_manager_with(pool, config, Default::default())
536    }
537
538    /// Map transactions manager with custom config and the given policy.
539    pub fn map_transactions_manager_with<P>(
540        self,
541        pool: P,
542        config: TransactionsManagerConfig,
543        policy: TransactionPropagationKind,
544    ) -> Peer<C, P>
545    where
546        P: TransactionPool,
547    {
548        let Self { mut network, request_handler, client, secret_key, .. } = self;
549        let (tx, rx) = memory_bounded_channel(
550            DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
551            "test_tx_channel",
552        );
553        network.set_transactions(tx);
554
555        let announcement_policy = StrictEthAnnouncementFilter::default();
556        let policies = NetworkPolicies::new(policy, announcement_policy);
557
558        let transactions_manager = TransactionsManager::with_policy(
559            network.handle().clone(),
560            pool.clone(),
561            rx,
562            config,
563            policies,
564        );
565
566        Peer {
567            network,
568            request_handler,
569            transactions_manager: Some(transactions_manager),
570            pool: Some(pool),
571            client,
572            secret_key,
573        }
574    }
575}
576
577impl<C> Peer<C>
578where
579    C: BlockReader + HeaderProvider + Clone + 'static,
580{
581    /// Installs a new [`TestPool`]
582    pub fn install_test_pool(&mut self) {
583        self.install_transactions_manager(TestPoolBuilder::default().into())
584    }
585}
586
587impl<C, Pool> Future for Peer<C, Pool>
588where
589    C: BlockReader<
590            Block = reth_ethereum_primitives::Block,
591            Receipt = reth_ethereum_primitives::Receipt,
592            Header = alloy_consensus::Header,
593        > + HeaderProvider
594        + BalProvider
595        + StateProviderFactory
596        + StateRangeProviderFactory
597        + Unpin
598        + 'static,
599    Pool: TransactionPool<
600            Transaction: PoolTransaction<
601                Consensus = TransactionSigned,
602                Pooled = PooledTransactionVariant,
603            >,
604        > + Unpin
605        + 'static,
606{
607    type Output = ();
608
609    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
610        let this = self.project();
611
612        if let Some(request) = this.request_handler.as_pin_mut() {
613            let _ = request.poll(cx);
614        }
615
616        if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {
617            let _ = tx_manager.poll(cx);
618        }
619
620        this.network.poll(cx)
621    }
622}
623
624/// A helper config for setting up the reth networking stack.
625#[derive(Debug)]
626pub struct PeerConfig<C = NoopProvider> {
627    config: NetworkConfig<C>,
628    client: C,
629    secret_key: SecretKey,
630}
631
632/// A handle to a peer in the [`Testnet`].
633#[derive(Debug)]
634pub struct PeerHandle<Pool> {
635    network: NetworkHandle<EthNetworkPrimitives>,
636    transactions: Option<TransactionsHandle<EthNetworkPrimitives>>,
637    pool: Option<Pool>,
638}
639
640// === impl PeerHandle ===
641
642impl<Pool> PeerHandle<Pool> {
643    /// Returns the [`PeerId`] used in the network.
644    pub fn peer_id(&self) -> &PeerId {
645        self.network.peer_id()
646    }
647
648    /// Returns the [`PeersHandle`] from the network.
649    pub fn peer_handle(&self) -> &PeersHandle {
650        self.network.peers_handle()
651    }
652
653    /// Returns the local socket as configured for the network.
654    pub fn local_addr(&self) -> SocketAddr {
655        self.network.local_addr()
656    }
657
658    /// Creates a new [`NetworkEvent`] listener channel.
659    pub fn event_listener(&self) -> EventStream<NetworkEvent> {
660        self.network.event_listener()
661    }
662
663    /// Returns the [`TransactionsHandle`] of this peer.
664    pub const fn transactions(&self) -> Option<&TransactionsHandle> {
665        self.transactions.as_ref()
666    }
667
668    /// Returns the [`TestPool`] of this peer.
669    pub const fn pool(&self) -> Option<&Pool> {
670        self.pool.as_ref()
671    }
672
673    /// Returns the [`NetworkHandle`] of this peer.
674    pub const fn network(&self) -> &NetworkHandle<EthNetworkPrimitives> {
675        &self.network
676    }
677}
678
679// === impl PeerConfig ===
680
681impl<C> PeerConfig<C>
682where
683    C: BlockReader + HeaderProvider + Clone + 'static,
684{
685    /// Launches the network and returns the [Peer] that manages it
686    pub async fn launch(self) -> Result<Peer<C>, NetworkError> {
687        let Self { config, client, secret_key } = self;
688        let network = NetworkManager::new(config).await?;
689        let peer = Peer {
690            network,
691            client,
692            secret_key,
693            request_handler: None,
694            transactions_manager: None,
695            pool: None,
696        };
697        Ok(peer)
698    }
699
700    /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind
701    /// to any available IP and port.
702    pub fn new(client: C) -> Self
703    where
704        C: ChainSpecProvider<ChainSpec: Hardforks>,
705    {
706        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
707        let config = Self::network_config_builder(secret_key).build(client.clone());
708        Self { config, client, secret_key }
709    }
710
711    /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any
712    /// available IP and port.
713    pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self
714    where
715        C: ChainSpecProvider<ChainSpec: Hardforks>,
716    {
717        let config = Self::network_config_builder(secret_key).build(client.clone());
718        Self { config, client, secret_key }
719    }
720
721    /// Initialize the network with a given capabilities.
722    pub fn with_protocols(client: C, protocols: impl IntoIterator<Item = Protocol>) -> Self
723    where
724        C: ChainSpecProvider<ChainSpec: Hardforks>,
725    {
726        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
727        let protocols: Vec<Protocol> = protocols.into_iter().collect();
728        // `NetworkConfigBuilder::build` re-derives snap advertisement from `snap_enabled`, which
729        // would otherwise silently strip a manually included `snap` capability.
730        let snap_enabled = protocols.iter().any(|p| p.cap.name == Protocol::snap_2().cap.name);
731
732        let builder = Self::network_config_builder(secret_key).with_snap(snap_enabled);
733        let hello_message =
734            HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();
735        let config = builder.hello_message(hello_message).build(client.clone());
736
737        Self { config, client, secret_key }
738    }
739
740    fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {
741        NetworkConfigBuilder::new(secret_key, Runtime::test())
742            .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))
743            .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))
744            .disable_dns_discovery()
745            .disable_discv4_discovery()
746            .peer_config(PeersConfig::test())
747    }
748}
749
750impl Default for PeerConfig {
751    fn default() -> Self {
752        Self::new(NoopProvider::default())
753    }
754}
755
756/// A helper type to await network events
757///
758/// This makes it easier to await established connections
759#[derive(Debug)]
760pub struct NetworkEventStream {
761    inner: EventStream<NetworkEvent>,
762}
763
764// === impl NetworkEventStream ===
765
766impl NetworkEventStream {
767    /// Create a new [`NetworkEventStream`] from the given network event receiver stream.
768    pub const fn new(inner: EventStream<NetworkEvent>) -> Self {
769        Self { inner }
770    }
771
772    /// Awaits the next event for a session to be closed
773    pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option<DisconnectReason>)> {
774        while let Some(ev) = self.inner.next().await {
775            if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {
776                return Some((peer_id, reason))
777            }
778        }
779        None
780    }
781
782    /// Awaits the next event for an established session
783    pub async fn next_session_established(&mut self) -> Option<PeerId> {
784        while let Some(ev) = self.inner.next().await {
785            match ev {
786                NetworkEvent::ActivePeerSession { info, .. } |
787                NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {
788                    return Some(info.peer_id)
789                }
790                _ => {}
791            }
792        }
793        None
794    }
795
796    /// Awaits the next `num` events for an established session
797    pub async fn take_session_established(&mut self, mut num: usize) -> Vec<PeerId> {
798        if num == 0 {
799            return Vec::new();
800        }
801        let mut peers = Vec::with_capacity(num);
802        while let Some(ev) = self.inner.next().await {
803            if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {
804                peers.push(peer_id);
805                num -= 1;
806                if num == 0 {
807                    return peers;
808                }
809            }
810        }
811        peers
812    }
813
814    /// Ensures that the first two events are a [`NetworkEvent::Peer`] and
815    /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the
816    /// established session.
817    pub async fn peer_added_and_established(&mut self) -> Option<PeerId> {
818        let peer_id = match self.inner.next().await {
819            Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,
820            _ => return None,
821        };
822
823        match self.inner.next().await {
824            Some(NetworkEvent::ActivePeerSession {
825                info: SessionInfo { peer_id: peer_id2, .. },
826                ..
827            }) => {
828                debug_assert_eq!(
829                    peer_id, peer_id2,
830                    "PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}"
831                );
832                Some(peer_id)
833            }
834            _ => None,
835        }
836    }
837
838    /// Awaits the next event for a peer added.
839    pub async fn peer_added(&mut self) -> Option<PeerId> {
840        let peer_id = match self.inner.next().await {
841            Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,
842            _ => return None,
843        };
844
845        Some(peer_id)
846    }
847
848    /// Awaits the next event for a peer removed.
849    pub async fn peer_removed(&mut self) -> Option<PeerId> {
850        let peer_id = match self.inner.next().await {
851            Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,
852            _ => return None,
853        };
854
855        Some(peer_id)
856    }
857}