feat: add network request proxy example (#13974)

This commit is contained in:
Matthias Seitz
2025-01-27 19:49:03 +01:00
committed by GitHub
parent 6b1b9c41aa
commit afd43db9b8
7 changed files with 150 additions and 0 deletions

12
Cargo.lock generated
View File

@ -3103,6 +3103,18 @@ dependencies = [
"tokio",
]
[[package]]
name = "example-network-proxy"
version = "0.0.0"
dependencies = [
"eyre",
"futures",
"reth-chainspec",
"reth-network",
"reth-tracing",
"tokio",
]
[[package]]
name = "example-network-txpool"
version = "0.0.0"

View File

@ -139,6 +139,7 @@ members = [
"examples/manual-p2p/",
"examples/network-txpool/",
"examples/network/",
"examples/network-proxy/",
"examples/node-custom-rpc/",
"examples/node-event-hooks/",
"examples/polygon-p2p/",

View File

@ -369,6 +369,12 @@ impl<N: NetworkPrimitives> NetworkConfigBuilder<N> {
self
}
/// Launches the network with an unused network and discovery port
/// This is useful for testing.
pub fn with_unused_ports(self) -> Self {
self.with_unused_discovery_port().with_unused_listener_port()
}
/// Sets the discovery port to an unused port.
/// This is useful for testing.
pub fn with_unused_discovery_port(self) -> Self {

View File

@ -168,3 +168,6 @@ pub use metrics::TxTypesCounter;
pub use network::{NetworkHandle, NetworkProtocols};
pub use swarm::NetworkConnectionState;
pub use transactions::{FilterAnnouncement, MessageFilter, ValidateTx68};
/// re-export p2p interfaces
pub use reth_network_p2p as p2p;

View File

@ -159,6 +159,16 @@ impl NetworkManager {
}
impl<N: NetworkPrimitives> NetworkManager<N> {
/// Sets the dedicated channel for events indented for the
/// [`TransactionsManager`](crate::transactions::TransactionsManager).
pub fn with_transactions(
mut self,
tx: mpsc::UnboundedSender<NetworkTransactionEvent<N>>,
) -> Self {
self.set_transactions(tx);
self
}
/// Sets the dedicated channel for events indented for the
/// [`TransactionsManager`](crate::transactions::TransactionsManager).
pub fn set_transactions(&mut self, tx: mpsc::UnboundedSender<NetworkTransactionEvent<N>>) {
@ -166,6 +176,13 @@ impl<N: NetworkPrimitives> NetworkManager<N> {
Some(UnboundedMeteredSender::new(tx, NETWORK_POOL_TRANSACTIONS_SCOPE));
}
/// Sets the dedicated channel for events indented for the
/// [`EthRequestHandler`](crate::eth_requests::EthRequestHandler).
pub fn with_eth_request_handler(mut self, tx: mpsc::Sender<IncomingEthRequest<N>>) -> Self {
self.set_eth_request_handler(tx);
self
}
/// Sets the dedicated channel for events indented for the
/// [`EthRequestHandler`](crate::eth_requests::EthRequestHandler).
pub fn set_eth_request_handler(&mut self, tx: mpsc::Sender<IncomingEthRequest<N>>) {

View File

@ -0,0 +1,14 @@
[package]
name = "example-network-proxy"
version = "0.0.0"
publish = false
edition.workspace = true
license.workspace = true
[dependencies]
reth-network.workspace = true
reth-chainspec.workspace = true
reth-tracing.workspace = true
futures.workspace = true
tokio.workspace = true
eyre.workspace = true

View File

@ -0,0 +1,97 @@
//! Example of how to use the network with a proxy for eth requests handling.
//!
//! This connects two peers:
//! - first peer installs a channel for incoming eth request
//! - second peer connects to first peer and sends a header request
//!
//! Run with
//!
//! ```not_rust
//! cargo run --release -p example-network-proxy
//! ```
use futures::StreamExt;
use reth_chainspec::DEV;
use reth_network::{
config::rng_secret_key, eth_requests::IncomingEthRequest, p2p::HeadersClient,
BlockDownloaderProvider, FetchClient, NetworkConfig, NetworkEventListenerProvider,
NetworkHandle, NetworkInfo, NetworkManager, Peers,
};
#[tokio::main]
async fn main() -> eyre::Result<()> {
reth_tracing::init_test_tracing();
// The key that's used for encrypting sessions and to identify our node.
let local_key = rng_secret_key();
// Configure the network
let config = NetworkConfig::builder(local_key).build_with_noop_provider(DEV.clone());
let (tx, mut rx) = tokio::sync::mpsc::channel(1000);
// create the network instance
let network = NetworkManager::eth(config)
.await?
// install the channel through which the network sends incoming eth requests
.with_eth_request_handler(tx);
// get a handle to the network to interact with it
let handle = network.handle().clone();
tokio::task::spawn(async move {
// print network events
let mut events = handle.event_listener();
while let Some(event) = events.next().await {
println!("Received event: {:?}", event);
}
});
let handle = network.handle().clone();
// spawn the network
tokio::task::spawn(network);
// spawn task to fetch a header using another peer/network
tokio::task::spawn(async move {
run_peer(handle).await.unwrap();
});
while let Some(event) = rx.recv().await {
match event {
IncomingEthRequest::GetBlockHeaders { peer_id, request, response } => {
println!("Received block headers request: {:?}, {:?}", peer_id, request);
response.send(Ok(vec![DEV.genesis_header().clone()].into())).unwrap();
}
IncomingEthRequest::GetBlockBodies { .. } => {}
IncomingEthRequest::GetNodeData { .. } => {}
IncomingEthRequest::GetReceipts { .. } => {}
}
}
Ok(())
}
/// Launches another network/peer, connects to the first peer and sends a header request.
async fn run_peer(handle: NetworkHandle) -> eyre::Result<()> {
// create another peer
let config = NetworkConfig::builder(rng_secret_key())
// use random ports
.with_unused_ports()
.build_with_noop_provider(DEV.clone());
let network = NetworkManager::eth(config).await?;
let peer = network.handle().clone();
// spawn additional peer
tokio::task::spawn(network);
// add the other peer as trusted
peer.add_trusted_peer(*handle.peer_id(), handle.local_addr());
// obtain the client that can emit requests
let client: FetchClient = peer.fetch_client().await?;
let header = client.get_header(0.into()).await.unwrap();
println!("Got header: {:?}", header);
Ok(())
}