mixnet/core/
request_builder.rs1use super::{
24 packet_queues::AddressedPacket,
25 sphinx::{
26 build_surb, complete_request_packet, mut_payload_data, Delay, MixnodeIndex, PayloadData,
27 Surb, SurbId, SurbPayloadEncryptionKeys,
28 },
29 topology::{NetworkStatus, RouteGenerator, RouteKind, Topology, TopologyErr},
30 util::default_boxed_array,
31};
32use arrayvec::ArrayVec;
33use rand::{CryptoRng, Rng};
34
35pub struct RouteMetrics {
36 pub num_hops: usize,
37 pub forwarding_delay: Delay,
38}
39
40pub struct RequestBuilder<'topology, X> {
41 route_generator: RouteGenerator<'topology, X>,
42 destination_index: MixnodeIndex,
43}
44
45impl<'topology, X> RequestBuilder<'topology, X> {
46 pub fn new(
47 rng: &mut (impl Rng + CryptoRng),
48 topology: &'topology Topology<X>,
49 ns: &dyn NetworkStatus,
50 destination_index: Option<MixnodeIndex>,
51 ) -> Result<Self, TopologyErr> {
52 let route_generator = RouteGenerator::new(topology, ns);
53 let destination_index = match destination_index {
54 Some(index) => index,
55 None => route_generator.choose_destination_index(rng)?,
56 };
57 Ok(Self { route_generator, destination_index })
58 }
59
60 pub fn destination_index(&self) -> MixnodeIndex {
61 self.destination_index
62 }
63
64 pub fn build_packet<R: Rng + CryptoRng>(
65 &self,
66 rng: &mut R,
67 write_payload_data: impl FnOnce(&mut PayloadData, &mut R) -> Result<(), TopologyErr>,
68 num_hops: usize,
69 ) -> Result<(AddressedPacket, RouteMetrics), TopologyErr> {
70 let mut targets = ArrayVec::new();
72 let mut their_kx_publics = ArrayVec::new();
73 let first_mixnode_index = self.route_generator.gen_route(
74 &mut targets,
75 &mut their_kx_publics,
76 rng,
77 RouteKind::ToMixnode(self.destination_index),
78 num_hops,
79 )?;
80 let peer_id =
81 self.route_generator.topology().mixnode_index_to_peer_id(first_mixnode_index)?;
82
83 let mut packet = default_boxed_array();
85 write_payload_data(mut_payload_data(&mut packet), rng)?;
86 let forwarding_delay =
87 complete_request_packet(&mut packet, rng, &targets, &their_kx_publics);
88
89 let packet = AddressedPacket { peer_id, packet };
90 let metrics = RouteMetrics { num_hops: their_kx_publics.len(), forwarding_delay };
91 Ok((packet, metrics))
92 }
93
94 pub fn build_surb(
95 &self,
96 surb: &mut Surb,
97 payload_encryption_keys: &mut SurbPayloadEncryptionKeys,
98 rng: &mut (impl Rng + CryptoRng),
99 id: &SurbId,
100 num_hops: usize,
101 ) -> Result<RouteMetrics, TopologyErr> {
102 let mut targets = ArrayVec::new();
104 let mut their_kx_publics = ArrayVec::new();
105 let first_mixnode_index = self.route_generator.gen_route(
106 &mut targets,
107 &mut their_kx_publics,
108 rng,
109 RouteKind::FromMixnode(self.destination_index),
110 num_hops,
111 )?;
112
113 let forwarding_delay = build_surb(
115 surb,
116 payload_encryption_keys,
117 rng,
118 first_mixnode_index,
119 &targets,
120 &their_kx_publics,
121 id,
122 );
123
124 Ok(RouteMetrics { num_hops: their_kx_publics.len(), forwarding_delay })
125 }
126}