mixnet/core/cover.rs
1// Copyright 2022 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Mixnet cover packet generation.
22
23use super::{
24 packet_queues::AddressedPacket,
25 sphinx::build_cover_packet,
26 topology::{NetworkStatus, RouteGenerator, RouteKind, Topology, TopologyErr},
27 util::default_boxed_array,
28};
29use arrayvec::ArrayVec;
30use rand::{CryptoRng, Rng};
31
32#[derive(PartialEq, Eq)]
33pub enum CoverKind {
34 Drop,
35 Loop,
36}
37
38pub fn gen_cover_packet<X>(
39 rng: &mut (impl Rng + CryptoRng),
40 topology: &Topology<X>,
41 ns: &dyn NetworkStatus,
42 kind: CoverKind,
43 num_hops: usize,
44) -> Result<AddressedPacket, TopologyErr> {
45 // Generate route
46 let route_generator = RouteGenerator::new(topology, ns);
47 let route_kind = match kind {
48 CoverKind::Drop => RouteKind::ToMixnode(route_generator.choose_destination_index(rng)?),
49 CoverKind::Loop => RouteKind::Loop,
50 };
51 let mut targets = ArrayVec::new();
52 let mut their_kx_publics = ArrayVec::new();
53 let first_mixnode_index = route_generator.gen_route(
54 &mut targets,
55 &mut their_kx_publics,
56 rng,
57 route_kind,
58 num_hops,
59 )?;
60 let peer_id = topology.mixnode_index_to_peer_id(first_mixnode_index)?;
61
62 // Build packet
63 let mut packet = default_boxed_array();
64 build_cover_packet(&mut packet, rng, &targets, &their_kx_publics, None);
65
66 Ok(AddressedPacket { peer_id, packet })
67}