use std::fmt;
use std::time::Duration;
use serde::Deserialize;
use serde::Serialize;
use crate::error::Error;
use crate::error::Result;
pub const ONION_BACKEND_NAME_MAX_BYTES: usize = 32;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum OnionWidthClass {
B32 = 0,
B64 = 1,
B256 = 2,
KiB1 = 3,
KiB16 = 4,
}
impl OnionWidthClass {
pub const ALL: [Self; 5] = [Self::B32, Self::B64, Self::B256, Self::KiB1, Self::KiB16];
pub const fn bytes(self) -> usize {
match self {
Self::B32 => 32,
Self::B64 => 64,
Self::B256 => 256,
Self::KiB1 => 1_024,
Self::KiB16 => 16_384,
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::B32 => "32",
Self::B64 => "64",
Self::B256 => "256",
Self::KiB1 => "1024",
Self::KiB16 => "16384",
}
}
const fn index(self) -> usize {
self as usize
}
fn parse_token(token: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|class| class.as_str().eq_ignore_ascii_case(token))
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum OnionInputType {
Unit,
Fixed(OnionWidthClass),
}
impl OnionInputType {
pub const ALL: [Self; 1 + OnionWidthClass::ALL.len()] = [
Self::Unit,
Self::Fixed(OnionWidthClass::B32),
Self::Fixed(OnionWidthClass::B64),
Self::Fixed(OnionWidthClass::B256),
Self::Fixed(OnionWidthClass::KiB1),
Self::Fixed(OnionWidthClass::KiB16),
];
pub const fn bytes(self) -> usize {
match self {
Self::Unit => 0,
Self::Fixed(width) => width.bytes(),
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Unit => "0",
Self::Fixed(width) => width.as_str(),
}
}
const fn index(self) -> usize {
match self {
Self::Unit => 0,
Self::Fixed(width) => 1 + width.index(),
}
}
fn parse_token(token: &str) -> Option<Self> {
if token == "0" {
return Some(Self::Unit);
}
OnionWidthClass::parse_token(token).map(Self::Fixed)
}
}
impl From<OnionWidthClass> for OnionInputType {
fn from(width: OnionWidthClass) -> Self {
Self::Fixed(width)
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum OnionLatencyClass {
Ms10 = 0,
Ms100 = 1,
Ms500 = 2,
Ms2000 = 3,
}
impl OnionLatencyClass {
pub const ALL: [Self; 4] = [Self::Ms10, Self::Ms100, Self::Ms500, Self::Ms2000];
pub const fn millis(self) -> u64 {
match self {
Self::Ms10 => 10,
Self::Ms100 => 100,
Self::Ms500 => 500,
Self::Ms2000 => 2_000,
}
}
pub const fn duration(self) -> Duration {
Duration::from_millis(self.millis())
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Ms10 => "10ms",
Self::Ms100 => "100ms",
Self::Ms500 => "500ms",
Self::Ms2000 => "2000ms",
}
}
const fn index(self) -> usize {
self as usize
}
fn parse_token(token: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|latency| latency.as_str().eq_ignore_ascii_case(token))
}
}
pub(crate) const INVOKE_SHAPES: usize =
OnionInputType::ALL.len() * OnionWidthClass::ALL.len() * OnionLatencyClass::ALL.len();
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(try_from = "String", into = "String")]
pub struct OnionInvokeShape {
input: OnionInputType,
output: OnionWidthClass,
latency: OnionLatencyClass,
}
impl OnionInvokeShape {
pub const fn new(
input: OnionInputType,
output: OnionWidthClass,
latency: OnionLatencyClass,
) -> Self {
Self {
input,
output,
latency,
}
}
pub fn all() -> impl Iterator<Item = Self> {
(0..INVOKE_SHAPES).filter_map(Self::from_index)
}
pub const fn input(self) -> OnionInputType {
self.input
}
pub const fn output(self) -> OnionWidthClass {
self.output
}
pub const fn output_bytes(self) -> usize {
self.output.bytes()
}
pub const fn latency(self) -> OnionLatencyClass {
self.latency
}
pub fn parse(raw: impl AsRef<str>) -> Result<Self> {
let raw = raw.as_ref();
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed != raw {
return Err(Error::InvalidConfig(
"onion invoke shape must be non-empty and trimmed".to_string(),
));
}
let invalid = || {
Error::InvalidConfig(format!(
"unknown onion invoke shape {raw:?}; expected invoke<in,out,latency> over the closed signature"
))
};
let Some((prefix, rest)) = trimmed.split_once('<') else {
return Err(invalid());
};
if !prefix.eq_ignore_ascii_case("invoke") {
return Err(invalid());
}
let Some(inner) = rest.strip_suffix('>') else {
return Err(invalid());
};
let mut parts = inner.split(',');
let (Some(input), Some(output), Some(latency), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err(invalid());
};
Ok(Self {
input: OnionInputType::parse_token(input).ok_or_else(invalid)?,
output: OnionWidthClass::parse_token(output).ok_or_else(invalid)?,
latency: OnionLatencyClass::parse_token(latency).ok_or_else(invalid)?,
})
}
pub(crate) const fn index(self) -> usize {
let outputs = OnionWidthClass::ALL.len();
let latencies = OnionLatencyClass::ALL.len();
(self.input.index() * outputs + self.output.index()) * latencies + self.latency.index()
}
pub(crate) fn from_index(index: usize) -> Option<Self> {
if index >= INVOKE_SHAPES {
return None;
}
let latencies = OnionLatencyClass::ALL.len();
let outputs = OnionWidthClass::ALL.len();
let latency_idx = index % latencies;
let output_idx = (index / latencies) % outputs;
let input_idx = index / (latencies * outputs);
Some(Self {
input: *OnionInputType::ALL.get(input_idx)?,
output: *OnionWidthClass::ALL.get(output_idx)?,
latency: *OnionLatencyClass::ALL.get(latency_idx)?,
})
}
}
impl fmt::Display for OnionInvokeShape {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invoke<{},{},{}>",
self.input.as_str(),
self.output.as_str(),
self.latency.as_str()
)
}
}
impl TryFrom<String> for OnionInvokeShape {
type Error = String;
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
Self::parse(&value).map_err(|error| error.to_string())
}
}
impl From<OnionInvokeShape> for String {
fn from(shape: OnionInvokeShape) -> Self {
shape.to_string()
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(try_from = "String", into = "String")]
pub struct OnionBackendName(String);
impl OnionBackendName {
pub fn parse(name: impl AsRef<str>) -> Result<Self> {
let raw = name.as_ref();
if raw.is_empty() || raw.len() > ONION_BACKEND_NAME_MAX_BYTES {
return Err(Error::InvalidConfig(format!(
"onion backend name {raw:?} must be 1..={ONION_BACKEND_NAME_MAX_BYTES} bytes"
)));
}
if !raw.bytes().all(is_backend_name_byte) {
return Err(Error::InvalidConfig(format!(
"onion backend name {raw:?} must contain only [a-z0-9._-]"
)));
}
Ok(Self(raw.to_owned()))
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
const fn is_backend_name_byte(byte: u8) -> bool {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'_' | b'-')
}
impl fmt::Display for OnionBackendName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl TryFrom<String> for OnionBackendName {
type Error = String;
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
Self::parse(&value).map_err(|error| error.to_string())
}
}
impl From<OnionBackendName> for String {
fn from(name: OnionBackendName) -> Self {
name.0
}
}
macro_rules! onion_signature {
(
world_facing: [
$($(#[doc = $doc:literal])* $variant:ident $field:ident $name:literal,)+
] $(,)?
) => {
pub(crate) const WORLD_FACING_SYMBOLS: usize = [$(onion_signature!(@unit $variant),)+].len();
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(u8)]
enum OnionWorldSymbol {
$($(#[doc = $doc])* $variant,)+
}
impl OnionWorldSymbol {
const ALL: [Self; WORLD_FACING_SYMBOLS] = [$(Self::$variant,)+];
const fn name(self) -> &'static str {
match self {
$(Self::$variant => $name,)+
}
}
}
impl OnionServiceName {
pub fn world_facing() -> impl Iterator<Item = Self> {
OnionWorldSymbol::ALL.into_iter().map(Self)
}
$(
#[doc = concat!("Return the name of the world-facing `", $name, "` symbol.")]
pub const fn $field() -> Self {
Self(OnionWorldSymbol::$variant)
}
)+
}
};
(@unit $variant:ident) => {
()
};
}
onion_signature! {
world_facing: [
Tcp tcp "tcp",
Https https "https",
Udp udp "udp",
],
}
const _: () = assert!(1 + INVOKE_SHAPES + WORLD_FACING_SYMBOLS <= (u8::MAX as usize) + 1);
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum OnionShape {
Invoke(OnionInvokeShape),
WorldFacing(OnionServiceName),
}
impl OnionShape {
pub fn all() -> impl Iterator<Item = Self> {
OnionInvokeShape::all()
.map(Self::Invoke)
.chain(OnionServiceName::world_facing().map(Self::WorldFacing))
}
}
impl fmt::Display for OnionShape {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Invoke(shape) => shape.fmt(f),
Self::WorldFacing(service) => f.write_str(service.as_str()),
}
}
}
impl From<OnionInvokeShape> for OnionShape {
fn from(shape: OnionInvokeShape) -> Self {
Self::Invoke(shape)
}
}
impl From<OnionServiceName> for OnionShape {
fn from(service: OnionServiceName) -> Self {
Self::WorldFacing(service)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum OnionSymbol {
Relay,
Shape(OnionShape),
}
impl OnionSymbol {
#[cfg(test)]
pub(crate) const COUNT: usize = 1 + INVOKE_SHAPES + WORLD_FACING_SYMBOLS;
pub(crate) const fn code(&self) -> u8 {
match self {
Self::Relay => 0,
Self::Shape(OnionShape::Invoke(shape)) => (1 + shape.index()) as u8,
Self::Shape(OnionShape::WorldFacing(OnionServiceName(symbol))) => {
(1 + INVOKE_SHAPES) as u8 + *symbol as u8
}
}
}
pub(crate) fn from_code(code: u8) -> Option<Self> {
let Some(non_relay) = usize::from(code).checked_sub(1) else {
return Some(Self::Relay);
};
if let Some(shape) = OnionInvokeShape::from_index(non_relay) {
return Some(Self::Shape(OnionShape::Invoke(shape)));
}
let world = non_relay.checked_sub(INVOKE_SHAPES)?;
OnionWorldSymbol::ALL
.into_iter()
.nth(world)
.map(|symbol| Self::Shape(OnionShape::WorldFacing(OnionServiceName(symbol))))
}
}
#[derive(Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(try_from = "String", into = "String")]
pub struct OnionServiceName(OnionWorldSymbol);
impl OnionServiceName {
pub fn parse(name: impl AsRef<str>) -> Result<Self> {
let name = name.as_ref();
let trimmed = name.trim();
if trimmed.is_empty() || trimmed != name {
return Err(Error::InvalidConfig(
"onion exit service name must be non-empty and trimmed".to_string(),
));
}
OnionServiceName::world_facing()
.find(|service| service.as_str().eq_ignore_ascii_case(trimmed))
.ok_or_else(|| {
Error::InvalidConfig(format!(
"unknown onion service {name:?}; the onion signature is closed: expected one of {}",
OnionServiceName::world_facing()
.map(|service| service.as_str())
.collect::<Vec<_>>()
.join(", ")
))
})
}
pub const fn as_str(&self) -> &'static str {
self.0.name()
}
pub fn matches(&self, service: &str) -> bool {
Self::parse(service).is_ok_and(|candidate| candidate == *self)
}
}
impl fmt::Debug for OnionServiceName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("OnionServiceName")
.field(&self.as_str())
.finish()
}
}
impl PartialOrd for OnionServiceName {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OnionServiceName {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_str().cmp(other.as_str())
}
}
impl TryFrom<String> for OnionServiceName {
type Error = String;
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
Self::parse(&value).map_err(|error| error.to_string())
}
}
impl From<OnionServiceName> for String {
fn from(name: OnionServiceName) -> Self {
name.as_str().to_string()
}
}
#[cfg(test)]
mod tests {
use super::OnionBackendName;
use super::OnionInputType;
use super::OnionInvokeShape;
use super::OnionLatencyClass;
use super::OnionServiceName;
use super::OnionShape;
use super::OnionSymbol;
use super::OnionWidthClass;
use super::INVOKE_SHAPES;
use super::ONION_BACKEND_NAME_MAX_BYTES;
#[test]
fn test_service_names_are_exactly_the_world_facing_signature() {
for service in OnionServiceName::world_facing() {
assert_eq!(
OnionServiceName::parse(service.as_str()).ok(),
Some(service.clone())
);
assert_eq!(
OnionServiceName::parse(service.as_str().to_ascii_uppercase()).ok(),
Some(service)
);
}
for outside in [
"relay",
"invoke<32,64,500ms>",
"jev.typesafe",
"web",
"api",
"custom",
"tcp2",
"",
" tcp",
"tcp!",
] {
assert!(OnionServiceName::parse(outside).is_err());
}
}
#[test]
fn test_invoke_shapes_are_closed_and_round_trip() {
let all = OnionInvokeShape::all().collect::<Vec<_>>();
assert_eq!(all.len(), INVOKE_SHAPES);
assert_eq!(INVOKE_SHAPES, 120);
for (index, shape) in all.iter().copied().enumerate() {
assert_eq!(shape.index(), index);
assert_eq!(OnionInvokeShape::from_index(index), Some(shape));
let rendered = shape.to_string();
assert_eq!(OnionInvokeShape::parse(&rendered).ok(), Some(shape));
assert_eq!(
OnionInvokeShape::parse(rendered.to_ascii_uppercase()).ok(),
Some(shape)
);
let encoded = rings_codec::serialize(&shape).expect("encode invoke shape");
assert_eq!(
rings_codec::deserialize::<OnionInvokeShape>(&encoded).ok(),
Some(shape)
);
}
let sample = OnionInvokeShape::new(
OnionInputType::Fixed(OnionWidthClass::B32),
OnionWidthClass::B64,
OnionLatencyClass::Ms500,
);
assert_eq!(sample.to_string(), "invoke<32,64,500ms>");
for invalid in [
"",
"tcp",
"relay",
" invoke<32,64,500ms>",
"invoke<32,0,10ms>",
"invoke<16,32,10ms>",
"invoke<32,48,10ms>",
"invoke<32,64,25ms>",
"invoke<32,64>",
"invoke<32,64,10ms,extra>",
] {
assert!(
OnionInvokeShape::parse(invalid).is_err(),
"expected {invalid:?} to fail"
);
let bytes = rings_codec::serialize(&invalid).expect("encode raw string");
assert!(rings_codec::deserialize::<OnionInvokeShape>(&bytes).is_err());
}
}
#[test]
fn test_backend_names_enforce_canonical_bounds() {
for valid in [
"a",
"add",
"jev.typesafe",
"hash_256-v1",
&"x".repeat(ONION_BACKEND_NAME_MAX_BYTES),
] {
let parsed = OnionBackendName::parse(valid).expect("valid backend name");
assert_eq!(parsed.as_str(), valid);
let encoded = rings_codec::serialize(&parsed).expect("encode backend name");
assert_eq!(
rings_codec::deserialize::<OnionBackendName>(&encoded).ok(),
Some(parsed)
);
}
for invalid in [
"",
" add",
"add ",
"Jev",
"jev/typesafe",
"jev:1",
"jev\0",
&"x".repeat(ONION_BACKEND_NAME_MAX_BYTES + 1),
] {
assert!(
OnionBackendName::parse(invalid).is_err(),
"expected {invalid:?} to fail"
);
}
}
#[test]
fn test_codec_is_the_name_string_and_rejects_names_outside_the_world_facing_signature() {
let encoded = rings_codec::serialize(&OnionServiceName::https()).expect("encode name");
assert_eq!(
encoded,
rings_codec::serialize(&"https").expect("encode string")
);
for outside in ["web", "relay", "invoke<32,64,10ms>"] {
let bytes = rings_codec::serialize(&outside).expect("encode string");
assert!(rings_codec::deserialize::<OnionServiceName>(bytes.as_slice()).is_err());
}
}
#[test]
fn test_from_code_inverts_code() {
let decoded = (0..=u8::MAX)
.filter_map(|code| OnionSymbol::from_code(code).map(|symbol| (code, symbol)))
.collect::<Vec<_>>();
let table = std::iter::once(OnionSymbol::Relay)
.chain(OnionShape::all().map(OnionSymbol::Shape))
.collect::<Vec<_>>();
assert_eq!(table.len(), OnionSymbol::COUNT);
assert_eq!(decoded.len(), table.len());
for ((position, (code, symbol)), expected) in decoded.iter().enumerate().zip(&table) {
assert_eq!(usize::from(*code), position);
assert_eq!(symbol.code(), *code);
assert_eq!(symbol, expected);
}
}
#[test]
fn test_service_names_order_by_name() {
assert!(OnionServiceName::https() < OnionServiceName::tcp());
assert!(OnionServiceName::tcp() < OnionServiceName::udp());
}
}