use either::Either;
use libp2p::{
core::{
muxing::StreamMuxerBox,
transport::{Boxed, OptionalTransport},
upgrade,
},
dns, identity, noise, tcp, websocket, PeerId, Transport, TransportExt,
};
use std::{sync::Arc, time::Duration};
pub use libp2p::bandwidth::BandwidthSinks;
pub fn build_transport(
keypair: identity::Keypair,
memory_only: bool,
yamux_window_size: Option<u32>,
yamux_maximum_buffer_size: usize,
) -> (Boxed<(PeerId, StreamMuxerBox)>, Arc<BandwidthSinks>) {
let transport = if !memory_only {
let tcp_config = tcp::Config::new().nodelay(true);
let tcp_trans = tcp::tokio::Transport::new(tcp_config.clone());
let dns_init = dns::TokioDnsConfig::system(tcp_trans);
Either::Left(if let Ok(dns) = dns_init {
let tcp_trans = tcp::tokio::Transport::new(tcp_config);
let dns_for_wss = dns::TokioDnsConfig::system(tcp_trans)
.expect("same system_conf & resolver to work");
Either::Left(websocket::WsConfig::new(dns_for_wss).or_transport(dns))
} else {
let tcp_trans = tcp::tokio::Transport::new(tcp_config.clone());
let desktop_trans = websocket::WsConfig::new(tcp_trans)
.or_transport(tcp::tokio::Transport::new(tcp_config));
Either::Right(desktop_trans)
})
} else {
Either::Right(OptionalTransport::some(libp2p::core::transport::MemoryTransport::default()))
};
let authentication_config = noise::Config::new(&keypair).expect("Can create noise config. qed");
let multiplexing_config = {
let mut yamux_config = libp2p::yamux::Config::default();
yamux_config.set_window_update_mode(libp2p::yamux::WindowUpdateMode::on_read());
yamux_config.set_max_buffer_size(yamux_maximum_buffer_size);
if let Some(yamux_window_size) = yamux_window_size {
yamux_config.set_receive_window_size(yamux_window_size);
}
yamux_config
};
let transport = transport
.upgrade(upgrade::Version::V1Lazy)
.authenticate(authentication_config)
.multiplex(multiplexing_config)
.timeout(Duration::from_secs(20))
.boxed();
transport.with_bandwidth_logging()
}