use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use super::admission::OnionAdmissionRejection;
use super::admission::OnionAdmissionState;
use super::admission::OnionChargeRejection;
use crate::onion::sphinx::cell::OnionCell;
use crate::onion::sphinx::cell::OnionStep;
use crate::onion::sphinx::cell::OnionStepError;
use crate::onion::sphinx::header::OnionLoopTag;
use crate::onion::sphinx::header::OnionPeelError;
use crate::onion::sphinx::layer::OnionLayerApplication;
#[derive(Debug)]
pub(crate) enum OnionHopOutcome {
Refused(OnionChargeRejection),
Dropped(OnionHopDrop),
Stepped(OnionStep),
Returned {
tag: OnionLoopTag,
cell: OnionCell,
},
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum OnionHopDrop {
#[error(transparent)]
Peel(#[from] OnionPeelError),
#[error("admission refused the layer: {0:?}")]
Admission(OnionAdmissionRejection),
#[error("relay layer at a node that relays nothing")]
NotRelay,
#[error("relay layer names a next hop that is not a live link")]
NextNotLive,
#[error(transparent)]
Step(#[from] OnionStepError),
}
pub(crate) fn hop(
admission: &mut OnionAdmissionState,
key: &DelegateeKey,
relays: bool,
is_client_tag: impl Fn(&OnionLoopTag) -> bool,
from: Did,
now_ms: u128,
cell: OnionCell,
) -> OnionHopOutcome {
let Some(link) = admission.live_link(from) else {
return OnionHopOutcome::Refused(OnionChargeRejection::LinkNotLive);
};
let charged = match admission.charge(now_ms, link, cell) {
Ok(charged) => charged,
Err(rejection) => return OnionHopOutcome::Refused(rejection),
};
let tag = charged.value().loop_tag();
if is_client_tag(&tag) {
return OnionHopOutcome::Returned {
tag,
cell: charged.settle(),
};
}
let admitted = match charged.peel(key) {
Ok(peeled) => match peeled.admit(admission, now_ms) {
Ok(admitted) => admitted,
Err(rejection) => return OnionHopOutcome::Dropped(OnionHopDrop::Admission(rejection)),
},
Err(error) => return OnionHopOutcome::Dropped(error.into()),
};
if admitted.head().application == OnionLayerApplication::Relay {
if !relays {
return OnionHopOutcome::Dropped(OnionHopDrop::NotRelay);
}
if admission.live_link(admitted.head().next).is_none() {
return OnionHopOutcome::Dropped(OnionHopDrop::NextNotLive);
}
}
admitted.step().map_or_else(
|error| OnionHopOutcome::Dropped(error.into()),
OnionHopOutcome::Stepped,
)
}