use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use futures::channel::mpsc;
use futures::StreamExt;
use rings_core::dht::Did;
use rings_core::utils::get_epoch_ms;
use rings_test_support::with_hang_guard;
use super::fixture::session_loop;
use crate::error::Error;
use crate::error::Result;
use crate::onion::circuit::OnionAlgebra;
use crate::onion::circuit::OnionLinkSender;
use crate::onion::exit_accounting::OnionExitAccounting;
use crate::onion::runtime::OnionRuntime;
use crate::onion::session::serve::OnionWorld;
use crate::onion::session::serve::OnionWorldReader;
use crate::onion::session::serve::OnionWorldWriter;
use crate::onion::OnionExitDescriptor;
use crate::onion::OnionExitOffer;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionProxyTarget;
use crate::onion::OnionRole;
use crate::onion::OnionRoute;
use crate::onion::OnionRouteHop;
use crate::onion::OnionServiceName;
use crate::online::OnlineNodeType;
use crate::processor::Processor;
use crate::provider::Provider;
use crate::tests::exit_descriptor::ExitDescriptorFixture;
#[cfg(not(feature = "dummy"))]
use crate::tests::native::network_test_guard;
use crate::tests::native::prepare_processor_with_onion_role;
use crate::tests::native::signal_edge;
pub(super) const EVENT_BOUND: Duration = Duration::from_secs(30);
pub(super) struct LoopNode {
processor: Arc<Processor>,
pub(super) runtime: OnionRuntime,
}
impl LoopNode {
async fn new(
role: OnionRole<OnionExitOffer>,
algebra: impl FnOnce(&OnionExitAccounting, &OnionLinkSender) -> OnionAlgebra,
) -> Result<Self> {
let processor = Arc::new(prepare_processor_with_onion_role(role).await);
let provider = Arc::new(Provider::from_processor(Arc::clone(&processor)));
let runtime = OnionRuntime::install_with(&provider.extensions(), algebra)?;
provider.set_backend()?;
Ok(Self { processor, runtime })
}
pub(super) fn did(&self) -> Did {
self.processor.did()
}
fn route_hop(&self) -> OnionRouteHop {
OnionRouteHop::new(
self.did(),
self.processor.delegatee_key().delegatee_public_key(),
self.processor.onion_process_epoch().get(),
)
}
fn exit_descriptor(
&self,
service: OnionServiceName,
policy: OnionExitPolicy,
) -> Result<OnionExitDescriptor> {
ExitDescriptorFixture {
node_type: OnlineNodeType::Native,
..ExitDescriptorFixture::live(&self.processor, service, policy, get_epoch_ms())
}
.sign()
}
}
async fn link(a: &LoopNode, b: &LoopNode) -> Result<()> {
signal_edge(&a.processor, &b.processor).await?;
with_hang_guard("the loop network's link", EVENT_BOUND, async {
a.runtime.links().live(b.did()).await;
b.runtime.links().live(a.did()).await;
})
.await;
Ok(())
}
pub(super) struct LoopNetwork {
pub(super) client: LoopNode,
hops: [LoopNode; 4],
#[cfg(not(feature = "dummy"))]
_serial: tokio::sync::MutexGuard<'static, ()>,
}
impl LoopNetwork {
pub(super) async fn new(
algebra: impl FnOnce(&OnionExitAccounting, &OnionLinkSender) -> OnionAlgebra,
) -> Result<Self> {
#[cfg(not(feature = "dummy"))]
let serial = network_test_guard().await;
let relay = || LoopNode::new(OnionRole::Relay, |_, _| OnionAlgebra::default());
let client = LoopNode::new(OnionRole::Client, |_, _| OnionAlgebra::default()).await?;
let hops = [
relay().await?,
relay().await?,
LoopNode::new(OnionRole::Relay, algebra).await?,
relay().await?,
];
let [g, r02, h, r11] = &hops;
link(&client, g).await?;
link(g, r02).await?;
link(r02, h).await?;
link(h, r11).await?;
link(r11, g).await?;
Ok(Self {
client,
hops,
#[cfg(not(feature = "dummy"))]
_serial: serial,
})
}
pub(super) fn route(&self, service: OnionServiceName) -> Result<OnionRoute> {
self.route_over(service, self.route_hops())
}
pub(super) fn route_hops(&self) -> [OnionRouteHop; 4] {
self.hops.each_ref().map(LoopNode::route_hop)
}
pub(super) fn route_over(
&self,
service: OnionServiceName,
hops: [OnionRouteHop; 4],
) -> Result<OnionRoute> {
let hops = session_loop(hops);
let [_, _, h, _] = &self.hops;
Ok(OnionRoute::new(
service.clone(),
hops,
h.exit_descriptor(service, open_policy())?,
))
}
}
pub(super) fn open_policy() -> OnionExitPolicy {
OnionExitPolicy::from_target_strings(vec!["*".to_string()], Vec::new())
.expect("the wildcard parses")
}
pub(super) struct EchoWorld;
pub(super) struct EchoReader {
written: mpsc::UnboundedReceiver<Bytes>,
pending: Bytes,
}
pub(super) struct EchoWriter(Option<mpsc::UnboundedSender<Bytes>>);
#[async_trait::async_trait]
impl OnionWorld for EchoWorld {
type Reader = EchoReader;
type Writer = EchoWriter;
async fn open(&self, _: &OnionProxyTarget) -> Result<(EchoReader, EchoWriter)> {
let (writer, written) = mpsc::unbounded();
Ok((
EchoReader {
written,
pending: Bytes::new(),
},
EchoWriter(Some(writer)),
))
}
}
#[async_trait::async_trait]
impl OnionWorldReader for EchoReader {
async fn read(&mut self, max: usize) -> Result<Option<Bytes>> {
if self.pending.is_empty() {
match self.written.next().await {
Some(bytes) => self.pending = bytes,
None => return Ok(None),
}
}
let length = max.min(self.pending.len());
Ok(Some(self.pending.split_to(length)))
}
}
#[async_trait::async_trait]
impl OnionWorldWriter for EchoWriter {
async fn write(&mut self, bytes: Bytes) -> Result<()> {
self.0
.as_ref()
.and_then(|writer| writer.unbounded_send(bytes).ok())
.ok_or(Error::InvalidData)
}
async fn shutdown(&mut self) -> Result<()> {
self.0 = None;
Ok(())
}
}
pub(super) struct SourceWorld(pub(super) usize);
pub(super) struct SourceReader(usize);
pub(super) struct SourceWriter;
#[async_trait::async_trait]
impl OnionWorld for SourceWorld {
type Reader = SourceReader;
type Writer = SourceWriter;
async fn open(&self, _: &OnionProxyTarget) -> Result<(SourceReader, SourceWriter)> {
Ok((SourceReader(self.0), SourceWriter))
}
}
#[async_trait::async_trait]
impl OnionWorldReader for SourceReader {
async fn read(&mut self, max: usize) -> Result<Option<Bytes>> {
let length = max.min(self.0);
if length == 0 {
return Ok(None);
}
self.0 -= length;
Ok(Some(Bytes::from(vec![0x5a; length])))
}
}
#[async_trait::async_trait]
impl OnionWorldWriter for SourceWriter {
async fn write(&mut self, _: Bytes) -> Result<()> {
Ok(())
}
async fn shutdown(&mut self) -> Result<()> {
Ok(())
}
}