Skip to main content

nym_sphinx/preparer/
mod.rs

1// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::NymPayloadBuilder;
5use crate::message::{ACK_OVERHEAD, NymMessage};
6use nym_crypto::Digest;
7use nym_crypto::asymmetric::x25519;
8use nym_lp_data::packet::LpFrame;
9use nym_lp_data::packet::frame::{ForwardSphinxFrameAttributes, LpFrameKind};
10use nym_sphinx_acknowledgements::AckKey;
11use nym_sphinx_acknowledgements::surb_ack::SurbAck;
12use nym_sphinx_addressing::clients::Recipient;
13use nym_sphinx_addressing::nodes::NymNodeRoutingAddress;
14use nym_sphinx_anonymous_replies::reply_surb::ReplySurb;
15use nym_sphinx_chunking::fragment::{Fragment, FragmentIdentifier};
16use nym_sphinx_forwarding::packet::MixPacket;
17use nym_sphinx_params::packet_sizes::PacketSize;
18use nym_sphinx_params::{PacketType, ReplySurbKeyDigestAlgorithm, SphinxKeyRotation};
19use nym_sphinx_types::{
20    Delay, Node as SphinxNode, NymPacket, NymPacketError, PAYLOAD_OVERHEAD_SIZE,
21};
22use nym_topology::lp::LpRouteProvider;
23use nym_topology::{NodeId, NymRouteProvider, NymTopologyError};
24use rand::{CryptoRng, Rng, RngExt, SeedableRng};
25use rand_chacha::ChaCha8Rng;
26use tracing::*;
27
28use nym_sphinx_anonymous_replies::ReplySurbWithKeyRotation;
29use nym_sphinx_chunking::monitoring;
30use std::time::Duration;
31
32pub(crate) mod payload;
33
34/// Fully packed and prepared [`Fragment`] that is sent to its first hop inside an LP frame.
35///
36/// No `total_delay` and no `fragment_identifier`: both exist to track an acknowledgement, and this
37/// path carries none.
38pub struct PreparedLpFragment {
39    /// The packet and the address of the node it goes to first.
40    pub mix_packet: MixPacket,
41
42    /// That same first hop, named the way an LP frame names it.
43    pub first_hop_id: NodeId,
44}
45
46impl PreparedLpFragment {
47    /// Wrap the packet in the frame that tells a gateway to forward it.
48    pub fn into_lp_frame(self) -> Result<LpFrame, NymPacketError> {
49        let attributes = ForwardSphinxFrameAttributes {
50            key_rotation: self.mix_packet.key_rotation(),
51            next_hop: self.first_hop_id,
52        };
53
54        Ok(LpFrame::new_with_attributes(
55            LpFrameKind::ForwardSphinxPacket,
56            attributes,
57            self.mix_packet.into_packet().to_bytes()?,
58        ))
59    }
60}
61
62/// Represents fully packed and prepared [`Fragment`] that can be sent through the mix network.
63pub struct PreparedFragment {
64    /// Indicates the total expected round-trip time, i.e. delay from the sending of this message
65    /// until receiving the acknowledgement included inside of it.
66    pub total_delay: Delay,
67
68    /// Indicates all data required to serialize and forward the data. It contains the actual
69    /// address of the node to which the message should be sent, the actual 'chunk' of the message
70    /// going through the mix network and also the 'mode' of the packet, i.e. VPN or Mix.
71    pub mix_packet: MixPacket,
72
73    /// Identifier to uniquely identify a fragment.
74    pub fragment_identifier: FragmentIdentifier,
75}
76
77impl From<PreparedFragment> for MixPacket {
78    fn from(value: PreparedFragment) -> Self {
79        value.mix_packet
80    }
81}
82
83// this is extracted into a trait with default implementation to remove duplicate code
84// (which we REALLY want to avoid with crypto)
85pub trait FragmentPreparer {
86    type Rng: CryptoRng + Rng;
87
88    fn mix_hops_disabled(&self) -> bool {
89        // Unless otherwise configured, mix hops are enabled
90        false
91    }
92
93    fn deterministic_route_selection(&self) -> bool;
94    fn rng(&mut self) -> &mut Self::Rng;
95    fn nonce(&self) -> i32;
96    fn average_packet_delay(&self) -> Duration;
97    fn average_ack_delay(&self) -> Duration;
98
99    fn generate_surb_ack_legacy(
100        &mut self,
101        recipient: &Recipient,
102        fragment_id: FragmentIdentifier,
103        topology: &NymRouteProvider,
104        ack_key: &AckKey,
105        packet_type: PacketType,
106    ) -> Result<SurbAck, NymTopologyError> {
107        let ack_delay = self.average_ack_delay();
108        let disable_mix_hops = self.mix_hops_disabled();
109
110        SurbAck::construct_legacy(
111            self.rng(),
112            recipient,
113            ack_key,
114            fragment_id.to_bytes(),
115            ack_delay,
116            topology,
117            packet_type,
118            disable_mix_hops,
119        )
120    }
121
122    /// The procedure is as follows:
123    /// For each fragment:
124    /// - compute SURB_ACK
125    /// - generate (x, g^x)
126    /// - obtain key k from the reply-surb which was computed as follows:
127    ///   k = KDF(remote encryption key ^ x) this is equivalent to KDF( dh(remote, x) )
128    /// - compute v_b = AES-128-CTR(k, serialized_fragment)
129    /// - compute vk_b = H(k) || v_b
130    /// - compute sphinx_plaintext = SURB_ACK || H(k) || v_b
131    /// - compute sphinx_packet by applying the reply surb on the sphinx_plaintext
132    fn prepare_reply_chunk_for_sending(
133        &mut self,
134        fragment: Fragment,
135        topology: &NymRouteProvider,
136        ack_key: &AckKey,
137        reply_surb: ReplySurbWithKeyRotation,
138        packet_sender: &Recipient,
139        packet_type: PacketType,
140    ) -> Result<PreparedFragment, NymTopologyError> {
141        debug!("Preparing reply chunk for sending");
142
143        // each reply attaches the digest of the encryption key so that the recipient could
144        // lookup correct key for decryption,
145        let reply_overhead = ReplySurbKeyDigestAlgorithm::output_size();
146        let PacketType::Mix = packet_type else {
147            return Err(NymTopologyError::PacketTypeNotSupported);
148        };
149        let expected_plaintext = fragment.serialized_size() + ACK_OVERHEAD + reply_overhead;
150
151        // the reason we're unwrapping (or rather 'expecting') here rather than handling the error
152        // more gracefully is that this error should never be reached as it implies incorrect chunking
153        // reply packets are always Sphinx
154        let packet_size = PacketSize::get_type_from_plaintext(expected_plaintext, PacketType::Mix)
155            .expect("the message has been incorrectly fragmented");
156
157        // this is not going to be accurate by any means. but that's the best estimation we can do
158        let expected_forward_delay =
159            Delay::new_from_millis((self.average_packet_delay().as_millis() * 3) as u64);
160
161        let fragment_identifier = fragment.fragment_identifier();
162
163        // create an ack
164        let surb_ack = self.generate_surb_ack_legacy(
165            packet_sender,
166            fragment_identifier,
167            topology,
168            ack_key,
169            packet_type,
170        )?;
171        let ack_delay = surb_ack.expected_total_delay();
172
173        let packet_payload = match NymPayloadBuilder::new(fragment, surb_ack)
174            .build_reply(reply_surb.encryption_key())
175        {
176            Ok(payload) => payload,
177            Err(_e) => return Err(NymTopologyError::PayloadBuilder),
178        };
179
180        // the unwrap here is fine as the failures can only originate from attempting to use invalid payload lengths
181        // and we just very carefully constructed a (presumably) valid one
182        let applied_surb = reply_surb
183            .apply_surb(packet_payload, packet_size, packet_type)
184            .unwrap();
185
186        Ok(PreparedFragment {
187            // the round-trip delay is the sum of delays of all hops on the forward route as
188            // well as the total delay of the ack packet.
189            // we don't know the delays inside the reply surbs so we use best-effort estimation from our poisson distribution
190            total_delay: expected_forward_delay + ack_delay,
191            mix_packet: MixPacket::from_applied_surb(applied_surb, packet_type),
192            fragment_identifier,
193        })
194    }
195
196    /// Tries to convert this [`Fragment`] into a [`SphinxPacket`] that can be sent through the Nym mix-network,
197    /// such that it contains required SURB-ACK and public component of the ephemeral key used to
198    /// derive the shared key.
199    /// Also all the data, apart from the said public component, is encrypted with an ephemeral shared key.
200    /// This method can fail if the provided network topology is invalid.
201    /// It returns total expected delay as well as the [`SphinxPacket`] (including first hop address)
202    /// to be sent through the network.
203    ///
204    /// The procedure is as follows:
205    /// For each fragment:
206    /// - compute SURB_ACK
207    /// - generate (x, g^x)
208    /// - compute k = KDF(remote encryption key ^ x) this is equivalent to KDF( dh(remote, x) )
209    /// - compute v_b = AES-128-CTR(k, serialized_fragment)
210    /// - compute vk_b = g^x || v_b
211    /// - compute sphinx_plaintext = SURB_ACK || g^x || v_b
212    /// - compute sphinx_packet = Sphinx(recipient, sphinx_plaintext)
213    #[allow(clippy::too_many_arguments)]
214    fn prepare_chunk_for_sending(
215        &mut self,
216        fragment: Fragment,
217        topology: &NymRouteProvider,
218        ack_key: &AckKey,
219        packet_sender: &Recipient,
220        packet_recipient: &Recipient,
221        packet_type: PacketType,
222    ) -> Result<PreparedFragment, NymTopologyError> {
223        debug!("Preparing chunk for sending");
224        // each plain or repliable packet (i.e. not a reply) attaches an ephemeral public key so that the recipient
225        // could perform diffie-hellman with its own keys followed by a kdf to re-derive
226        // the packet encryption key
227
228        let fragment_header = fragment.header();
229        let destination = packet_recipient.gateway();
230        monitoring::fragment_sent(&fragment, self.nonce(), destination);
231
232        let non_reply_overhead = x25519::PUBLIC_KEY_SIZE;
233        let PacketType::Mix = packet_type else {
234            return Err(NymTopologyError::PacketTypeNotSupported);
235        };
236        let expected_plaintext = fragment.serialized_size() + ACK_OVERHEAD + non_reply_overhead;
237
238        // the reason we're unwrapping (or rather 'expecting') here rather than handling the error
239        // more gracefully is that this error should never be reached as it implies incorrect chunking
240        let packet_size = PacketSize::get_type_from_plaintext(expected_plaintext, packet_type)
241            .expect("the message has been incorrectly fragmented");
242
243        let rotation_id = topology.current_key_rotation();
244        let sphinx_key_rotation = SphinxKeyRotation::from(rotation_id);
245
246        let fragment_identifier = fragment.fragment_identifier();
247
248        // create an ack
249        let surb_ack = self.generate_surb_ack_legacy(
250            packet_sender,
251            fragment_identifier,
252            topology,
253            ack_key,
254            packet_type,
255        )?;
256        let ack_delay = surb_ack.expected_total_delay();
257
258        let packet_payload = match NymPayloadBuilder::new(fragment, surb_ack)
259            .build_regular(self.rng(), packet_recipient.encryption_key())
260        {
261            Ok(payload) => payload,
262            Err(_e) => return Err(NymTopologyError::PayloadBuilder),
263        };
264
265        // generate pseudorandom route for the packet. Unless mix hops are disabled then build an empty route.
266        trace!("Preparing chunk for sending");
267        let route = if self.mix_hops_disabled() {
268            topology.empty_route_to_egress(destination)?
269        } else if self.deterministic_route_selection() {
270            trace!("using deterministic route selection");
271            let seed = fragment_header.seed().wrapping_mul(self.nonce());
272            let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
273            topology.random_route_to_egress(&mut rng, destination)?
274        } else {
275            trace!("using pseudorandom route selection");
276            topology.random_route_to_egress(self.rng(), destination)?
277        };
278
279        let destination = packet_recipient.as_sphinx_destination();
280
281        // including set of delays
282        let delays =
283            nym_sphinx_routing::generate_hop_delays(self.average_packet_delay(), route.len());
284
285        // create the actual sphinx packet here. With valid route and correct payload size,
286        // there's absolutely no reason for this call to fail.
287        #[allow(deprecated)]
288        let packet = match packet_type {
289            PacketType::Outfox => return Err(NymTopologyError::PacketTypeNotSupported),
290            PacketType::Mix => NymPacket::sphinx_build_legacy(
291                packet_size.payload_size(),
292                packet_payload,
293                &route,
294                &destination,
295                &delays,
296            )?,
297        };
298
299        // from the previously constructed route extract the first hop
300        let first_hop_address =
301            NymNodeRoutingAddress::try_from(route.first().unwrap().address).unwrap();
302
303        Ok(PreparedFragment {
304            // the round-trip delay is the sum of delays of all hops on the forward route as
305            // well as the total delay of the ack packet.
306            // note that the last hop of the packet is a gateway that does not do any delays
307            total_delay: delays.iter().take(delays.len() - 1).sum::<Delay>() + ack_delay,
308            mix_packet: MixPacket::new(first_hop_address, packet, packet_type, sphinx_key_rotation),
309            fragment_identifier,
310        })
311    }
312
313    /// As [`Self::prepare_chunk_for_sending`], but for the Lewes Protocol path.
314    ///
315    /// Three differences, all following from the recipient client being the **last sphinx hop**
316    /// rather than a destination behind a gateway that does final-hop processing:
317    ///
318    /// 1. **No SURB-ack.** There is no gateway to peel one off and send it back, and the recipient
319    ///    reads the payload directly - a leading ack would simply corrupt the message. The packet
320    ///    is sized without [`ACK_OVERHEAD`] accordingly.
321    /// 2. **No payload wrapper.** The ephemeral-DH layer that [`NymPayloadBuilder`] adds exists so
322    ///    that a gateway performing final-hop processing cannot read the message. Here the
323    ///    recipient performs it, so sphinx's own final layer already gives that and the payload is
324    ///    the serialised [`Fragment`] alone.
325    /// 3. **The route ends at the recipient**, appended as a hop, rather than at its egress
326    ///    gateway.
327    ///
328    /// Returns the first hop's [`NodeId`] alongside the packet: an LP frame names its next hop by
329    /// id, not by address, and the id is known here because the route was chosen from
330    /// [`RoutingNode`]s. Recovering it afterwards would mean searching the topology by address,
331    /// which it does not index.
332    ///
333    /// [`RoutingNode`]: nym_topology::RoutingNode
334    fn prepare_chunk_for_lp(
335        &mut self,
336        fragment: Fragment,
337        topology: &LpRouteProvider,
338        packet_recipient: &Recipient,
339    ) -> Result<PreparedLpFragment, NymTopologyError> {
340        debug!("Preparing chunk for LP sending");
341
342        let fragment_header = fragment.header();
343        let destination = packet_recipient.gateway();
344        monitoring::fragment_sent(&fragment, self.nonce(), destination);
345
346        // the fragment fills the sphinx plaintext exactly, so the payload is that plus what the
347        // sphinx layer wraps it in - which is what looking the size up as a `PacketSize` would
348        // arrive at, without requiring it to be one of that fixed set. On this path it is not: LP
349        // chunks to whatever its frame budget leaves.
350        let payload_size = fragment.serialized_size() + PAYLOAD_OVERHEAD_SIZE;
351
352        let sphinx_key_rotation = SphinxKeyRotation::from(topology.current_key_rotation());
353
354        let packet_payload = fragment.into_bytes();
355
356        // generate pseudorandom route for the packet. Unless mix hops are disabled then build an empty route.
357
358        trace!("Preparing chunk for sending");
359        // the path runs through the mix layers and ends at the recipient's egress gateway, which is
360        // the hop that can actually reach them
361        let mix_path = if self.mix_hops_disabled() {
362            // the egress is the whole path
363            topology.empty_path_to_egress(destination)?
364        } else if self.deterministic_route_selection() {
365            trace!("using deterministic route selection");
366            let seed = fragment_header.seed().wrapping_mul(self.nonce());
367            let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
368            topology.random_path_to_egress(&mut rng, destination)?
369        } else {
370            trace!("using pseudorandom route selection");
371            topology.random_path_to_egress(self.rng(), destination)?
372        };
373
374        let first_hop_id = mix_path
375            .first()
376            .ok_or(NymTopologyError::NoMixnodesAvailable)?
377            .node_id;
378
379        // an `LpRoutingNode` carries no mix address at all, so this cannot name the legacy listener
380        let mut route = mix_path
381            .into_iter()
382            .map(Into::into)
383            .collect::<Vec<SphinxNode>>();
384
385        // the recipient is a hop, not merely the destination: on this path it is the one that
386        // performs final-hop processing
387        // SAFETY: a client address fits the sphinx addressing scheme
388        #[expect(clippy::unwrap_used)]
389        route.push(SphinxNode::new(
390            packet_recipient.as_sphinx_hop().try_into().unwrap(),
391            (*packet_recipient.encryption_key()).into(),
392        ));
393
394        let delays =
395            nym_sphinx_routing::generate_hop_delays(self.average_packet_delay(), route.len());
396
397        // create the actual sphinx packet here. With valid route and correct payload size,
398        // there's absolutely no reason for this call to fail.
399        let packet = NymPacket::sphinx_build(
400            payload_size,
401            packet_payload,
402            &route,
403            &packet_recipient.as_sphinx_destination(),
404            &delays,
405        )?;
406
407        // from the previously constructed route extract the first hop
408        // SAFETY: the route is non-empty, having just been built with at least the recipient
409        #[expect(clippy::unwrap_used)]
410        let first_hop_address =
411            NymNodeRoutingAddress::try_from(route.first().unwrap().address).unwrap();
412
413        Ok(PreparedLpFragment {
414            mix_packet: MixPacket::new(
415                first_hop_address,
416                packet,
417                PacketType::Mix,
418                sphinx_key_rotation,
419            ),
420            first_hop_id,
421        })
422    }
423
424    fn pad_and_split_message(
425        &mut self,
426        message: NymMessage,
427        packet_size: PacketSize,
428    ) -> Vec<Fragment> {
429        let plaintext_per_packet = message.available_sphinx_plaintext_per_packet(packet_size);
430
431        message
432            .pad_to_full_packet_lengths(plaintext_per_packet)
433            .split_into_fragments(self.rng(), plaintext_per_packet)
434    }
435}
436
437/// Prepares the message that is to be sent through the mix network.
438///
439/// Prepares the message that is to be sent through the mix network by attaching
440/// an optional reply-SURB, padding it to appropriate length, encrypting its content,
441/// and chunking into appropriate size [`Fragment`]s.
442#[derive(Clone)]
443#[must_use]
444pub struct MessagePreparer<R> {
445    /// Instance of a cryptographically secure random number generator.
446    rng: R,
447
448    /// Specify whether route selection should be determined by the packet header.
449    deterministic_route_selection: bool,
450
451    /// Address of this client which also represent an address to which all acknowledgements
452    /// and surb-based are going to be sent.
453    sender_address: Recipient,
454
455    /// Average delay a data packet is going to get delay at a single mixnode.
456    average_packet_delay: Duration,
457
458    /// Average delay an acknowledgement packet is going to get delay at a single mixnode.
459    average_ack_delay: Duration,
460
461    nonce: i32,
462
463    /// Indicates whether to mix hops or not. If mix hops are enabled, traffic
464    /// will be routed as usual, to the entry gateway, through three mix nodes, egressing
465    /// through the exit gateway. If mix hops are disabled, traffic will be routed directly
466    /// from the entry gateway to the exit gateway, bypassing the mix nodes.
467    pub disable_mix_hops: bool,
468}
469
470impl<R> MessagePreparer<R>
471where
472    R: CryptoRng + Rng,
473{
474    pub fn new(
475        rng: R,
476        deterministic_route_selection: bool,
477        sender_address: Recipient,
478        average_packet_delay: Duration,
479        average_ack_delay: Duration,
480        disable_mix_hops: bool,
481    ) -> Self {
482        let mut rng = rng;
483        let nonce = rng.random();
484        MessagePreparer {
485            rng,
486            deterministic_route_selection,
487            sender_address,
488            average_packet_delay,
489            average_ack_delay,
490            nonce,
491            disable_mix_hops,
492        }
493    }
494
495    /// Overwrites existing sender address with the provided value.
496    pub fn set_sender_address(&mut self, sender_address: Recipient) {
497        self.sender_address = sender_address;
498    }
499
500    pub fn generate_reply_surbs(
501        &mut self,
502        amount: usize,
503        topology: &NymRouteProvider,
504    ) -> Result<Vec<ReplySurbWithKeyRotation>, NymTopologyError> {
505        let mut reply_surbs = Vec::with_capacity(amount);
506        let disabled_mix_hops = self.mix_hops_disabled();
507
508        let key_rotation = SphinxKeyRotation::from(topology.current_key_rotation());
509
510        for _ in 0..amount {
511            let reply_surb = ReplySurb::construct(
512                &mut self.rng,
513                &self.sender_address,
514                self.average_packet_delay,
515                topology,
516                disabled_mix_hops,
517            )?
518            .with_key_rotation(key_rotation);
519            reply_surbs.push(reply_surb)
520        }
521
522        Ok(reply_surbs)
523    }
524
525    pub fn prepare_reply_chunk_for_sending(
526        &mut self,
527        fragment: Fragment,
528        topology: &NymRouteProvider,
529        ack_key: &AckKey,
530        reply_surb: ReplySurbWithKeyRotation,
531        packet_type: PacketType,
532    ) -> Result<PreparedFragment, NymTopologyError> {
533        let sender = self.sender_address;
534
535        <Self as FragmentPreparer>::prepare_reply_chunk_for_sending(
536            self,
537            fragment,
538            topology,
539            ack_key,
540            reply_surb,
541            &sender,
542            packet_type,
543        )
544    }
545
546    pub fn prepare_chunk_for_sending(
547        &mut self,
548        fragment: Fragment,
549        topology: &NymRouteProvider,
550        ack_key: &AckKey,
551        packet_recipient: &Recipient,
552        packet_type: PacketType,
553    ) -> Result<PreparedFragment, NymTopologyError> {
554        let sender = self.sender_address;
555
556        <Self as FragmentPreparer>::prepare_chunk_for_sending(
557            self,
558            fragment,
559            topology,
560            ack_key,
561            &sender,
562            packet_recipient,
563            packet_type,
564        )
565    }
566
567    /// Prepare a chunk for the Lewes Protocol path: no SURB-ack, and the recipient is the last hop.
568    ///
569    /// See [`FragmentPreparer::prepare_chunk_for_lp`].
570    pub fn prepare_chunk_for_lp(
571        &mut self,
572        fragment: Fragment,
573        topology: &LpRouteProvider,
574        packet_recipient: &Recipient,
575    ) -> Result<PreparedLpFragment, NymTopologyError> {
576        <Self as FragmentPreparer>::prepare_chunk_for_lp(self, fragment, topology, packet_recipient)
577    }
578
579    /// Construct an acknowledgement SURB for the given [`FragmentIdentifier`]
580    pub fn generate_surb_ack_legacy(
581        &mut self,
582        fragment_id: FragmentIdentifier,
583        topology: &NymRouteProvider,
584        ack_key: &AckKey,
585        packet_type: PacketType,
586    ) -> Result<SurbAck, NymTopologyError> {
587        let sender = self.sender_address;
588        <Self as FragmentPreparer>::generate_surb_ack_legacy(
589            self,
590            &sender,
591            fragment_id,
592            topology,
593            ack_key,
594            packet_type,
595        )
596    }
597
598    pub fn pad_and_split_message(
599        &mut self,
600        message: NymMessage,
601        packet_size: PacketSize,
602    ) -> Vec<Fragment> {
603        <Self as FragmentPreparer>::pad_and_split_message(self, message, packet_size)
604    }
605}
606
607impl<R: CryptoRng + Rng> FragmentPreparer for MessagePreparer<R> {
608    type Rng = R;
609
610    fn mix_hops_disabled(&self) -> bool {
611        self.disable_mix_hops
612    }
613
614    fn deterministic_route_selection(&self) -> bool {
615        self.deterministic_route_selection
616    }
617
618    fn rng(&mut self) -> &mut Self::Rng {
619        &mut self.rng
620    }
621
622    fn nonce(&self) -> i32 {
623        self.nonce
624    }
625
626    fn average_packet_delay(&self) -> Duration {
627        self.average_packet_delay
628    }
629
630    fn average_ack_delay(&self) -> Duration {
631        self.average_ack_delay
632    }
633}
634
635/*
636   And for completion reconstruction:
637   1. receive unwrapped sphinx packet: g^x || v_b
638   2. recompute k = KDF(g^x * our encryption key)
639   3. original_fragment = AES(k, v_b)
640   4. deal with fragment as before
641   5. on full message reconstruction output (message, Option<reply_surb>)
642*/