1use std::time::Duration;
30
31use super::signature::OnionBackendName;
32use super::signature::OnionInputType;
33use super::signature::OnionInvokeShape;
34use super::signature::OnionServiceName;
35use super::signature::OnionShape;
36use super::signature::OnionWidthClass;
37use super::signature::ONION_BACKEND_NAME_MAX_BYTES;
38use super::sphinx::class::OnionLoopClass;
39use super::sphinx::layer::OnionApplication;
40use super::sphinx::layer::OnionArguments;
41use super::sphinx::layer::ONION_ARGUMENT_BYTES;
42use super::MAX_ONION_LOOP_SYMBOLS;
43use crate::error::Error;
44use crate::error::Result;
45
46const ONION_INVOKE_ARG_HEADER_BYTES: usize = 2;
48
49pub const ONION_INVOKE_MAX_CONSTANTS_BYTES: usize =
51 ONION_ARGUMENT_BYTES - ONION_INVOKE_ARG_HEADER_BYTES - 1;
52
53const _: () = assert!(OnionWidthClass::KiB16.bytes() <= OnionLoopClass::KiB64.value_capacity());
55const _: () =
57 assert!(ONION_INVOKE_ARG_HEADER_BYTES + ONION_BACKEND_NAME_MAX_BYTES < ONION_ARGUMENT_BYTES);
58
59#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
61pub enum OnionValueType {
62 Unit,
64 Fixed(OnionWidthClass),
66 Frame,
68}
69
70impl From<OnionInputType> for OnionValueType {
71 fn from(input: OnionInputType) -> Self {
72 match input {
73 OnionInputType::Unit => Self::Unit,
74 OnionInputType::Fixed(width) => Self::Fixed(width),
75 }
76 }
77}
78
79impl From<OnionWidthClass> for OnionValueType {
80 fn from(width: OnionWidthClass) -> Self {
81 Self::Fixed(width)
82 }
83}
84
85#[derive(Clone, Debug, Eq, PartialEq)]
92pub struct OnionInvokeArguments {
93 backend: OnionBackendName,
94 constants: Vec<u8>,
95}
96
97impl OnionInvokeArguments {
98 pub fn new(
100 backend: OnionBackendName,
101 constants: impl Into<Vec<u8>>,
102 ) -> std::result::Result<Self, OnionPipelineError> {
103 let constants = constants.into();
104 let used = ONION_INVOKE_ARG_HEADER_BYTES
105 .saturating_add(backend.as_str().len())
106 .saturating_add(constants.len());
107 if used > ONION_ARGUMENT_BYTES {
108 return Err(OnionPipelineError::ArgumentsTooWide {
109 backend_bytes: backend.as_str().len(),
110 constants_bytes: constants.len(),
111 capacity: ONION_ARGUMENT_BYTES - ONION_INVOKE_ARG_HEADER_BYTES,
112 });
113 }
114 Ok(Self { backend, constants })
115 }
116
117 pub const fn backend(&self) -> &OnionBackendName {
119 &self.backend
120 }
121
122 pub fn constants(&self) -> &[u8] {
124 self.constants.as_slice()
125 }
126
127 pub fn into_parts(self) -> (OnionBackendName, Vec<u8>) {
129 (self.backend, self.constants)
130 }
131
132 pub(crate) fn encode(&self) -> OnionArguments {
134 let mut bytes = [0_u8; ONION_ARGUMENT_BYTES];
135 let name = self.backend.as_str().as_bytes();
136 let constants = self.constants.as_slice();
137 bytes[0] = name.len() as u8;
138 bytes[1] = constants.len() as u8;
139 bytes
140 .iter_mut()
141 .skip(ONION_INVOKE_ARG_HEADER_BYTES)
142 .zip(name.iter().chain(constants.iter()))
143 .for_each(|(slot, byte)| *slot = *byte);
144 OnionArguments::new(bytes)
145 }
146
147 pub(crate) fn decode(arguments: &OnionArguments) -> Option<Self> {
149 let bytes = arguments.as_bytes();
150 let name_len = usize::from(bytes[0]);
151 let const_len = usize::from(bytes[1]);
152 if name_len == 0 || name_len > ONION_BACKEND_NAME_MAX_BYTES {
153 return None;
154 }
155 let name_end = ONION_INVOKE_ARG_HEADER_BYTES.checked_add(name_len)?;
156 let end = name_end.checked_add(const_len)?;
157 if bytes.get(end..)?.iter().any(|byte| *byte != 0) {
158 return None;
159 }
160 let name_str =
161 std::str::from_utf8(bytes.get(ONION_INVOKE_ARG_HEADER_BYTES..name_end)?).ok()?;
162 let backend = OnionBackendName::parse(name_str).ok()?;
163 let constants = bytes.get(name_end..end)?.to_vec();
164 Some(Self { backend, constants })
165 }
166}
167
168#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
170pub enum OnionPipelineError {
171 #[error("onion pipeline must apply at least one non-relay symbol")]
173 Empty,
174 #[error("onion pipeline has {symbols} symbols; maximum is {max_symbols}")]
176 TooManySymbols {
177 symbols: usize,
179 max_symbols: usize,
181 },
182 #[error("onion pipeline type mismatch: {left_out:?} cannot feed {right_in:?}")]
184 TypeMismatch {
185 left_out: OnionValueType,
187 right_in: OnionValueType,
189 },
190 #[error("world-facing onion symbol must be terminal")]
192 WorldFacingNotTerminal,
193 #[error("world-facing session symbol must stand alone (n = 1)")]
195 SessionSymbolMustStandAlone,
196 #[error(
198 "onion invoke arguments ({backend_bytes}B backend + {constants_bytes}B constants) exceed {capacity}B inline capacity"
199 )]
200 ArgumentsTooWide {
201 backend_bytes: usize,
203 constants_bytes: usize,
205 capacity: usize,
207 },
208}
209
210impl From<OnionPipelineError> for Error {
211 fn from(error: OnionPipelineError) -> Self {
212 Self::InvalidConfig(error.to_string())
213 }
214}
215
216#[derive(Clone, Debug, Eq, PartialEq)]
218pub struct OnionInvokeStage {
219 shape: OnionInvokeShape,
220 arguments: OnionInvokeArguments,
221}
222
223impl OnionInvokeStage {
224 pub fn new(
226 shape: OnionInvokeShape,
227 backend: OnionBackendName,
228 constants: impl Into<Vec<u8>>,
229 ) -> std::result::Result<Self, OnionPipelineError> {
230 Ok(Self {
231 shape,
232 arguments: OnionInvokeArguments::new(backend, constants)?,
233 })
234 }
235
236 pub const fn shape(&self) -> OnionInvokeShape {
238 self.shape
239 }
240
241 pub const fn backend(&self) -> &OnionBackendName {
243 self.arguments.backend()
244 }
245
246 pub fn constants(&self) -> &[u8] {
248 self.arguments.constants()
249 }
250
251 pub fn into_pipeline(self) -> OnionInvokePipeline {
253 OnionInvokePipeline { stages: vec![self] }
254 }
255
256 pub fn then(
258 self,
259 next: OnionInvokeStage,
260 ) -> std::result::Result<OnionInvokePipeline, OnionPipelineError> {
261 self.into_pipeline().then_stage(next)
262 }
263
264 pub(crate) fn to_application(&self) -> OnionApplication {
265 OnionApplication {
266 symbol: OnionShape::Invoke(self.shape),
267 arguments: self.arguments.encode(),
268 }
269 }
270}
271
272#[derive(Clone, Debug, Eq, PartialEq)]
278pub struct OnionInvokePipeline {
279 stages: Vec<OnionInvokeStage>,
280}
281
282impl OnionInvokePipeline {
283 pub fn from_stages(
286 stages: impl IntoIterator<Item = OnionInvokeStage>,
287 ) -> std::result::Result<Self, OnionPipelineError> {
288 let mut iter = stages.into_iter();
289 let first = iter.next().ok_or(OnionPipelineError::Empty)?;
290 iter.try_fold(first.into_pipeline(), Self::then_stage)
291 }
292
293 pub fn then_stage(
295 mut self,
296 next: OnionInvokeStage,
297 ) -> std::result::Result<Self, OnionPipelineError> {
298 let left_out = OnionValueType::Fixed(self.output());
299 let right_in = OnionValueType::from(next.shape.input());
300 if left_out != right_in {
301 return Err(OnionPipelineError::TypeMismatch { left_out, right_in });
302 }
303 let symbols = self.stages.len() + 1;
304 if symbols > MAX_ONION_LOOP_SYMBOLS {
305 return Err(OnionPipelineError::TooManySymbols {
306 symbols,
307 max_symbols: MAX_ONION_LOOP_SYMBOLS,
308 });
309 }
310 self.stages.push(next);
311 Ok(self)
312 }
313
314 pub fn then(self, other: Self) -> std::result::Result<Self, OnionPipelineError> {
316 other.stages.into_iter().try_fold(self, Self::then_stage)
317 }
318
319 pub fn stages(&self) -> &[OnionInvokeStage] {
321 self.stages.as_slice()
322 }
323
324 pub fn len(&self) -> usize {
326 self.stages.len()
327 }
328
329 pub fn is_empty(&self) -> bool {
331 self.stages.is_empty()
332 }
333
334 pub fn input(&self) -> OnionInputType {
336 self.stages
337 .first()
338 .map_or(OnionInputType::Unit, |stage| stage.shape.input())
339 }
340
341 pub fn input_bytes(&self) -> usize {
343 self.input().bytes()
344 }
345
346 pub fn output(&self) -> OnionWidthClass {
348 self.stages
349 .last()
350 .map_or(OnionWidthClass::B32, |stage| stage.shape.output())
351 }
352
353 pub fn output_bytes(&self) -> usize {
355 self.output().bytes()
356 }
357
358 pub fn total_latency(&self) -> Duration {
360 self.stages.iter().fold(Duration::ZERO, |acc, stage| {
361 acc.saturating_add(stage.shape.latency().duration())
362 })
363 }
364
365 pub fn symbol_word(&self) -> Vec<OnionInvokeShape> {
367 self.stages.iter().map(OnionInvokeStage::shape).collect()
368 }
369
370 pub fn required_symbols(&self) -> Vec<(OnionInvokeShape, OnionBackendName)> {
372 self.stages
373 .iter()
374 .map(|stage| (stage.shape, stage.backend().clone()))
375 .collect()
376 }
377
378 pub fn loop_class(&self) -> OnionLoopClass {
380 let widest = self.stages.iter().fold(self.input_bytes(), |acc, stage| {
381 acc.max(stage.shape.output_bytes())
382 });
383 OnionLoopClass::least_for_value_bytes(widest).unwrap_or(OnionLoopClass::MiB12)
384 }
385
386 pub(crate) fn applications(&self) -> Vec<OnionApplication> {
387 self.stages
388 .iter()
389 .map(OnionInvokeStage::to_application)
390 .collect()
391 }
392}
393
394impl From<OnionInvokeStage> for OnionInvokePipeline {
395 fn from(stage: OnionInvokeStage) -> Self {
396 stage.into_pipeline()
397 }
398}
399
400#[derive(Clone, Debug, Eq, PartialEq)]
402pub struct OnionPipelineTerm {
403 input: OnionValueType,
404 output: OnionValueType,
405 non_relay: Vec<TermAtom>,
406}
407
408#[derive(Clone, Debug, Eq, PartialEq)]
409enum TermAtom {
410 Invoke(OnionInvokeStage),
411 WorldFacing(OnionServiceName),
412}
413
414impl OnionPipelineTerm {
415 pub const fn relay(ty: OnionValueType) -> Self {
417 Self {
418 input: ty,
419 output: ty,
420 non_relay: Vec::new(),
421 }
422 }
423
424 pub fn invoke(stage: OnionInvokeStage) -> Self {
426 let input = OnionValueType::from(stage.shape.input());
427 let output = OnionValueType::Fixed(stage.shape.output());
428 Self {
429 input,
430 output,
431 non_relay: vec![TermAtom::Invoke(stage)],
432 }
433 }
434
435 pub fn world_facing(service: OnionServiceName) -> Self {
437 Self {
438 input: OnionValueType::Frame,
439 output: OnionValueType::Frame,
440 non_relay: vec![TermAtom::WorldFacing(service)],
441 }
442 }
443
444 pub const fn input_type(&self) -> OnionValueType {
446 self.input
447 }
448
449 pub const fn output_type(&self) -> OnionValueType {
451 self.output
452 }
453
454 pub fn then(mut self, next: Self) -> std::result::Result<Self, OnionPipelineError> {
456 if self.output != next.input {
457 return Err(OnionPipelineError::TypeMismatch {
458 left_out: self.output,
459 right_in: next.input,
460 });
461 }
462 if !next.non_relay.is_empty()
463 && self
464 .non_relay
465 .iter()
466 .any(|atom| matches!(atom, TermAtom::WorldFacing(_)))
467 {
468 return Err(OnionPipelineError::WorldFacingNotTerminal);
469 }
470 self.non_relay.extend(next.non_relay);
471 if self.non_relay.len() > 1
472 && matches!(self.non_relay.last(), Some(TermAtom::WorldFacing(_)))
473 {
474 return Err(OnionPipelineError::SessionSymbolMustStandAlone);
475 }
476 if self.non_relay.len() > MAX_ONION_LOOP_SYMBOLS {
477 return Err(OnionPipelineError::TooManySymbols {
478 symbols: self.non_relay.len(),
479 max_symbols: MAX_ONION_LOOP_SYMBOLS,
480 });
481 }
482 self.output = next.output;
483 Ok(self)
484 }
485
486 pub fn into_pipeline(self) -> std::result::Result<OnionPipeline, OnionPipelineError> {
489 if self.non_relay.is_empty() {
490 return Err(OnionPipelineError::Empty);
491 }
492 if self.non_relay.len() == 1 {
493 if let Some(TermAtom::WorldFacing(service)) = self.non_relay.first() {
494 return Ok(OnionPipeline::Session(service.clone()));
495 }
496 }
497 let mut stages = Vec::with_capacity(self.non_relay.len());
498 for (index, atom) in self.non_relay.into_iter().enumerate() {
499 match atom {
500 TermAtom::Invoke(stage) => stages.push(stage),
501 TermAtom::WorldFacing(_) => {
502 return Err(if index + 1 == stages.capacity() {
503 OnionPipelineError::SessionSymbolMustStandAlone
504 } else {
505 OnionPipelineError::WorldFacingNotTerminal
506 });
507 }
508 }
509 }
510 OnionInvokePipeline::from_stages(stages).map(OnionPipeline::Invoke)
511 }
512}
513
514#[derive(Clone, Debug, Eq, PartialEq)]
517pub enum OnionPipeline {
518 Invoke(OnionInvokePipeline),
520 Session(OnionServiceName),
522}
523
524impl OnionPipeline {
525 pub fn symbol_word(&self) -> Vec<OnionShape> {
527 match self {
528 Self::Invoke(pipeline) => pipeline
529 .symbol_word()
530 .into_iter()
531 .map(OnionShape::Invoke)
532 .collect(),
533 Self::Session(service) => vec![OnionShape::WorldFacing(service.clone())],
534 }
535 }
536}
537
538pub(crate) fn ensure_pipeline_input_width(
540 pipeline: &OnionInvokePipeline,
541 input: &[u8],
542) -> Result<()> {
543 let expected = pipeline.input_bytes();
544 if input.len() != expected {
545 return Err(Error::InvalidConfig(format!(
546 "onion pipeline expects {expected}-byte input, got {} bytes",
547 input.len()
548 )));
549 }
550 Ok(())
551}
552
553#[cfg(test)]
554mod tests {
555 use rand::SeedableRng;
556 use rand_chacha::ChaCha20Rng;
557 use rings_core::dht::Did;
558
559 use super::OnionInvokeArguments;
560 use super::OnionInvokePipeline;
561 use super::OnionInvokeStage;
562 use super::OnionPipeline;
563 use super::OnionPipelineError;
564 use super::OnionPipelineTerm;
565 use super::OnionValueType;
566 use crate::onion::signature::OnionBackendName;
567 use crate::onion::signature::OnionInputType;
568 use crate::onion::signature::OnionInvokeShape;
569 use crate::onion::signature::OnionLatencyClass;
570 use crate::onion::signature::OnionServiceName;
571 use crate::onion::signature::OnionShape;
572 use crate::onion::signature::OnionWidthClass;
573 use crate::onion::sphinx::builder::build_loop;
574 use crate::onion::sphinx::class::OnionLoopClass;
575 use crate::onion::sphinx::layer::OnionArguments;
576 use crate::onion::sphinx::layer::ONION_ARGUMENT_BYTES;
577 use crate::onion::tests::fixture::fixture_secret;
578 use crate::onion::tests::fixture::grid_expiry;
579 use crate::onion::tests::fixture::session_loop;
580 use crate::onion::OnionProcessEpoch;
581 use crate::onion::OnionRouteHop;
582
583 fn stage(
584 input: OnionInputType,
585 output: OnionWidthClass,
586 latency: OnionLatencyClass,
587 backend: &str,
588 constants: &[u8],
589 ) -> OnionInvokeStage {
590 OnionInvokeStage::new(
591 OnionInvokeShape::new(input, output, latency),
592 OnionBackendName::parse(backend).expect("backend"),
593 constants,
594 )
595 .expect("valid stage")
596 }
597
598 #[test]
601 fn test_invoke_arguments_are_canonical_and_hidden_from_symbol_word() {
602 let backend = OnionBackendName::parse("jev.typesafe").expect("backend");
603 let constants = vec![0x00, 0x11, 0x22, 0x00];
604 let args = OnionInvokeArguments::new(backend.clone(), constants.clone()).expect("fits");
605 let encoded = args.encode();
606 let decoded = OnionInvokeArguments::decode(&encoded).expect("decodes");
607 assert_eq!(decoded, args);
608 assert_eq!(decoded.encode(), encoded);
609
610 let mut non_canonical = *encoded.as_bytes();
612 non_canonical[ONION_ARGUMENT_BYTES - 1] = 1;
613 assert!(OnionInvokeArguments::decode(&OnionArguments::new(non_canonical)).is_none());
614
615 assert!(matches!(
617 OnionInvokeArguments::new(backend, vec![0xaa; 60]),
618 Err(OnionPipelineError::ArgumentsTooWide { .. })
619 ));
620
621 let p = stage(
623 OnionInputType::Fixed(OnionWidthClass::B32),
624 OnionWidthClass::B64,
625 OnionLatencyClass::Ms500,
626 "jev.typesafe",
627 b"secret-const",
628 )
629 .into_pipeline();
630 let word = OnionPipeline::Invoke(p).symbol_word();
631 assert_eq!(word.len(), 1);
632 assert!(matches!(word[0], OnionShape::Invoke(_)));
633 assert!(!word[0].to_string().contains("jev"));
634 }
635
636 #[test]
639 fn test_pipeline_type_and_position_checking() {
640 let only_relay = OnionPipelineTerm::relay(OnionValueType::Fixed(OnionWidthClass::B32))
642 .then(OnionPipelineTerm::relay(OnionValueType::Fixed(
643 OnionWidthClass::B32,
644 )))
645 .expect("relay ⋙ relay composes as term");
646 assert_eq!(only_relay.into_pipeline(), Err(OnionPipelineError::Empty));
647 assert_eq!(
648 OnionInvokePipeline::from_stages(Vec::new()),
649 Err(OnionPipelineError::Empty)
650 );
651
652 let f = stage(
654 OnionInputType::Fixed(OnionWidthClass::B32),
655 OnionWidthClass::B64,
656 OnionLatencyClass::Ms10,
657 "add",
658 b"1",
659 );
660 let g_bad = stage(
661 OnionInputType::Fixed(OnionWidthClass::B32),
662 OnionWidthClass::B32,
663 OnionLatencyClass::Ms10,
664 "mul",
665 b"2",
666 );
667 assert_eq!(
668 f.clone().then(g_bad),
669 Err(OnionPipelineError::TypeMismatch {
670 left_out: OnionValueType::Fixed(OnionWidthClass::B64),
671 right_in: OnionValueType::Fixed(OnionWidthClass::B32),
672 })
673 );
674
675 let tcp = OnionPipelineTerm::world_facing(OnionServiceName::tcp());
677 let https = OnionPipelineTerm::world_facing(OnionServiceName::https());
678 assert_eq!(
679 tcp.then(https),
680 Err(OnionPipelineError::WorldFacingNotTerminal)
681 );
682
683 let id_stage = || {
685 stage(
686 OnionInputType::Fixed(OnionWidthClass::B32),
687 OnionWidthClass::B32,
688 OnionLatencyClass::Ms10,
689 "step",
690 b"",
691 )
692 };
693 let four = OnionInvokePipeline::from_stages((0..4).map(|_| id_stage())).expect("4 fits");
694 assert_eq!(
695 four.then_stage(id_stage()),
696 Err(OnionPipelineError::TooManySymbols {
697 symbols: 5,
698 max_symbols: 4,
699 })
700 );
701 }
702
703 #[test]
706 fn test_identity_normal_form_and_associativity_laws() {
707 let f = stage(
708 OnionInputType::Unit,
709 OnionWidthClass::B32,
710 OnionLatencyClass::Ms10,
711 "seed",
712 b"a",
713 );
714 let g = stage(
715 OnionInputType::Fixed(OnionWidthClass::B32),
716 OnionWidthClass::B64,
717 OnionLatencyClass::Ms100,
718 "expand",
719 b"b",
720 );
721 let h = stage(
722 OnionInputType::Fixed(OnionWidthClass::B64),
723 OnionWidthClass::B256,
724 OnionLatencyClass::Ms500,
725 "finalize",
726 b"c",
727 );
728
729 let left = f
731 .clone()
732 .then(g.clone())
733 .expect("f ⋙ g")
734 .then_stage(h.clone())
735 .expect("(f ⋙ g) ⋙ h");
736 let right = f
737 .clone()
738 .into_pipeline()
739 .then(g.clone().then(h).expect("g ⋙ h"))
740 .expect("f ⋙ (g ⋙ h)");
741 assert_eq!(left, right);
742
743 let plain = f.clone().into_pipeline();
745 let wrapped_term = OnionPipelineTerm::relay(OnionValueType::Unit)
746 .then(OnionPipelineTerm::invoke(f))
747 .expect("relay ⋙ f")
748 .then(OnionPipelineTerm::relay(OnionValueType::Fixed(
749 OnionWidthClass::B32,
750 )))
751 .expect("(relay ⋙ f) ⋙ relay");
752 let OnionPipeline::Invoke(normalized) = wrapped_term.into_pipeline().expect("nf") else {
753 panic!("invoke pipeline");
754 };
755 assert_eq!(normalized, plain);
756
757 let hops = session_loop([1_u8, 2, 3, 4].map(|seed| {
758 OnionRouteHop::new(
759 Did::from(u32::from(seed)),
760 fixture_secret(seed).pubkey(),
761 OnionProcessEpoch::new([0x31; 16]),
762 )
763 }));
764 let built_plain = build_loop(
765 &hops,
766 &plain.applications(),
767 Did::from(99_u32),
768 plain.loop_class(),
769 grid_expiry(5),
770 b"",
771 &mut ChaCha20Rng::from_seed([0x77; 32]),
772 )
773 .expect("build plain");
774 let built_normalized = build_loop(
775 &hops,
776 &normalized.applications(),
777 Did::from(99_u32),
778 normalized.loop_class(),
779 grid_expiry(5),
780 b"",
781 &mut ChaCha20Rng::from_seed([0x77; 32]),
782 )
783 .expect("build normalized");
784 assert_eq!(
785 built_plain.cell.into_bytes(),
786 built_normalized.cell.into_bytes()
787 );
788 assert_eq!(built_plain.reply.tag, built_normalized.reply.tag);
789 }
790
791 #[test]
794 fn test_loop_class_selects_least_admissible_bucket() {
795 let small = stage(
796 OnionInputType::Fixed(OnionWidthClass::B32),
797 OnionWidthClass::KiB1,
798 OnionLatencyClass::Ms10,
799 "small",
800 b"",
801 )
802 .into_pipeline();
803 assert_eq!(small.loop_class(), OnionLoopClass::KiB16);
804
805 let wide = small
806 .then_stage(stage(
807 OnionInputType::Fixed(OnionWidthClass::KiB1),
808 OnionWidthClass::KiB16,
809 OnionLatencyClass::Ms100,
810 "wide",
811 b"",
812 ))
813 .expect("compose wide");
814 assert_eq!(wide.loop_class(), OnionLoopClass::KiB64);
815 }
816}