nym-sphinx 3.0.1

Top-level crate for sphinx packets as used by the Nym mixnet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0

use crate::NymPayloadBuilder;
use crate::message::{ACK_OVERHEAD, NymMessage};
use nym_crypto::Digest;
use nym_crypto::asymmetric::x25519;
use nym_lp_data::packet::LpFrame;
use nym_lp_data::packet::frame::{ForwardSphinxFrameAttributes, LpFrameKind};
use nym_sphinx_acknowledgements::AckKey;
use nym_sphinx_acknowledgements::surb_ack::SurbAck;
use nym_sphinx_addressing::clients::Recipient;
use nym_sphinx_addressing::nodes::NymNodeRoutingAddress;
use nym_sphinx_anonymous_replies::reply_surb::ReplySurb;
use nym_sphinx_chunking::fragment::{Fragment, FragmentIdentifier};
use nym_sphinx_forwarding::packet::MixPacket;
use nym_sphinx_params::packet_sizes::PacketSize;
use nym_sphinx_params::{PacketType, ReplySurbKeyDigestAlgorithm, SphinxKeyRotation};
use nym_sphinx_types::{
    Delay, Node as SphinxNode, NymPacket, NymPacketError, PAYLOAD_OVERHEAD_SIZE,
};
use nym_topology::lp::LpRouteProvider;
use nym_topology::{NodeId, NymRouteProvider, NymTopologyError};
use rand::{CryptoRng, Rng, RngExt, SeedableRng};
use rand_chacha::ChaCha8Rng;
use tracing::*;

use nym_sphinx_anonymous_replies::ReplySurbWithKeyRotation;
use nym_sphinx_chunking::monitoring;
use std::time::Duration;

pub(crate) mod payload;

/// Fully packed and prepared [`Fragment`] that is sent to its first hop inside an LP frame.
///
/// No `total_delay` and no `fragment_identifier`: both exist to track an acknowledgement, and this
/// path carries none.
pub struct PreparedLpFragment {
    /// The packet and the address of the node it goes to first.
    pub mix_packet: MixPacket,

    /// That same first hop, named the way an LP frame names it.
    pub first_hop_id: NodeId,
}

impl PreparedLpFragment {
    /// Wrap the packet in the frame that tells a gateway to forward it.
    pub fn into_lp_frame(self) -> Result<LpFrame, NymPacketError> {
        let attributes = ForwardSphinxFrameAttributes {
            key_rotation: self.mix_packet.key_rotation(),
            next_hop: self.first_hop_id,
        };

        Ok(LpFrame::new_with_attributes(
            LpFrameKind::ForwardSphinxPacket,
            attributes,
            self.mix_packet.into_packet().to_bytes()?,
        ))
    }
}

/// Represents fully packed and prepared [`Fragment`] that can be sent through the mix network.
pub struct PreparedFragment {
    /// Indicates the total expected round-trip time, i.e. delay from the sending of this message
    /// until receiving the acknowledgement included inside of it.
    pub total_delay: Delay,

    /// Indicates all data required to serialize and forward the data. It contains the actual
    /// address of the node to which the message should be sent, the actual 'chunk' of the message
    /// going through the mix network and also the 'mode' of the packet, i.e. VPN or Mix.
    pub mix_packet: MixPacket,

    /// Identifier to uniquely identify a fragment.
    pub fragment_identifier: FragmentIdentifier,
}

impl From<PreparedFragment> for MixPacket {
    fn from(value: PreparedFragment) -> Self {
        value.mix_packet
    }
}

// this is extracted into a trait with default implementation to remove duplicate code
// (which we REALLY want to avoid with crypto)
pub trait FragmentPreparer {
    type Rng: CryptoRng + Rng;

    fn mix_hops_disabled(&self) -> bool {
        // Unless otherwise configured, mix hops are enabled
        false
    }

    fn deterministic_route_selection(&self) -> bool;
    fn rng(&mut self) -> &mut Self::Rng;
    fn nonce(&self) -> i32;
    fn average_packet_delay(&self) -> Duration;
    fn average_ack_delay(&self) -> Duration;

    fn generate_surb_ack_legacy(
        &mut self,
        recipient: &Recipient,
        fragment_id: FragmentIdentifier,
        topology: &NymRouteProvider,
        ack_key: &AckKey,
        packet_type: PacketType,
    ) -> Result<SurbAck, NymTopologyError> {
        let ack_delay = self.average_ack_delay();
        let disable_mix_hops = self.mix_hops_disabled();

        SurbAck::construct_legacy(
            self.rng(),
            recipient,
            ack_key,
            fragment_id.to_bytes(),
            ack_delay,
            topology,
            packet_type,
            disable_mix_hops,
        )
    }

    /// The procedure is as follows:
    /// For each fragment:
    /// - compute SURB_ACK
    /// - generate (x, g^x)
    /// - obtain key k from the reply-surb which was computed as follows:
    ///   k = KDF(remote encryption key ^ x) this is equivalent to KDF( dh(remote, x) )
    /// - compute v_b = AES-128-CTR(k, serialized_fragment)
    /// - compute vk_b = H(k) || v_b
    /// - compute sphinx_plaintext = SURB_ACK || H(k) || v_b
    /// - compute sphinx_packet by applying the reply surb on the sphinx_plaintext
    fn prepare_reply_chunk_for_sending(
        &mut self,
        fragment: Fragment,
        topology: &NymRouteProvider,
        ack_key: &AckKey,
        reply_surb: ReplySurbWithKeyRotation,
        packet_sender: &Recipient,
        packet_type: PacketType,
    ) -> Result<PreparedFragment, NymTopologyError> {
        debug!("Preparing reply chunk for sending");

        // each reply attaches the digest of the encryption key so that the recipient could
        // lookup correct key for decryption,
        let reply_overhead = ReplySurbKeyDigestAlgorithm::output_size();
        let PacketType::Mix = packet_type else {
            return Err(NymTopologyError::PacketTypeNotSupported);
        };
        let expected_plaintext = fragment.serialized_size() + ACK_OVERHEAD + reply_overhead;

        // the reason we're unwrapping (or rather 'expecting') here rather than handling the error
        // more gracefully is that this error should never be reached as it implies incorrect chunking
        // reply packets are always Sphinx
        let packet_size = PacketSize::get_type_from_plaintext(expected_plaintext, PacketType::Mix)
            .expect("the message has been incorrectly fragmented");

        // this is not going to be accurate by any means. but that's the best estimation we can do
        let expected_forward_delay =
            Delay::new_from_millis((self.average_packet_delay().as_millis() * 3) as u64);

        let fragment_identifier = fragment.fragment_identifier();

        // create an ack
        let surb_ack = self.generate_surb_ack_legacy(
            packet_sender,
            fragment_identifier,
            topology,
            ack_key,
            packet_type,
        )?;
        let ack_delay = surb_ack.expected_total_delay();

        let packet_payload = match NymPayloadBuilder::new(fragment, surb_ack)
            .build_reply(reply_surb.encryption_key())
        {
            Ok(payload) => payload,
            Err(_e) => return Err(NymTopologyError::PayloadBuilder),
        };

        // the unwrap here is fine as the failures can only originate from attempting to use invalid payload lengths
        // and we just very carefully constructed a (presumably) valid one
        let applied_surb = reply_surb
            .apply_surb(packet_payload, packet_size, packet_type)
            .unwrap();

        Ok(PreparedFragment {
            // the round-trip delay is the sum of delays of all hops on the forward route as
            // well as the total delay of the ack packet.
            // we don't know the delays inside the reply surbs so we use best-effort estimation from our poisson distribution
            total_delay: expected_forward_delay + ack_delay,
            mix_packet: MixPacket::from_applied_surb(applied_surb, packet_type),
            fragment_identifier,
        })
    }

    /// Tries to convert this [`Fragment`] into a [`SphinxPacket`] that can be sent through the Nym mix-network,
    /// such that it contains required SURB-ACK and public component of the ephemeral key used to
    /// derive the shared key.
    /// Also all the data, apart from the said public component, is encrypted with an ephemeral shared key.
    /// This method can fail if the provided network topology is invalid.
    /// It returns total expected delay as well as the [`SphinxPacket`] (including first hop address)
    /// to be sent through the network.
    ///
    /// The procedure is as follows:
    /// For each fragment:
    /// - compute SURB_ACK
    /// - generate (x, g^x)
    /// - compute k = KDF(remote encryption key ^ x) this is equivalent to KDF( dh(remote, x) )
    /// - compute v_b = AES-128-CTR(k, serialized_fragment)
    /// - compute vk_b = g^x || v_b
    /// - compute sphinx_plaintext = SURB_ACK || g^x || v_b
    /// - compute sphinx_packet = Sphinx(recipient, sphinx_plaintext)
    #[allow(clippy::too_many_arguments)]
    fn prepare_chunk_for_sending(
        &mut self,
        fragment: Fragment,
        topology: &NymRouteProvider,
        ack_key: &AckKey,
        packet_sender: &Recipient,
        packet_recipient: &Recipient,
        packet_type: PacketType,
    ) -> Result<PreparedFragment, NymTopologyError> {
        debug!("Preparing chunk for sending");
        // each plain or repliable packet (i.e. not a reply) attaches an ephemeral public key so that the recipient
        // could perform diffie-hellman with its own keys followed by a kdf to re-derive
        // the packet encryption key

        let fragment_header = fragment.header();
        let destination = packet_recipient.gateway();
        monitoring::fragment_sent(&fragment, self.nonce(), destination);

        let non_reply_overhead = x25519::PUBLIC_KEY_SIZE;
        let PacketType::Mix = packet_type else {
            return Err(NymTopologyError::PacketTypeNotSupported);
        };
        let expected_plaintext = fragment.serialized_size() + ACK_OVERHEAD + non_reply_overhead;

        // the reason we're unwrapping (or rather 'expecting') here rather than handling the error
        // more gracefully is that this error should never be reached as it implies incorrect chunking
        let packet_size = PacketSize::get_type_from_plaintext(expected_plaintext, packet_type)
            .expect("the message has been incorrectly fragmented");

        let rotation_id = topology.current_key_rotation();
        let sphinx_key_rotation = SphinxKeyRotation::from(rotation_id);

        let fragment_identifier = fragment.fragment_identifier();

        // create an ack
        let surb_ack = self.generate_surb_ack_legacy(
            packet_sender,
            fragment_identifier,
            topology,
            ack_key,
            packet_type,
        )?;
        let ack_delay = surb_ack.expected_total_delay();

        let packet_payload = match NymPayloadBuilder::new(fragment, surb_ack)
            .build_regular(self.rng(), packet_recipient.encryption_key())
        {
            Ok(payload) => payload,
            Err(_e) => return Err(NymTopologyError::PayloadBuilder),
        };

        // generate pseudorandom route for the packet. Unless mix hops are disabled then build an empty route.
        trace!("Preparing chunk for sending");
        let route = if self.mix_hops_disabled() {
            topology.empty_route_to_egress(destination)?
        } else if self.deterministic_route_selection() {
            trace!("using deterministic route selection");
            let seed = fragment_header.seed().wrapping_mul(self.nonce());
            let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
            topology.random_route_to_egress(&mut rng, destination)?
        } else {
            trace!("using pseudorandom route selection");
            topology.random_route_to_egress(self.rng(), destination)?
        };

        let destination = packet_recipient.as_sphinx_destination();

        // including set of delays
        let delays =
            nym_sphinx_routing::generate_hop_delays(self.average_packet_delay(), route.len());

        // create the actual sphinx packet here. With valid route and correct payload size,
        // there's absolutely no reason for this call to fail.
        #[allow(deprecated)]
        let packet = match packet_type {
            PacketType::Outfox => return Err(NymTopologyError::PacketTypeNotSupported),
            PacketType::Mix => NymPacket::sphinx_build_legacy(
                packet_size.payload_size(),
                packet_payload,
                &route,
                &destination,
                &delays,
            )?,
        };

        // from the previously constructed route extract the first hop
        let first_hop_address =
            NymNodeRoutingAddress::try_from(route.first().unwrap().address).unwrap();

        Ok(PreparedFragment {
            // the round-trip delay is the sum of delays of all hops on the forward route as
            // well as the total delay of the ack packet.
            // note that the last hop of the packet is a gateway that does not do any delays
            total_delay: delays.iter().take(delays.len() - 1).sum::<Delay>() + ack_delay,
            mix_packet: MixPacket::new(first_hop_address, packet, packet_type, sphinx_key_rotation),
            fragment_identifier,
        })
    }

    /// As [`Self::prepare_chunk_for_sending`], but for the Lewes Protocol path.
    ///
    /// Three differences, all following from the recipient client being the **last sphinx hop**
    /// rather than a destination behind a gateway that does final-hop processing:
    ///
    /// 1. **No SURB-ack.** There is no gateway to peel one off and send it back, and the recipient
    ///    reads the payload directly - a leading ack would simply corrupt the message. The packet
    ///    is sized without [`ACK_OVERHEAD`] accordingly.
    /// 2. **No payload wrapper.** The ephemeral-DH layer that [`NymPayloadBuilder`] adds exists so
    ///    that a gateway performing final-hop processing cannot read the message. Here the
    ///    recipient performs it, so sphinx's own final layer already gives that and the payload is
    ///    the serialised [`Fragment`] alone.
    /// 3. **The route ends at the recipient**, appended as a hop, rather than at its egress
    ///    gateway.
    ///
    /// Returns the first hop's [`NodeId`] alongside the packet: an LP frame names its next hop by
    /// id, not by address, and the id is known here because the route was chosen from
    /// [`RoutingNode`]s. Recovering it afterwards would mean searching the topology by address,
    /// which it does not index.
    ///
    /// [`RoutingNode`]: nym_topology::RoutingNode
    fn prepare_chunk_for_lp(
        &mut self,
        fragment: Fragment,
        topology: &LpRouteProvider,
        packet_recipient: &Recipient,
    ) -> Result<PreparedLpFragment, NymTopologyError> {
        debug!("Preparing chunk for LP sending");

        let fragment_header = fragment.header();
        let destination = packet_recipient.gateway();
        monitoring::fragment_sent(&fragment, self.nonce(), destination);

        // the fragment fills the sphinx plaintext exactly, so the payload is that plus what the
        // sphinx layer wraps it in - which is what looking the size up as a `PacketSize` would
        // arrive at, without requiring it to be one of that fixed set. On this path it is not: LP
        // chunks to whatever its frame budget leaves.
        let payload_size = fragment.serialized_size() + PAYLOAD_OVERHEAD_SIZE;

        let sphinx_key_rotation = SphinxKeyRotation::from(topology.current_key_rotation());

        let packet_payload = fragment.into_bytes();

        // generate pseudorandom route for the packet. Unless mix hops are disabled then build an empty route.

        trace!("Preparing chunk for sending");
        // the path runs through the mix layers and ends at the recipient's egress gateway, which is
        // the hop that can actually reach them
        let mix_path = if self.mix_hops_disabled() {
            // the egress is the whole path
            topology.empty_path_to_egress(destination)?
        } else if self.deterministic_route_selection() {
            trace!("using deterministic route selection");
            let seed = fragment_header.seed().wrapping_mul(self.nonce());
            let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
            topology.random_path_to_egress(&mut rng, destination)?
        } else {
            trace!("using pseudorandom route selection");
            topology.random_path_to_egress(self.rng(), destination)?
        };

        let first_hop_id = mix_path
            .first()
            .ok_or(NymTopologyError::NoMixnodesAvailable)?
            .node_id;

        // an `LpRoutingNode` carries no mix address at all, so this cannot name the legacy listener
        let mut route = mix_path
            .into_iter()
            .map(Into::into)
            .collect::<Vec<SphinxNode>>();

        // the recipient is a hop, not merely the destination: on this path it is the one that
        // performs final-hop processing
        // SAFETY: a client address fits the sphinx addressing scheme
        #[expect(clippy::unwrap_used)]
        route.push(SphinxNode::new(
            packet_recipient.as_sphinx_hop().try_into().unwrap(),
            (*packet_recipient.encryption_key()).into(),
        ));

        let delays =
            nym_sphinx_routing::generate_hop_delays(self.average_packet_delay(), route.len());

        // create the actual sphinx packet here. With valid route and correct payload size,
        // there's absolutely no reason for this call to fail.
        let packet = NymPacket::sphinx_build(
            payload_size,
            packet_payload,
            &route,
            &packet_recipient.as_sphinx_destination(),
            &delays,
        )?;

        // from the previously constructed route extract the first hop
        // SAFETY: the route is non-empty, having just been built with at least the recipient
        #[expect(clippy::unwrap_used)]
        let first_hop_address =
            NymNodeRoutingAddress::try_from(route.first().unwrap().address).unwrap();

        Ok(PreparedLpFragment {
            mix_packet: MixPacket::new(
                first_hop_address,
                packet,
                PacketType::Mix,
                sphinx_key_rotation,
            ),
            first_hop_id,
        })
    }

    fn pad_and_split_message(
        &mut self,
        message: NymMessage,
        packet_size: PacketSize,
    ) -> Vec<Fragment> {
        let plaintext_per_packet = message.available_sphinx_plaintext_per_packet(packet_size);

        message
            .pad_to_full_packet_lengths(plaintext_per_packet)
            .split_into_fragments(self.rng(), plaintext_per_packet)
    }
}

/// Prepares the message that is to be sent through the mix network.
///
/// Prepares the message that is to be sent through the mix network by attaching
/// an optional reply-SURB, padding it to appropriate length, encrypting its content,
/// and chunking into appropriate size [`Fragment`]s.
#[derive(Clone)]
#[must_use]
pub struct MessagePreparer<R> {
    /// Instance of a cryptographically secure random number generator.
    rng: R,

    /// Specify whether route selection should be determined by the packet header.
    deterministic_route_selection: bool,

    /// Address of this client which also represent an address to which all acknowledgements
    /// and surb-based are going to be sent.
    sender_address: Recipient,

    /// Average delay a data packet is going to get delay at a single mixnode.
    average_packet_delay: Duration,

    /// Average delay an acknowledgement packet is going to get delay at a single mixnode.
    average_ack_delay: Duration,

    nonce: i32,

    /// Indicates whether to mix hops or not. If mix hops are enabled, traffic
    /// will be routed as usual, to the entry gateway, through three mix nodes, egressing
    /// through the exit gateway. If mix hops are disabled, traffic will be routed directly
    /// from the entry gateway to the exit gateway, bypassing the mix nodes.
    pub disable_mix_hops: bool,
}

impl<R> MessagePreparer<R>
where
    R: CryptoRng + Rng,
{
    pub fn new(
        rng: R,
        deterministic_route_selection: bool,
        sender_address: Recipient,
        average_packet_delay: Duration,
        average_ack_delay: Duration,
        disable_mix_hops: bool,
    ) -> Self {
        let mut rng = rng;
        let nonce = rng.random();
        MessagePreparer {
            rng,
            deterministic_route_selection,
            sender_address,
            average_packet_delay,
            average_ack_delay,
            nonce,
            disable_mix_hops,
        }
    }

    /// Overwrites existing sender address with the provided value.
    pub fn set_sender_address(&mut self, sender_address: Recipient) {
        self.sender_address = sender_address;
    }

    pub fn generate_reply_surbs(
        &mut self,
        amount: usize,
        topology: &NymRouteProvider,
    ) -> Result<Vec<ReplySurbWithKeyRotation>, NymTopologyError> {
        let mut reply_surbs = Vec::with_capacity(amount);
        let disabled_mix_hops = self.mix_hops_disabled();

        let key_rotation = SphinxKeyRotation::from(topology.current_key_rotation());

        for _ in 0..amount {
            let reply_surb = ReplySurb::construct(
                &mut self.rng,
                &self.sender_address,
                self.average_packet_delay,
                topology,
                disabled_mix_hops,
            )?
            .with_key_rotation(key_rotation);
            reply_surbs.push(reply_surb)
        }

        Ok(reply_surbs)
    }

    pub fn prepare_reply_chunk_for_sending(
        &mut self,
        fragment: Fragment,
        topology: &NymRouteProvider,
        ack_key: &AckKey,
        reply_surb: ReplySurbWithKeyRotation,
        packet_type: PacketType,
    ) -> Result<PreparedFragment, NymTopologyError> {
        let sender = self.sender_address;

        <Self as FragmentPreparer>::prepare_reply_chunk_for_sending(
            self,
            fragment,
            topology,
            ack_key,
            reply_surb,
            &sender,
            packet_type,
        )
    }

    pub fn prepare_chunk_for_sending(
        &mut self,
        fragment: Fragment,
        topology: &NymRouteProvider,
        ack_key: &AckKey,
        packet_recipient: &Recipient,
        packet_type: PacketType,
    ) -> Result<PreparedFragment, NymTopologyError> {
        let sender = self.sender_address;

        <Self as FragmentPreparer>::prepare_chunk_for_sending(
            self,
            fragment,
            topology,
            ack_key,
            &sender,
            packet_recipient,
            packet_type,
        )
    }

    /// Prepare a chunk for the Lewes Protocol path: no SURB-ack, and the recipient is the last hop.
    ///
    /// See [`FragmentPreparer::prepare_chunk_for_lp`].
    pub fn prepare_chunk_for_lp(
        &mut self,
        fragment: Fragment,
        topology: &LpRouteProvider,
        packet_recipient: &Recipient,
    ) -> Result<PreparedLpFragment, NymTopologyError> {
        <Self as FragmentPreparer>::prepare_chunk_for_lp(self, fragment, topology, packet_recipient)
    }

    /// Construct an acknowledgement SURB for the given [`FragmentIdentifier`]
    pub fn generate_surb_ack_legacy(
        &mut self,
        fragment_id: FragmentIdentifier,
        topology: &NymRouteProvider,
        ack_key: &AckKey,
        packet_type: PacketType,
    ) -> Result<SurbAck, NymTopologyError> {
        let sender = self.sender_address;
        <Self as FragmentPreparer>::generate_surb_ack_legacy(
            self,
            &sender,
            fragment_id,
            topology,
            ack_key,
            packet_type,
        )
    }

    pub fn pad_and_split_message(
        &mut self,
        message: NymMessage,
        packet_size: PacketSize,
    ) -> Vec<Fragment> {
        <Self as FragmentPreparer>::pad_and_split_message(self, message, packet_size)
    }
}

impl<R: CryptoRng + Rng> FragmentPreparer for MessagePreparer<R> {
    type Rng = R;

    fn mix_hops_disabled(&self) -> bool {
        self.disable_mix_hops
    }

    fn deterministic_route_selection(&self) -> bool {
        self.deterministic_route_selection
    }

    fn rng(&mut self) -> &mut Self::Rng {
        &mut self.rng
    }

    fn nonce(&self) -> i32 {
        self.nonce
    }

    fn average_packet_delay(&self) -> Duration {
        self.average_packet_delay
    }

    fn average_ack_delay(&self) -> Duration {
        self.average_ack_delay
    }
}

/*
   And for completion reconstruction:
   1. receive unwrapped sphinx packet: g^x || v_b
   2. recompute k = KDF(g^x * our encryption key)
   3. original_fragment = AES(k, v_b)
   4. deal with fragment as before
   5. on full message reconstruction output (message, Option<reply_surb>)
*/