use std::collections::BTreeMap;
use std::num::NonZeroUsize;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use bytes::Bytes;
use rings_core::dht::Did;
use rings_core::message::SlotRoster;
use rings_core::utils::SharedClock;
use rings_core::utils::SharedRng;
use rings_core::utils::SystemClock;
use rings_runtime::MaybeSendSync;
use super::admission::OnionAdmissionLink;
use super::admission::OnionAdmissionState;
use super::admission::OnionReplayFilterKey;
use super::codec::OnionLinkFact;
use super::hop::hop;
use super::hop::OnionHopOutcome;
use super::invoke::OnionInvokeRegistry;
use super::OnionCircuitInput;
use super::OnionClientTags;
use super::OnionLink;
use super::OnionLinkSender;
use crate::error::Error;
use crate::error::Result;
use crate::extension::ext::EffectScope;
use crate::extension::ext::Interpret;
use crate::extension::ext::Scope;
use crate::onion::signature::OnionShape;
use crate::onion::sphinx::carry::OnionCarryValue;
use crate::onion::sphinx::cell::OnionStep;
use crate::onion::sphinx::cell::OnionSurb;
use crate::onion::sphinx::layer::OnionArguments;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionProcessEpochCell;
use crate::onion::OnionServiceName;
use crate::sync_lock::lock;
pub(crate) struct OnionApplicationInput {
pub(crate) from: Did,
pub(crate) arguments: OnionArguments,
pub(crate) value: OnionCarryValue,
pub(crate) surb: Box<OnionSurb>,
pub(crate) received_at_ms: u128,
}
#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
#[cfg_attr(rings_native, async_trait::async_trait)]
pub(crate) trait OnionInterpretation: MaybeSendSync {
async fn evaluate(&self, scope: &Scope, input: OnionApplicationInput) -> Result<()>;
fn lose(&self, peer: Did);
}
#[derive(Default)]
pub(crate) struct OnionAlgebra {
interpretations:
BTreeMap<OnionServiceName, Box<rings_runtime::maybe_send_sync!(dyn OnionInterpretation)>>,
invokes: OnionInvokeRegistry,
}
impl OnionAlgebra {
pub(crate) fn with_invokes(mut self, invokes: OnionInvokeRegistry) -> Self {
self.invokes = invokes;
self
}
fn lose(&self, peer: Did) {
self.interpretations
.values()
.for_each(|interpretation| interpretation.lose(peer));
}
pub(crate) fn register(
mut self,
symbol: OnionServiceName,
interpretation: impl OnionInterpretation + 'static,
) -> Self {
self.interpretations
.insert(symbol, Box::new(interpretation));
self
}
#[cfg(all(test, rings_native))]
pub(crate) fn symbols(&self) -> impl Iterator<Item = &OnionServiceName> {
self.interpretations.keys()
}
async fn evaluate(
&self,
scope: &Scope,
symbol: &OnionShape,
input: OnionApplicationInput,
) -> Result<()> {
match symbol {
OnionShape::WorldFacing(service) => match self.interpretations.get(service) {
Some(interpretation) => interpretation.evaluate(scope, input).await,
None => {
tracing::debug!(
symbol = service.as_str(),
"drop an onion application of an unregistered symbol"
);
Ok(())
}
},
OnionShape::Invoke(shape) => self.invokes.evaluate(scope, *shape, input),
}
}
}
pub(crate) struct OnionCircuitShell {
relays: bool,
admission: Arc<Mutex<OnionAdmissionState>>,
epoch: OnionProcessEpochCell,
tags: OnionClientTags,
link_sender: OnionLinkSender,
algebra: OnionAlgebra,
generations: AtomicU64,
clock: SharedClock,
rng: SharedRng,
#[cfg(all(test, rings_native))]
link_waiters: OnionLinkWaiters,
}
#[cfg(all(test, rings_native))]
type OnionLinkWaiters = Arc<Mutex<Vec<futures::channel::oneshot::Sender<()>>>>;
#[cfg(all(test, rings_native))]
#[derive(Clone)]
pub(crate) struct OnionLinkWitness {
admission: Arc<Mutex<OnionAdmissionState>>,
waiters: OnionLinkWaiters,
}
#[cfg(all(test, rings_native))]
impl OnionLinkWitness {
pub(crate) async fn live(&self, did: Did) {
loop {
let woken = {
let admission = lock(&self.admission).expect("admission lock");
if admission.live_link(did).is_some() {
return;
}
let (waiter, woken) = futures::channel::oneshot::channel();
lock(&self.waiters).expect("waiter lock").push(waiter);
woken
};
let _ = woken.await;
}
}
}
impl OnionCircuitShell {
#[allow(dead_code)]
pub(crate) fn new(
relays: bool,
epoch: OnionProcessEpochCell,
registry_capacity: NonZeroUsize,
slot_roster: Arc<SlotRoster>,
tags: OnionClientTags,
link_sender: OnionLinkSender,
algebra: OnionAlgebra,
) -> Self {
Self::new_with_capabilities(
relays,
epoch,
registry_capacity,
slot_roster,
tags,
link_sender,
algebra,
Arc::new(SystemClock),
SharedRng::system(),
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new_with_capabilities(
relays: bool,
epoch: OnionProcessEpochCell,
registry_capacity: NonZeroUsize,
slot_roster: Arc<SlotRoster>,
tags: OnionClientTags,
link_sender: OnionLinkSender,
algebra: OnionAlgebra,
clock: SharedClock,
rng: SharedRng,
) -> Self {
let filter_key = OnionReplayFilterKey::from_rng(&mut rng.lock_rng());
let admission = OnionAdmissionState::new(epoch.get(), filter_key, registry_capacity)
.with_slot_roster(slot_roster);
Self {
relays,
admission: Arc::new(Mutex::new(admission)),
epoch,
tags,
link_sender,
algebra,
generations: AtomicU64::new(0),
clock,
rng,
#[cfg(all(test, rings_native))]
link_waiters: OnionLinkWaiters::default(),
}
}
#[cfg(all(test, rings_native))]
pub(crate) fn link_witness(&self) -> OnionLinkWitness {
OnionLinkWitness {
admission: Arc::clone(&self.admission),
waiters: Arc::clone(&self.link_waiters),
}
}
#[cfg(all(test, rings_native))]
pub(crate) fn registered_services(
&self,
) -> std::collections::BTreeSet<crate::onion::OnionServiceName> {
self.algebra.symbols().cloned().collect()
}
async fn hop(
&self,
scope: &EffectScope,
from: Did,
cell: crate::onion::sphinx::cell::OnionCell,
) -> Result<()> {
let now_ms = self.clock.now_ms();
self.renew_if_rolled_back(now_ms)?;
let keys = scope.lifecycle().decryption_keys_at(now_ms);
let outcome = {
let mut admission = lock(&self.admission)?;
hop(
&mut admission,
&keys,
self.relays,
|tag| self.tags.expects(from, tag),
from,
now_ms,
cell,
)
};
match outcome {
OnionHopOutcome::Stepped(OnionStep::Relayed { next, cell }) => {
if let Err(error) =
self.link_sender
.enqueue(scope.lifecycle(), OnionLink::new(next), cell)
{
tracing::debug!(%next, %error, "drop a relayed onion cell");
}
Ok(())
}
OnionHopOutcome::Stepped(OnionStep::Consumed {
symbol,
arguments,
value,
surb,
}) => {
let input = OnionApplicationInput {
from,
arguments,
value,
surb,
received_at_ms: now_ms,
};
self.algebra
.evaluate(&scope.lifecycle(), &symbol, input)
.await
}
OnionHopOutcome::Returned { tag, cell } => {
if let Err(dropped) = self.tags.deliver(now_ms, from, &tag, cell) {
tracing::debug!(%from, %dropped, "drop a returning onion cell");
}
Ok(())
}
OnionHopOutcome::Refused(rejection) => {
tracing::debug!(%from, ?rejection, "refuse an onion cell uncharged");
Ok(())
}
OnionHopOutcome::Dropped(drop) => {
tracing::debug!(%from, %drop, "drop a charged onion cell");
Ok(())
}
}
}
async fn link(&self, scope: &EffectScope, fact: OnionLinkFact) -> Result<()> {
let now_ms = self.clock.now_ms();
let lifecycle = scope.lifecycle();
let (refused, lanes) = match fact {
OnionLinkFact::Opened(peer) => self.open_link(now_ms, peer)?,
OnionLinkFact::Closed(peer) => {
let mut admission = lock(&self.admission)?;
if let Some(link) = admission.live_link(peer) {
admission.link_closed(now_ms, link);
}
(Vec::new(), OnionLaneChange::Close(peer))
}
OnionLinkFact::Dropped(_) => (Vec::new(), OnionLaneChange::Keep),
OnionLinkFact::Reconcile => self.reconcile(now_ms, lifecycle.admitted_peers())?,
};
let applied = match lanes {
OnionLaneChange::Keep => Ok(()),
OnionLaneChange::Open(peer) => self.link_sender.open(lifecycle, OnionLink::new(peer)),
OnionLaneChange::Close(peer) => self.link_sender.close(OnionLink::new(peer)),
OnionLaneChange::Follow(up) => self.link_sender.reconcile(&lifecycle, &up),
};
if let Err(error) = applied {
tracing::debug!(%error, "onion link lanes did not follow a link fact");
}
if let OnionLinkFact::Closed(peer) | OnionLinkFact::Dropped(peer) = fact {
self.tags.lose(peer);
self.algebra.lose(peer);
}
#[cfg(all(test, rings_native))]
if let Ok(mut waiters) = lock(&self.link_waiters) {
waiters.drain(..).for_each(|waiter| {
let _ = waiter.send(());
});
}
for link in refused {
tracing::debug!(
did = %link.peer(),
"onion link table is full; the link carries no onion cell"
);
}
Ok(())
}
fn open_link(
&self,
now_ms: u128,
peer: Did,
) -> Result<(Vec<OnionAdmissionLink>, OnionLaneChange)> {
let mut admission = lock(&self.admission)?;
if admission.live_link(peer).is_some() {
return Ok((Vec::new(), OnionLaneChange::Keep));
}
let link = OnionAdmissionLink::new(peer, self.next_generation());
Ok(match admission.link_opened(now_ms, link) {
Ok(()) => (Vec::new(), OnionLaneChange::Open(peer)),
Err(_) => (vec![link], OnionLaneChange::Keep),
})
}
fn reconcile(
&self,
now_ms: u128,
admitted: Vec<Did>,
) -> Result<(Vec<OnionAdmissionLink>, OnionLaneChange)> {
let mut admission = lock(&self.admission)?;
let snapshot = admitted
.into_iter()
.map(|peer| {
admission
.live_link(peer)
.unwrap_or_else(|| OnionAdmissionLink::new(peer, self.next_generation()))
})
.collect::<Vec<_>>();
let refused = admission.reconcile(now_ms, snapshot).links().to_vec();
Ok((refused, OnionLaneChange::Follow(live_peers(&admission))))
}
fn next_generation(&self) -> u64 {
self.generations.fetch_add(1, Ordering::Relaxed)
}
fn renew_if_rolled_back(&self, now_ms: u128) -> Result<()> {
let mut admission = lock(&self.admission)?;
if !admission.is_rolled_back_at(now_ms) {
return Ok(());
}
loop {
let mut rng = self.rng.lock_rng();
let epoch = OnionProcessEpoch::from_rng(&mut rng);
let key = OnionReplayFilterKey::from_rng(&mut rng);
drop(rng);
if admission.renew(epoch, key).is_ok() {
self.epoch.renew(epoch);
tracing::warn!("onion admission renewed its epoch after a clock rollback");
return Ok(());
}
}
}
}
impl Drop for OnionCircuitShell {
fn drop(&mut self) {
if let Err(error) = self.link_sender.shutdown() {
tracing::debug!(%error, "onion data plane could not close its link lanes");
}
}
}
enum OnionLaneChange {
Keep,
Open(Did),
Close(Did),
Follow(Vec<Did>),
}
fn live_peers(admission: &OnionAdmissionState) -> Vec<Did> {
let mut peers = admission
.live_links()
.into_iter()
.map(OnionAdmissionLink::peer)
.collect::<Vec<_>>();
peers.dedup();
peers
}
#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
#[cfg_attr(rings_native, async_trait::async_trait)]
impl Interpret for OnionCircuitShell {
type Effect = OnionCircuitInput;
async fn run(&self, scope: &EffectScope, effect: OnionCircuitInput) -> Result<Vec<Bytes>> {
match effect {
OnionCircuitInput::Cell { from, cell } => self.hop(scope, from, cell).await,
OnionCircuitInput::Link(fact) => self.link(scope, fact).await,
}
.map(|()| Vec::new())
.or_else(|error: Error| {
tracing::debug!(%error, "onion circuit effect failed");
Ok(Vec::new())
})
}
}