Skip to main content

hopr_crypto_packet/
packet.rs

1use std::fmt::Formatter;
2
3use bytes::Bytes;
4use hopr_protocol_pix::{EntryShareGenerator, TaggedEncryptedPartialSsaShare};
5use hopr_types::{
6    crypto::prelude::*,
7    internal::{
8        prelude::*,
9        routing::{HoprSenderId, HoprSurbId},
10    },
11    primitive::prelude::*,
12};
13#[cfg(feature = "rayon")]
14use hopr_utils::parallelize::cpu::rayon::prelude::*;
15
16use crate::{
17    HoprEncryptedPartialSsaShare, HoprPixSpec, HoprPseudonym, HoprReplyOpener, HoprSphinxHeaderSpec, HoprSphinxSuite,
18    HoprSurb, PAYLOAD_SIZE_INT,
19    errors::{
20        PacketError::{PacketConstructionError, PacketDecodingError, PacketReplay},
21        Result,
22    },
23    expand::KeyExpander,
24    por::{ProofOfRelayString, ProofOfRelayValues, derive_ack_key_share, generate_proof_of_relay, pre_verify},
25    sphinx::prelude::*,
26    types::{HoprPacketMessage, HoprPacketParts, HoprReceivedPacketParts, PacketSignals, SurbReceiverInfo},
27};
28
29/// Represents an outgoing packet that has been only partially instantiated.
30///
31/// It contains [`PartialPacket`], required Proof-of-Relay
32/// fields, and the [`Ticket`], but it does not contain the payload.
33///
34/// This can be used to pre-compute packets for certain destinations,
35/// and [convert](PartialHoprPacket::into_hopr_packet) them to full packets
36/// once the payload is known.
37#[derive(Clone)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub struct PartialHoprPacket {
40    partial_packet: PartialPacket<HoprSphinxSuite, HoprSphinxHeaderSpec>,
41    surbs: Vec<HoprSurb>,
42    openers: Vec<HoprReplyOpener>,
43    ticket: Ticket,
44    next_hop: OffchainPublicKey,
45    ack_challenge: HalfKeyChallenge,
46    encrypted_pix_share: Option<TaggedEncryptedPartialSsaShare<HoprPixSpec>>,
47    final_packet_tag: Option<PacketTag>,
48}
49
50/// Shared key data for a path.
51///
52/// This contains the derived shared secrets and Proof of Relay data for a path.
53struct PathKeyData {
54    /// Shared secrets for the path.
55    pub shared_keys: SharedKeys<<HoprSphinxSuite as SphinxSuite>::E, <HoprSphinxSuite as SphinxSuite>::G>,
56    /// Proof of Relay data for each hop on the path.
57    pub por_strings: Vec<ProofOfRelayString>,
58    /// Proof of Relay values for the first ticket on the path.
59    pub por_values: ProofOfRelayValues,
60    /// Solution to the first PoR challenge.
61    ///
62    /// This is set only for non-zero hop paths.
63    pub first_relayer_solution: Option<HalfKey>,
64}
65
66impl PathKeyData {
67    /// The single place in the protocol where a peer's packet key has to be decompressed; see
68    /// [`KeyExpander`].
69    fn new<X: KeyExpander>(path: &[OffchainPublicKey], expander: &X) -> Result<Self> {
70        let expanded = expander.expand_path(path)?;
71        let shared_keys = HoprSphinxSuite::new_shared_keys_expanded(&expanded)?;
72        let (por_strings, (por_values, first_relayer_solution)) = generate_proof_of_relay(&shared_keys.secrets)?;
73
74        Ok(Self {
75            shared_keys,
76            por_strings,
77            por_values,
78            // We do not offer the first relayer solution on 0-hops
79            first_relayer_solution: (path.len() > 1).then_some(first_relayer_solution),
80        })
81    }
82
83    /// Computes `PathKeyData` for the given paths.
84    ///
85    /// Uses parallel processing if the `rayon` feature is enabled.
86    fn iter_from_paths<X: KeyExpander>(
87        paths: Vec<&[OffchainPublicKey]>,
88        expander: &X,
89    ) -> Result<impl Iterator<Item = Self> + use<X>> {
90        #[cfg(not(feature = "rayon"))]
91        let paths = paths.into_iter();
92
93        #[cfg(feature = "rayon")]
94        let paths = paths.into_par_iter();
95
96        paths
97            .map(|path| Self::new(path, expander))
98            .collect::<Result<Vec<_>>>()
99            .map(|paths| paths.into_iter())
100    }
101}
102
103impl PartialHoprPacket {
104    /// Instantiates a new partial HOPR packet.
105    ///
106    /// # Arguments
107    ///
108    /// * `pseudonym` our pseudonym as packet sender.
109    /// * `routing` routing to the destination.
110    /// * `chain_keypair` private key of the local node.
111    /// * `ticket` ticket builder for the first hop on the path.
112    /// * `mapper` of the public key identifiers.
113    /// * `expander` supplying the expanded form of the packet keys on the path.
114    /// * `pix_share_gen` generator for the pix share.
115    /// * `domain_separator` channel contract domain separator.
116    #[allow(clippy::too_many_arguments)] // TODO: needs refactoring (perhaps introduce a builder pattern?)
117    pub fn new<
118        G: EntryShareGenerator<HoprPixSpec>,
119        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
120        P: NonEmptyPath<OffchainPublicKey> + Send,
121        X: KeyExpander,
122    >(
123        pseudonym: &HoprPseudonym,
124        routing: PacketRouting<P>,
125        chain_keypair: &ChainKeypair,
126        ticket: TicketBuilder,
127        mapper: &M,
128        expander: &X,
129        pix_share_gen: &G,
130        domain_separator: &Hash,
131    ) -> Result<Self> {
132        match routing {
133            PacketRouting::ForwardPath {
134                forward_path,
135                return_paths,
136                generation,
137            } => {
138                // Create shared secrets and PoR challenge chain for forward and return paths
139                let mut key_data = PathKeyData::iter_from_paths(
140                    std::iter::once(forward_path.hops())
141                        .chain(return_paths.iter().map(|p| p.hops()))
142                        .collect(),
143                    expander,
144                )?;
145
146                let PathKeyData {
147                    shared_keys,
148                    por_strings,
149                    por_values,
150                    ..
151                } = key_data
152                    .next()
153                    .ok_or_else(|| PacketConstructionError("empty path".into()))?;
154
155                // The tag the final hop will derive for this packet
156                let final_packet_tag = shared_keys.secrets.last().map(derive_packet_tag).transpose()?;
157
158                let receiver_data = HoprSenderId::new(pseudonym);
159
160                // Create SURBs if some return paths were specified
161                // Possibly makes little sense to parallelize this iterator via rayon,
162                // as in most cases the number of return paths is 1.
163                // TODO: PIX shares consumed here (via create_surb_for_path → next_share) are
164                // not rolled back on later fallible operations (ticket signing, encoding).
165                // This is intentional: the EntryShareGenerator emits surplus shares to absorb
166                // such packet-loss events, so the budget impact is bounded and expected.
167                let (surbs, openers): (Vec<_>, Vec<_>) = key_data
168                    .zip(return_paths)
169                    .zip(receiver_data.into_sequence())
170                    .map(|((key_data, rp), data)| {
171                        create_surb_for_path((rp, key_data), data, mapper, pix_share_gen, generation)
172                    })
173                    .collect::<Result<Vec<_>>>()?
174                    .into_iter()
175                    .unzip();
176
177                // Update the ticket with the challenge
178                let ticket = ticket
179                    .eth_challenge(por_values.ticket_challenge())
180                    .build_signed(chain_keypair, domain_separator)?
181                    .leak();
182
183                Ok(Self {
184                    partial_packet: PartialPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec>::new(
185                        MetaPacketRouting::ForwardPath {
186                            shared_keys,
187                            forward_path: &forward_path,
188                            receiver_data: &receiver_data,
189                            additional_data_relayer: &por_strings,
190                            no_ack: false,
191                        },
192                        mapper,
193                    )?,
194                    surbs,
195                    openers,
196                    ticket,
197                    next_hop: forward_path[0],
198                    ack_challenge: por_values.acknowledgement_challenge(),
199                    encrypted_pix_share: None,
200                    final_packet_tag,
201                })
202            }
203            PacketRouting::Surb(id, surb) => {
204                let surb_por_values = surb.additional_data_receiver.proof_of_relay_values();
205
206                // Update the ticket with the challenge
207                let ticket = ticket
208                    .eth_challenge(surb_por_values.ticket_challenge())
209                    .build_signed(chain_keypair, domain_separator)?
210                    .leak();
211
212                // Extract the encrypted partial SSA share from the SURB
213                let partial_share = surb.additional_data_receiver.encrypted_partial_ssa_share();
214
215                Ok(Self {
216                    ticket,
217                    next_hop: mapper.map_id_to_public(&surb.first_relayer).ok_or_else(|| {
218                        PacketConstructionError(format!(
219                            "failed to map key id {} to public key",
220                            surb.first_relayer.to_hex()
221                        ))
222                    })?,
223                    ack_challenge: surb_por_values.acknowledgement_challenge(),
224                    encrypted_pix_share: (!partial_share.is_empty())
225                        .then(|| TaggedEncryptedPartialSsaShare::new(id.pseudonym(), &surb.sender_key, partial_share))
226                        .transpose()?,
227                    partial_packet: PartialPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec>::new(
228                        MetaPacketRouting::Surb(surb, &id),
229                        mapper,
230                    )?,
231                    surbs: vec![],
232                    openers: vec![],
233                    final_packet_tag: None,
234                })
235            }
236            PacketRouting::NoAck(destination) => {
237                // Create shared secrets and PoR challenge chain
238                let PathKeyData {
239                    shared_keys,
240                    por_strings,
241                    por_values,
242                    ..
243                } = PathKeyData::new(&[destination], expander)?;
244
245                // Update the ticket with the challenge
246                let ticket = ticket
247                    .eth_challenge(por_values.ticket_challenge())
248                    .build_signed(chain_keypair, domain_separator)?
249                    .leak();
250
251                Ok(Self {
252                    partial_packet: PartialPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec>::new(
253                        MetaPacketRouting::ForwardPath {
254                            shared_keys,
255                            forward_path: &[destination],
256                            receiver_data: &HoprSenderId::new(pseudonym),
257                            additional_data_relayer: &por_strings,
258                            no_ack: true, // Indicate this is a no-acknowledgement probe packet
259                        },
260                        mapper,
261                    )?,
262                    ticket,
263                    next_hop: destination,
264                    ack_challenge: por_values.acknowledgement_challenge(),
265                    surbs: vec![],
266                    openers: vec![],
267                    encrypted_pix_share: None,
268                    final_packet_tag: None,
269                })
270            }
271        }
272    }
273
274    /// Turns this partial HOPR packet into a full [`Outgoing`](HoprPacket::Outgoing) [`HoprPacket`] by
275    /// attaching the given payload `msg` and optional packet `signals` for the recipient.
276    ///
277    /// No `signals` are equivalent to `0`.
278    pub fn into_hopr_packet<S: Into<PacketSignals>>(
279        self,
280        msg: &[u8],
281        signals: S,
282    ) -> Result<(HoprPacket, Vec<HoprReplyOpener>)> {
283        let msg = HoprPacketMessage::try_from(HoprPacketParts {
284            surbs: self.surbs,
285            payload: msg.into(),
286            signals: signals.into(),
287        })?;
288        Ok((
289            HoprPacket::Outgoing(
290                HoprOutgoingPacket {
291                    packet: self.partial_packet.into_meta_packet(msg.into()),
292                    ticket: self.ticket,
293                    next_hop: self.next_hop,
294                    ack_challenge: self.ack_challenge,
295                    encrypted_pix_share: self.encrypted_pix_share,
296                    final_packet_tag: self.final_packet_tag,
297                }
298                .into(),
299            ),
300            self.openers,
301        ))
302    }
303}
304
305/// Represents a packet incoming to its final destination.
306#[derive(Clone)]
307pub struct HoprIncomingPacket {
308    /// Packet's authentication tag.
309    pub packet_tag: PacketTag,
310    /// Acknowledgement to be sent to the previous hop.
311    ///
312    /// In case an acknowledgement is not required, this field is `None`. This arises specifically
313    /// in case the message payload is used to send one or more acknowledgements in the payload.
314    pub ack_key: Option<HalfKey>,
315    /// Address of the previous hop.
316    pub previous_hop: OffchainPublicKey,
317    /// Decrypted packet payload.
318    pub plain_text: Bytes,
319    /// Pseudonym of the packet creator.
320    pub sender: HoprPseudonym,
321    /// List of [`SURBs`](SURB) to be used for replies sent to the packet creator.
322    pub surbs: Vec<(HoprSurbId, HoprSurb)>,
323    /// Additional packet signals from the lower protocol layer passed from the packet sender.
324    ///
325    /// Zero if no signal flags were specified.
326    pub signals: PacketSignals,
327}
328
329impl std::fmt::Debug for HoprIncomingPacket {
330    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
331        f.debug_struct("HoprIncomingPacket")
332            .field("packet_tag", &self.packet_tag)
333            .field("ack_key", &self.ack_key)
334            .field("previous_hop", &self.previous_hop)
335            .field("sender", &self.sender)
336            .field("signals", &self.signals)
337            .finish_non_exhaustive()
338    }
339}
340
341/// Represents a packet destined for another node.
342#[derive(Clone)]
343pub struct HoprOutgoingPacket {
344    /// Encrypted packet.
345    pub packet: MetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>,
346    /// Ticket for this node.
347    pub ticket: Ticket,
348    /// Next hop this packet should be sent to.
349    pub next_hop: OffchainPublicKey,
350    /// Acknowledgement challenge solved once the next hop sends us an acknowledgement.
351    pub ack_challenge: HalfKeyChallenge,
352    /// PIX protocol encrypted partial SSA share to be decrypted once the next hop sends back an acknowledgement.
353    ///
354    /// This is populated only if this is a return path packet and the associated SURB contained an encrypted partial
355    /// SSA share.
356    pub encrypted_pix_share: Option<TaggedEncryptedPartialSsaShare<HoprPixSpec>>,
357    /// Tag the final hop derives for this packet; set only on packets built from a forward path.
358    pub final_packet_tag: Option<PacketTag>,
359}
360
361impl HoprOutgoingPacket {
362    /// Builds the wire frame (the packet followed by its ticket) in the packet's own buffer.
363    ///
364    /// This does not copy the packet if its buffer has room for the ticket, as is the case for relayed packets.
365    pub fn frame(packet: MetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>, ticket: Ticket) -> Bytes {
366        let encoded_ticket = ticket.into_encoded();
367        let mut frame = packet.into_vec();
368        frame.reserve_exact(encoded_ticket.len());
369        frame.extend_from_slice(&encoded_ticket);
370        frame.into()
371    }
372}
373
374impl std::fmt::Debug for HoprOutgoingPacket {
375    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
376        f.debug_struct("HoprOutgoingPacket")
377            .field("ticket", &self.ticket)
378            .field("next_hop", &self.next_hop)
379            .field("ack_challenge", &self.ack_challenge)
380            .field("encrypted_pix_share", &self.encrypted_pix_share)
381            .finish_non_exhaustive()
382    }
383}
384
385/// Represents a [`HoprOutgoingPacket`] with additional forwarding information.
386#[derive(Clone)]
387pub struct HoprForwardedPacket {
388    /// Packet to be sent.
389    pub outgoing: HoprOutgoingPacket,
390    /// Authentication tag of the packet's header.
391    pub packet_tag: PacketTag,
392    /// Acknowledgement to be sent to the previous hop.
393    pub ack_key: HalfKey,
394    /// Sender of this packet.
395    pub previous_hop: OffchainPublicKey,
396    /// Key used to verify our challenge.
397    pub own_key: HalfKey,
398    /// Challenge for the next hop.
399    pub next_challenge: EthereumChallenge,
400    /// Our position in the path.
401    pub path_pos: u8,
402}
403
404impl std::fmt::Debug for HoprForwardedPacket {
405    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
406        f.debug_struct("HoprForwardedPacket")
407            .field("outgoing", &self.outgoing)
408            .field("packet_tag", &const_hex::encode(self.packet_tag))
409            .field("ack_key", &self.ack_key)
410            .field("previous_hop", &self.previous_hop)
411            .field("own_key", &self.own_key)
412            .field("next_challenge", &self.next_challenge)
413            .field("path_pos", &self.path_pos)
414            .finish_non_exhaustive()
415    }
416}
417
418/// Contains HOPR packet and its variants.
419///
420/// See [`HoprIncomingPacket`], [`HoprForwardedPacket`] and [`HoprOutgoingPacket`] for details.
421///
422/// The members are intentionally boxed to equalize the variant sizes.
423#[derive(Clone, Debug, strum::EnumTryAs, strum::EnumIs, strum::IntoStaticStr, strum::Display)]
424pub enum HoprPacket {
425    /// The packet is intended for us
426    #[strum(to_string = "Final")]
427    Final(Box<HoprIncomingPacket>),
428    /// The packet must be forwarded
429    #[strum(to_string = "Forwarded")]
430    Forwarded(Box<HoprForwardedPacket>),
431    /// The packet that is being sent out by us
432    #[strum(to_string = "Outgoing")]
433    Outgoing(Box<HoprOutgoingPacket>),
434}
435
436impl HoprPacket {
437    /// Returns the [`PacketTag`] of forwarded or final packets, or `None` for outgoing packets.
438    pub fn packet_tag(&self) -> Option<&PacketTag> {
439        match self {
440            HoprPacket::Final(packet) => Some(&packet.packet_tag),
441            HoprPacket::Forwarded(packet) => Some(&packet.packet_tag),
442            HoprPacket::Outgoing(_) => None,
443        }
444    }
445}
446
447/// Determines options on how HOPR packet can be routed to its destination.
448#[derive(Clone)]
449pub enum PacketRouting<P: NonEmptyPath<OffchainPublicKey> = TransportPath> {
450    /// The packet is routed directly via the given path.
451    /// Optionally, return paths for
452    /// attached SURBs can be specified.
453    ///
454    /// `generation` is the RFC-1982 serial stamped into every SURB minted here (see
455    /// `SurbReceiverInfo::generation()`). The creator bumps it whenever it changes the return path,
456    /// so the replying side can drop SURBs left over from a superseded path. It is irrelevant when
457    /// `return_paths` is empty; pass `0` there.
458    ForwardPath {
459        forward_path: P,
460        return_paths: Vec<P>,
461        generation: u8,
462    },
463    /// The packet is routed via an existing SURB that corresponds to a pseudonym.
464    Surb(HoprSenderId, HoprSurb),
465    /// No acknowledgement packet: a special type of 0-hop packet that is not going to be acknowledged but can carry a
466    /// payload.
467    NoAck(OffchainPublicKey),
468}
469
470fn create_surb_for_path<
471    G: EntryShareGenerator<HoprPixSpec>,
472    M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
473    P: NonEmptyPath<OffchainPublicKey>,
474>(
475    return_path: (P, PathKeyData),
476    recv_data: HoprSenderId,
477    mapper: &M,
478    pix_share_gen: &G,
479    generation: u8,
480) -> Result<(HoprSurb, HoprReplyOpener)> {
481    let (
482        return_path,
483        PathKeyData {
484            shared_keys,
485            por_strings,
486            por_values,
487            first_relayer_solution,
488        },
489    ) = return_path;
490
491    // The first relayer challenge solution is known only if this is not a 0-hop return path.
492    // It is a logical protocol bug otherwise.
493    debug_assert!(
494        (return_path.len() == 1 && first_relayer_solution.is_none())
495            || (return_path.len() > 1 && first_relayer_solution.is_some()),
496        "multi-hop return path must have a first relayer challenge solution"
497    );
498
499    tracing::debug!(
500        has_first_relayer_solution = first_relayer_solution.is_some(),
501        "prepared return-path PoR data"
502    );
503
504    let (mut surb, (surb_id, ro)) = create_surb::<HoprSphinxSuite, HoprSphinxHeaderSpec>(
505        shared_keys,
506        &return_path
507            .iter()
508            .map(|k| {
509                mapper
510                    .map_key_to_id(k)
511                    .ok_or_else(|| PacketConstructionError(format!("failed to map key {} to id", k.to_hex())))
512            })
513            .collect::<Result<Vec<_>>>()?,
514        &por_strings,
515        recv_data,
516        SurbReceiverInfo::new(por_values, HoprEncryptedPartialSsaShare::default(), generation),
517    )
518    .map(|(s, r)| (s, (recv_data.surb_id(), r)))?;
519
520    // Existence of the first-relayer challenge solution indicates this is not a 0-hop return path.
521    if let Some(first_solution) = first_relayer_solution
522        && let Some(enc_share) = pix_share_gen
523            .next_share(&recv_data.pseudonym(), &ro.sender_key)
524            .map_err(|e| PacketConstructionError(format!("failed to generate PIX share: {e}")))?
525            .map(|gen_share| gen_share.encrypt(&first_solution))
526            .transpose()?
527    {
528        // Replace the empty encrypted share with the generated one, encrypted using the first relayer ticket challenge
529        // solution.
530        surb.additional_data_receiver = SurbReceiverInfo::new(por_values, enc_share, generation);
531    }
532
533    Ok((surb, (surb_id, ro)))
534}
535
536/// Guards the SURB-batch generation byte added to `SurbReceiverInfo`: it must not have shrunk the
537/// per-packet SURB capacity. The larger packet payload must still fit eight SURBs.
538const _: () = assert!(
539    HoprPacket::MAX_SURBS_IN_PACKET == 8,
540    "SURB size grew enough to reduce MAX_SURBS_IN_PACKET; the generation carrier must move to spare bits (e.g. \
541     ProofOfRelayValues chain_length high bits) instead of enlarging SurbReceiverInfo"
542);
543
544impl HoprPacket {
545    /// The maximum number of SURBs that fit into a packet that contains no message.
546    pub const MAX_SURBS_IN_PACKET: usize = HoprPacket::PAYLOAD_SIZE / HoprSurb::SIZE;
547    /// Maximum message size when no SURBs are present in the packet.
548    ///
549    /// See [`HoprPacket::max_surbs_with_message`].
550    pub const PAYLOAD_SIZE: usize = PAYLOAD_SIZE_INT - HoprPacketMessage::HEADER_LEN;
551    /// The size of the packet including header, padded payload, ticket, and ack challenge.
552    pub const SIZE: usize =
553        MetaPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>::PACKET_LEN + Ticket::SIZE;
554
555    /// Constructs a new outgoing packet with the given path.
556    ///
557    /// # Arguments
558    /// * `msg` packet payload.
559    /// * `pseudonym` our pseudonym as packet sender.
560    /// * `routing` routing to the destination.
561    /// * `chain_keypair` private key of the local node.
562    /// * `ticket` ticket builder for the first hop on the path.
563    /// * `mapper` of the public key identifiers.
564    /// * `expander` supplying the expanded form of the packet keys on the path.
565    /// * `domain_separator` channel contract domain separator.
566    /// * `pix_share_gen` generator of the PIX protocol shares.
567    /// * `signals` optional signals passed to the packet's final destination.
568    ///
569    /// **NOTE**
570    /// For the given pseudonym, the [`ReplyOpener`] order matters.
571    #[allow(clippy::too_many_arguments)] // TODO: needs refactoring (perhaps introduce a builder pattern?)
572    pub fn into_outgoing<
573        G: EntryShareGenerator<HoprPixSpec>,
574        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
575        P: NonEmptyPath<OffchainPublicKey> + Send,
576        S: Into<PacketSignals>,
577        X: KeyExpander,
578    >(
579        msg: &[u8],
580        pseudonym: &HoprPseudonym,
581        routing: PacketRouting<P>,
582        chain_keypair: &ChainKeypair,
583        ticket: TicketBuilder,
584        mapper: &M,
585        expander: &X,
586        domain_separator: &Hash,
587        pix_share_gen: &G,
588        signals: S,
589    ) -> Result<(Self, Vec<HoprReplyOpener>)> {
590        PartialHoprPacket::new(
591            pseudonym,
592            routing,
593            chain_keypair,
594            ticket,
595            mapper,
596            expander,
597            pix_share_gen,
598            domain_separator,
599        )?
600        .into_hopr_packet(msg, signals)
601    }
602
603    /// Calculates how many SURBs can be fitted into a packet that
604    /// also carries a message of the given length.
605    pub const fn max_surbs_with_message(msg_len: usize) -> usize {
606        HoprPacket::PAYLOAD_SIZE.saturating_sub(msg_len) / HoprSurb::SIZE
607    }
608
609    /// Calculates the maximum length of the message that can be carried by a packet
610    /// with the given number of SURBs.
611    pub const fn max_message_with_surbs(num_surbs: usize) -> usize {
612        HoprPacket::PAYLOAD_SIZE.saturating_sub(num_surbs * HoprSurb::SIZE)
613    }
614
615    /// Deserializes the packet and performs the forward-transformation, so the
616    /// packet can be further delivered (relayed to the next hop or read), after asking `is_replay` about the
617    /// packet's [`PacketTag`].
618    ///
619    /// The tag is derived from the shared secret, so it is meaningful only once the elliptic-curve multiplication
620    /// has been done - but it is available *before* the header MAC is verified and before the payload is permuted
621    /// or parsed. This constructor therefore lets a caller reject a replayed packet after the multiplication and
622    /// before that remaining work.
623    ///
624    /// `is_replay` is called at most once, after the secret is derived and before the header MAC is verified; it
625    /// should only *check*. `commit` is called at most once, once the header MAC and the payload permutation have
626    /// succeeded, and it should insert. Returning `true` from either reports [`PacketReplay`].
627    ///
628    /// Splitting them this way is what makes a token cost a well-formed packet: the secret is derived from the
629    /// node's *public* key and the packet's alpha, so anybody can make this function derive a tag - but only a
630    /// packet whose header MAC verifies reaches `commit`, and the MAC cannot be forged without the real secret.
631    ///
632    /// A tag that passes `is_replay` but whose packet then fails to transform is committed only if the header MAC
633    /// had already verified - the "we consumed the SURB opener, then could not finish" case, so its retry is
634    /// recognised. A packet that never authenticated is not committed, so a forged alpha neither advances the
635    /// filter nor can be retried for free.
636    pub fn from_incoming_checked<M, F, R, C>(
637        data: &[u8],
638        node_keypair: &OffchainKeypair,
639        previous_hop: OffchainPublicKey,
640        mapper: &M,
641        reply_openers: F,
642        is_replay: R,
643        commit: C,
644    ) -> Result<Self>
645    where
646        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
647        F: FnMut(&HoprSenderId) -> Option<ReplyOpener>,
648        R: FnOnce(&PacketTag) -> bool,
649        C: FnOnce(&PacketTag) -> bool,
650    {
651        if data.len() == Self::SIZE {
652            let (pre_packet, pre_ticket) =
653                data.split_at(MetaPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>::PACKET_LEN);
654
655            // Spare room for the ticket lets a relayed packet become the outbound frame without another copy.
656            let mut owned = Vec::with_capacity(Self::SIZE);
657            owned.extend_from_slice(pre_packet);
658            let mp: MetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT> = MetaPacket::try_from(owned)?;
659
660            let state = mp.forward_secret(node_keypair)?;
661            let tag = *state.tag();
662            if is_replay(&tag) {
663                return Err(PacketReplay);
664            }
665
666            // Only a packet whose header MAC verifies gets this far, so recording the tag from here on means a
667            // forged alpha costs the sender a well-formed packet rather than the public key alone.
668            //
669            // A failure past this point is not *necessarily* permanent - on a reply it can be the opener's
670            // absence, which a concurrent copy of the same packet may still be about to fix - so the tag is
671            // committed and the original error is returned. Reporting a replay instead would misdescribe a packet
672            // that was never seen before.
673            let mut authenticated = false;
674            let forwarded = match mp.into_forwarded_with_secret(state, mapper, reply_openers, || authenticated = true) {
675                Ok(forwarded) => forwarded,
676                Err(error) => {
677                    // A packet that never authenticated is not recorded - that is what keeps a token costing a
678                    // well-formed packet. One that did is, so its retry is recognised instead of paying a second
679                    // decode that cannot succeed either.
680                    //
681                    // `commit` reporting an already-present tag means a concurrent decode of the same packet got
682                    // there first, so this copy is the duplicate - whatever local failure ended this attempt.
683                    //
684                    // A missing reply opener is *not* by itself evidence of that: it is equally what an expired,
685                    // evicted or restart-lost opener looks like, and calling those replays would send an operator
686                    // looking at the wrong subsystem. So the opener error is recorded and returned as itself, and
687                    // only an already-known tag is reported as a replay.
688                    if authenticated && commit(&tag) {
689                        return Err(PacketReplay);
690                    }
691                    return Err(error.into());
692                }
693            };
694
695            // Closes the race between `is_replay` above and this insertion: of two concurrent decodes of the
696            // same packet, exactly one commits and the other is told it is the duplicate.
697            if commit(&tag) {
698                return Err(PacketReplay);
699            }
700
701            Self::from_forwarded_meta_packet(forwarded, pre_ticket, previous_hop)
702        } else {
703            Err(PacketDecodingError("packet has invalid size".into()))
704        }
705    }
706
707    /// Deserializes the packet and performs the forward-transformation, so the
708    /// packet can be further delivered (relayed to the next hop or read).
709    ///
710    /// Equivalent to [`HoprPacket::from_incoming_checked`] with no replay filter: the size check and parse live
711    /// there, so the two cannot diverge in which packets they accept.
712    pub fn from_incoming<M, F>(
713        data: &[u8],
714        node_keypair: &OffchainKeypair,
715        previous_hop: OffchainPublicKey,
716        mapper: &M,
717        reply_openers: F,
718    ) -> Result<Self>
719    where
720        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
721        F: FnMut(&HoprSenderId) -> Option<ReplyOpener>,
722    {
723        Self::from_incoming_checked(
724            data,
725            node_keypair,
726            previous_hop,
727            mapper,
728            reply_openers,
729            |_| false,
730            |_| false,
731        )
732    }
733
734    /// Turns a transformed packet into the [`HoprPacket`] the rest of the stack consumes.
735    ///
736    /// Shared by [`HoprPacket::from_incoming`] and [`HoprPacket::from_incoming_checked`], so that the checked
737    /// constructor cannot drift from the unchecked one in what it returns.
738    fn from_forwarded_meta_packet(
739        forwarded: ForwardedMetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>,
740        pre_ticket: &[u8],
741        previous_hop: OffchainPublicKey,
742    ) -> Result<Self> {
743        match forwarded {
744            ForwardedMetaPacket::Relayed {
745                packet,
746                derived_secret,
747                additional_info,
748                packet_tag,
749                next_node,
750                path_pos,
751                ..
752            } => {
753                let ack_key = derive_ack_key_share(&derived_secret);
754
755                let ticket = Ticket::try_from(pre_ticket)?;
756                let verification_output = pre_verify(&derived_secret, &additional_info, &ticket.challenge)?;
757                Ok(Self::Forwarded(
758                    HoprForwardedPacket {
759                        outgoing: HoprOutgoingPacket {
760                            packet,
761                            ticket,
762                            next_hop: next_node,
763                            ack_challenge: verification_output.ack_challenge,
764                            encrypted_pix_share: None,
765                            final_packet_tag: None,
766                        },
767                        packet_tag,
768                        ack_key,
769                        previous_hop,
770                        path_pos,
771                        own_key: verification_output.own_key,
772                        next_challenge: verification_output.next_ticket_challenge,
773                    }
774                    .into(),
775                ))
776            }
777            ForwardedMetaPacket::Final {
778                packet_tag,
779                plain_text,
780                derived_secret,
781                receiver_data,
782                no_ack,
783            } => {
784                // The pre_ticket is not parsed nor verified on the final hop
785                let HoprReceivedPacketParts {
786                    surbs,
787                    payload,
788                    signals,
789                } = HoprPacketMessage::from(plain_text).try_into()?;
790                let should_acknowledge = !no_ack;
791                Ok(Self::Final(
792                    HoprIncomingPacket {
793                        packet_tag,
794                        ack_key: should_acknowledge.then(|| derive_ack_key_share(&derived_secret)),
795                        previous_hop,
796                        plain_text: payload,
797                        surbs: receiver_data.into_sequence().map(|d| d.surb_id()).zip(surbs).collect(),
798                        sender: receiver_data.pseudonym(),
799                        signals,
800                    }
801                    .into(),
802                ))
803            }
804        }
805    }
806}
807
808#[cfg(test)]
809mod tests {
810    use anyhow::{Context, bail};
811    use bimap::BiHashMap;
812    use hex_literal::hex;
813    use hopr_protocol_pix::SsaGeneratorConfig;
814    use hopr_types::crypto_random::Randomizable;
815    use parameterized::parameterized;
816
817    use super::*;
818    use crate::{expand::DirectKeyExpander, types::PacketSignal};
819
820    lazy_static::lazy_static! {
821        static ref PEERS: [(ChainKeypair, OffchainKeypair); 5] = [
822            (hex!("a7c486ceccf5ab53bd428888ab1543dc2667abd2d5e80aae918da8d4b503a426"), hex!("5eb212d4d6aa5948c4f71574d45dad43afef6d330edb873fca69d0e1b197e906")),
823            (hex!("9a82976f7182c05126313bead5617c623b93d11f9f9691c87b1a26f869d569ed"), hex!("e995db483ada5174666c46bafbf3628005aca449c94ebdc0c9239c3f65d61ae0")),
824            (hex!("ca4bdfd54a8467b5283a0216288fdca7091122479ccf3cfb147dfa59d13f3486"), hex!("9dec751c00f49e50fceff7114823f726a0425a68a8dc6af0e4287badfea8f4a4")),
825            (hex!("e306ebfb0d01d0da0952c9a567d758093a80622c6cb55052bf5f1a6ebd8d7b5c"), hex!("9a82976f7182c05126313bead5617c623b93d11f9f9691c87b1a26f869d569ed")),
826            (hex!("492057cf93e99b31d2a85bc5e98a9c3aa0021feec52c227cc8170e8f7d047775"), hex!("e0bf93e9c916104da00b1850adc4608bd7e9087bbd3f805451f4556aa6b3fd6e")),
827        ].map(|(p1,p2)| (ChainKeypair::from_secret(&p1).expect("lazy static keypair should be valid"), OffchainKeypair::from_secret(&p2).expect("lazy static keypair should be valid")));
828
829        static ref MAPPER: SimpleBiMapper<HoprSphinxSuite, HoprSphinxHeaderSpec> = PEERS
830            .iter()
831            .enumerate()
832            .map(|(i, (_, k))| (KeyIdent::from(i as u32), *k.public()))
833            .collect::<BiHashMap<_, _>>()
834            .into();
835    }
836
837    /// Re-signs a forwarded packet's ticket so the next hop sees this node as its issuer.
838    fn forward(
839        mut packet: HoprPacket,
840        chain_keypair: &ChainKeypair,
841        next_ticket: TicketBuilder,
842        domain_separator: &Hash,
843    ) -> HoprPacket {
844        if let HoprPacket::Forwarded(fwd) = &mut packet {
845            fwd.outgoing.ticket = next_ticket
846                .eth_challenge(fwd.next_challenge)
847                .build_signed(chain_keypair, domain_separator)
848                .expect("ticket should create")
849                .leak();
850        }
851
852        packet
853    }
854
855    impl HoprPacket {
856        /// Serializes the packet the way the wire format expects: sphinx payload then ticket.
857        pub fn to_bytes(&self) -> Box<[u8]> {
858            let dummy_ticket = hex!(
859                "67f0ca18102feec505e5bfedcc25963e9c64a6f8a250adcad7d2830dd607585700000000000000000000000000000000000000000000000000000000000000003891bf6fd4a78e868fc7ad477c09b16fc70dd01ea67e18264d17e3d04f6d8576de2e6472b0072e510df6e9fa1dfcc2727cc7633edfeb9ec13860d9ead29bee71d68de3736c2f7a9f42de76ccd57a5f5847bc7349"
860            );
861            let (packet, ticket) = match self {
862                Self::Final(packet) => (packet.plain_text.as_ref().into(), dummy_ticket.as_ref().into()),
863                Self::Forwarded(fwd) => (
864                    Vec::from(fwd.outgoing.packet.as_ref()).into_boxed_slice(),
865                    fwd.outgoing.ticket.into_boxed(),
866                ),
867                Self::Outgoing(out) => (
868                    Vec::from(out.packet.as_ref()).into_boxed_slice(),
869                    out.ticket.into_boxed(),
870                ),
871            };
872
873            let mut ret = Vec::with_capacity(Self::SIZE);
874            ret.extend_from_slice(packet.as_ref());
875            ret.extend_from_slice(&ticket);
876            ret.into_boxed_slice()
877        }
878    }
879
880    /// A ticket builder for a path of `path_len` hops to `next_peer_channel_key`.
881    fn mock_ticket(next_peer_channel_key: &PublicKey, path_len: usize) -> anyhow::Result<TicketBuilder> {
882        assert!(path_len > 0);
883        let price_per_packet: U256 = 10000000000000000u128.into();
884
885        if path_len > 1 {
886            Ok(TicketBuilder::default()
887                .counterparty(next_peer_channel_key.to_address())
888                .amount(price_per_packet.div_f64(1.0)? * U256::from(path_len as u64 - 1))
889                .index(1)
890                .win_prob(WinningProbability::ALWAYS)
891                .channel_epoch(1)
892                .eth_challenge(Default::default()))
893        } else {
894            Ok(TicketBuilder::zero_hop().counterparty(next_peer_channel_key.to_address()))
895        }
896    }
897
898    const FLAGS: PacketSignal = PacketSignal::OutOfSurbs;
899
900    /// Builds an outgoing packet with the given forward path and optional return paths.
901    fn create_packet(
902        forward_hops: usize,
903        pseudonym: HoprPseudonym,
904        return_hops: Vec<usize>,
905        msg: &[u8],
906    ) -> anyhow::Result<(HoprPacket, Vec<HoprReplyOpener>)> {
907        assert!((0..=3).contains(&forward_hops), "forward hops must be between 1 and 3");
908        assert!(
909            return_hops.iter().all(|h| (0..=3).contains(h)),
910            "return hops must be between 1 and 3"
911        );
912
913        let ticket = mock_ticket(PEERS[1].0.public(), forward_hops + 1)?;
914        let forward_path = TransportPath::new(PEERS[1..=forward_hops + 1].iter().map(|kp| *kp.1.public()))?;
915
916        let return_paths = return_hops
917            .into_iter()
918            .map(|h| TransportPath::new(PEERS[0..=h].iter().rev().map(|kp| *kp.1.public())))
919            .collect::<std::result::Result<Vec<_>, hopr_types::internal::errors::PathError>>()?;
920
921        let ssa_gen = hopr_protocol_pix::SsaShareGenerator::new(SsaGeneratorConfig::default());
922
923        Ok(HoprPacket::into_outgoing(
924            msg,
925            &pseudonym,
926            PacketRouting::ForwardPath {
927                forward_path,
928                return_paths,
929                generation: 0,
930            },
931            &PEERS[0].0,
932            ticket,
933            &*MAPPER,
934            &DirectKeyExpander,
935            &Hash::default(),
936            &ssa_gen,
937            FLAGS,
938        )?)
939    }
940
941    /// Builds a reply packet over `surb`, signed by the node at `sender_node`.
942    fn create_packet_from_surb(
943        sender_node: usize,
944        surb_id: HoprSurbId,
945        surb: HoprSurb,
946        hopr_pseudonym: &HoprPseudonym,
947        msg: &[u8],
948    ) -> anyhow::Result<HoprPacket> {
949        assert!((1..=4).contains(&sender_node), "sender_node must be between 1 and 4");
950
951        let ticket = mock_ticket(
952            PEERS[sender_node - 1].0.public(),
953            surb.additional_data_receiver.proof_of_relay_values().chain_length() as usize,
954        )?;
955
956        let ssa_gen = hopr_protocol_pix::SsaShareGenerator::new(SsaGeneratorConfig::default());
957
958        Ok(HoprPacket::into_outgoing(
959            msg,
960            hopr_pseudonym,
961            PacketRouting::<TransportPath>::Surb(HoprSenderId::from_pseudonym_and_id(hopr_pseudonym, surb_id), surb),
962            &PEERS[sender_node].0,
963            ticket,
964            &*MAPPER,
965            &DirectKeyExpander,
966            &Hash::default(),
967            &ssa_gen,
968            FLAGS,
969        )?
970        .0)
971    }
972
973    fn process_packet_at_node<F>(
974        path_len: usize,
975        node_pos: usize,
976        is_reply: bool,
977        packet: HoprPacket,
978        openers: F,
979    ) -> anyhow::Result<HoprPacket>
980    where
981        F: FnMut(&HoprSenderId) -> Option<ReplyOpener>,
982    {
983        assert!((0..=4).contains(&node_pos), "node position must be between 1 and 3");
984
985        let prev_hop = match (node_pos, is_reply) {
986            (1, false) => *PEERS[0].1.public(),
987            (_, false) => *PEERS[node_pos - 1].1.public(),
988            (3, true) => *PEERS[4].1.public(),
989            (_, true) => *PEERS[node_pos + 1].1.public(),
990        };
991
992        let packet = HoprPacket::from_incoming(&packet.to_bytes(), &PEERS[node_pos].1, prev_hop, &*MAPPER, openers)
993            .context(format!("deserialization failure at hop {node_pos}"))?;
994
995        match &packet {
996            HoprPacket::Final(_) => Ok(packet),
997            HoprPacket::Forwarded(_) => {
998                let next_hop = match (node_pos, is_reply) {
999                    (3, false) => *PEERS[4].0.public(),
1000                    (_, false) => *PEERS[node_pos + 1].0.public(),
1001                    (1, true) => *PEERS[0].0.public(),
1002                    (_, true) => *PEERS[node_pos - 1].0.public(),
1003                };
1004
1005                let next_ticket = mock_ticket(&next_hop, path_len)?;
1006                Ok(forward(
1007                    packet.clone(),
1008                    &PEERS[node_pos].0,
1009                    next_ticket,
1010                    &Hash::default(),
1011                ))
1012            }
1013            HoprPacket::Outgoing(_) => bail!("invalid packet state"),
1014        }
1015    }
1016
1017    #[test]
1018    fn relayed_packet_frame_should_reuse_the_received_buffer() -> anyhow::Result<()> {
1019        let (packet, _) = create_packet(2, SimplePseudonym::random(), vec![], b"relay me")?;
1020        let wire = packet.to_bytes();
1021        let relayed = HoprPacket::from_incoming(&wire, &PEERS[1].1, *PEERS[0].1.public(), &*MAPPER, |_| None)?
1022            .try_as_forwarded()
1023            .context("packet is not forwarded")?;
1024
1025        let packet_ptr = relayed.outgoing.packet.as_ref().as_ptr();
1026        let packet_bytes = relayed.outgoing.packet.as_ref().to_vec();
1027        let ticket = relayed.outgoing.ticket;
1028        let frame = HoprOutgoingPacket::frame(relayed.outgoing.packet, ticket);
1029
1030        assert_eq!(HoprPacket::SIZE, frame.len());
1031        assert_eq!(packet_ptr, frame.as_ptr(), "the packet must not be copied");
1032        assert_eq!(packet_bytes, frame[..packet_bytes.len()]);
1033        assert_eq!(ticket.into_encoded().as_ref(), &frame[packet_bytes.len()..]);
1034        Ok(())
1035    }
1036
1037    #[test]
1038    fn meta_packet_from_vec_should_keep_the_buffer_and_check_its_size() -> anyhow::Result<()> {
1039        type Packet = MetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>;
1040
1041        let mut buffer = Vec::with_capacity(HoprPacket::SIZE);
1042        buffer.resize(Packet::SIZE, 7);
1043        let buffer_ptr = buffer.as_ptr();
1044
1045        let buffer = Packet::try_from(buffer)?.into_vec();
1046        assert_eq!(buffer_ptr, buffer.as_ptr());
1047        assert!(buffer.capacity() >= HoprPacket::SIZE);
1048
1049        assert_eq!(Packet::try_from(buffer.as_slice())?.as_ref(), buffer.as_slice());
1050        assert!(Packet::try_from(&buffer[..Packet::SIZE - 1]).is_err());
1051
1052        assert!(Packet::try_from(vec![0u8; Packet::SIZE - 1]).is_err());
1053        assert!(Packet::try_from(vec![0u8; Packet::SIZE + 1]).is_err());
1054        Ok(())
1055    }
1056
1057    #[test]
1058    fn relaying_should_fail_when_the_next_hop_key_cannot_be_resolved() -> anyhow::Result<()> {
1059        let (packet, _) = create_packet(2, SimplePseudonym::random(), vec![], b"relay me")?;
1060
1061        // The mapper of the first relayer does not know the next hop (node 2)
1062        let mapper: SimpleBiMapper<HoprSphinxSuite, HoprSphinxHeaderSpec> = PEERS
1063            .iter()
1064            .enumerate()
1065            .filter(|(i, _)| *i != 2)
1066            .map(|(i, (_, k))| (KeyIdent::from(i as u32), *k.public()))
1067            .collect::<BiHashMap<_, _>>()
1068            .into();
1069
1070        let error = HoprPacket::from_incoming(&packet.to_bytes(), &PEERS[1].1, *PEERS[0].1.public(), &mapper, |_| None)
1071            .err()
1072            .context("the packet must not decode")?;
1073        assert!(
1074            error.to_string().contains("map id to public key"),
1075            "unexpected: {error}"
1076        );
1077
1078        Ok(())
1079    }
1080
1081    #[parameterized(hops = { 0,1,2,3 })]
1082    fn test_packet_forward_message_no_surb(hops: usize) -> anyhow::Result<()> {
1083        let msg = b"some testing forward message";
1084        let pseudonym = SimplePseudonym::random();
1085        let (mut packet, opener) = create_packet(hops, pseudonym, vec![], msg)?;
1086
1087        assert!(opener.is_empty());
1088        match &packet {
1089            HoprPacket::Outgoing { .. } => {}
1090            _ => bail!("invalid packet initial state"),
1091        }
1092
1093        let mut actual_plain_text = Bytes::new();
1094        for hop in 1..=hops + 1 {
1095            packet = process_packet_at_node(hops + 1, hop, false, packet, |_| None)
1096                .context(format!("packet decoding failed at hop {hop}"))?;
1097
1098            match &packet {
1099                HoprPacket::Final(packet) => {
1100                    assert_eq!(hop - 1, hops, "final packet must be at the last hop");
1101                    assert!(packet.ack_key.is_some(), "must not be a no-ack packet");
1102                    assert_eq!(PacketSignals::from(FLAGS), packet.signals);
1103                    actual_plain_text = packet.plain_text.clone();
1104                }
1105                HoprPacket::Forwarded(fwd) => {
1106                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
1107                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
1108                    assert_eq!(hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
1109                }
1110                HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop}"),
1111            }
1112        }
1113
1114        assert_eq!(actual_plain_text.as_ref(), msg, "invalid plaintext");
1115        Ok(())
1116    }
1117
1118    #[parameterized(forward_hops = { 0,1,2,3 }, return_hops = { 0, 1, 2, 3})]
1119    fn test_packet_forward_message_with_surb(forward_hops: usize, return_hops: usize) -> anyhow::Result<()> {
1120        let msg = b"some testing forward message";
1121        let pseudonym = SimplePseudonym::random();
1122        let (mut packet, openers) = create_packet(forward_hops, pseudonym, vec![return_hops], msg)?;
1123
1124        assert_eq!(1, openers.len(), "invalid number of openers");
1125        match &packet {
1126            HoprPacket::Outgoing { .. } => {}
1127            _ => bail!("invalid packet initial state"),
1128        }
1129
1130        let mut received_plain_text = Bytes::new();
1131        let mut received_surbs = vec![];
1132        for hop in 1..=forward_hops + 1 {
1133            packet = process_packet_at_node(forward_hops + 1, hop, false, packet, |_| None)
1134                .context(format!("packet decoding failed at hop {hop}"))?;
1135
1136            match &packet {
1137                HoprPacket::Final(packet) => {
1138                    assert_eq!(hop - 1, forward_hops, "final packet must be at the last hop");
1139                    assert_eq!(pseudonym, packet.sender, "invalid sender");
1140                    assert!(packet.ack_key.is_some(), "must not be a no-ack packet");
1141                    assert_eq!(PacketSignals::from(FLAGS), packet.signals);
1142                    received_plain_text = packet.plain_text.clone();
1143                    received_surbs.extend(packet.surbs.clone());
1144                }
1145                HoprPacket::Forwarded(fwd) => {
1146                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
1147                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
1148                    assert_eq!(forward_hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
1149                }
1150                HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop}"),
1151            }
1152        }
1153
1154        assert_eq!(received_plain_text.as_ref(), msg, "invalid plaintext");
1155        assert_eq!(1, received_surbs.len(), "invalid number of surbs");
1156        assert_eq!(
1157            return_hops as u8 + 1,
1158            received_surbs[0]
1159                .1
1160                .additional_data_receiver
1161                .proof_of_relay_values()
1162                .chain_length(),
1163            "surb has invalid por chain length"
1164        );
1165
1166        Ok(())
1167    }
1168
1169    #[parameterized(
1170        forward_hops = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 },
1171        return_hops  = { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }
1172    )]
1173    fn test_packet_forward_and_reply_message(forward_hops: usize, return_hops: usize) -> anyhow::Result<()> {
1174        let pseudonym = SimplePseudonym::random();
1175
1176        // Forward packet
1177        let fwd_msg = b"some testing forward message";
1178        let (mut fwd_packet, mut openers) = create_packet(forward_hops, pseudonym, vec![return_hops], fwd_msg)?;
1179
1180        assert_eq!(1, openers.len(), "invalid number of openers");
1181        match &fwd_packet {
1182            HoprPacket::Outgoing { .. } => {}
1183            _ => bail!("invalid packet initial state"),
1184        }
1185
1186        let mut received_fwd_plain_text = Bytes::new();
1187        let mut received_surbs = vec![];
1188        for hop in 1..=forward_hops + 1 {
1189            fwd_packet = process_packet_at_node(forward_hops + 1, hop, false, fwd_packet, |_| None)
1190                .context(format!("packet decoding failed at hop {hop}"))?;
1191
1192            match &fwd_packet {
1193                HoprPacket::Final(incoming) => {
1194                    assert_eq!(hop - 1, forward_hops, "final packet must be at the last hop");
1195                    assert_eq!(pseudonym, incoming.sender, "invalid sender");
1196                    assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
1197                    assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
1198                    received_fwd_plain_text = incoming.plain_text.clone();
1199                    received_surbs.extend(incoming.surbs.clone());
1200                }
1201                HoprPacket::Forwarded(fwd) => {
1202                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
1203                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
1204                    assert_eq!(forward_hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
1205                }
1206                HoprPacket::Outgoing { .. } => bail!("invalid packet state at hop {hop}"),
1207            }
1208        }
1209
1210        assert_eq!(received_fwd_plain_text.as_ref(), fwd_msg, "invalid plaintext");
1211        assert_eq!(1, received_surbs.len(), "invalid number of surbs");
1212        assert_eq!(
1213            return_hops as u8 + 1,
1214            received_surbs[0]
1215                .1
1216                .additional_data_receiver
1217                .proof_of_relay_values()
1218                .chain_length(),
1219            "surb has invalid por chain length"
1220        );
1221
1222        // The reply packet
1223        let re_msg = b"some testing reply message";
1224        let mut re_packet = create_packet_from_surb(
1225            forward_hops + 1,
1226            received_surbs[0].0,
1227            received_surbs[0].1.clone(),
1228            &pseudonym,
1229            re_msg,
1230        )?;
1231
1232        let mut openers_fn = |p: &HoprSenderId| {
1233            assert_eq!(p.pseudonym(), pseudonym);
1234            let opener = openers.pop();
1235            assert!(opener.as_ref().is_none_or(|(id, _)| id == &p.surb_id()));
1236            opener.map(|(_, opener)| opener)
1237        };
1238
1239        match &re_packet {
1240            HoprPacket::Outgoing { .. } => {}
1241            _ => bail!("invalid packet initial state"),
1242        }
1243
1244        let mut received_re_plain_text = Bytes::new();
1245        for hop in (0..=return_hops).rev() {
1246            re_packet = process_packet_at_node(return_hops + 1, hop, true, re_packet, &mut openers_fn)
1247                .context(format!("packet decoding failed at hop {hop}"))?;
1248
1249            match &re_packet {
1250                HoprPacket::Final(incoming) => {
1251                    assert_eq!(hop, 0, "final packet must be at the last hop");
1252                    assert_eq!(pseudonym, incoming.sender, "invalid sender");
1253                    assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
1254                    assert!(incoming.surbs.is_empty(), "must not receive surbs on reply");
1255                    assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
1256                    received_re_plain_text = incoming.plain_text.clone();
1257                }
1258                HoprPacket::Forwarded(fwd) => {
1259                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.previous_hop, "invalid previous hop");
1260                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
1261                    assert_eq!(hop, fwd.path_pos as usize, "invalid path position");
1262                }
1263                HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop}"),
1264            }
1265        }
1266
1267        assert_eq!(received_re_plain_text.as_ref(), re_msg, "invalid plaintext");
1268        Ok(())
1269    }
1270
1271    #[parameterized(
1272        forward_hops = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 },
1273        return_hops  = { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }
1274    )]
1275    fn test_packet_surbs_only_and_reply_message(forward_hops: usize, return_hops: usize) -> anyhow::Result<()> {
1276        let pseudonym = SimplePseudonym::random();
1277
1278        // Forward packet
1279        let (mut fwd_packet, mut openers) = create_packet(forward_hops, pseudonym, vec![return_hops; 2], &[])?;
1280
1281        assert_eq!(2, openers.len(), "invalid number of openers");
1282        match &fwd_packet {
1283            HoprPacket::Outgoing { .. } => {}
1284            _ => bail!("invalid packet initial state"),
1285        }
1286
1287        let mut received_surbs = vec![];
1288        for hop in 1..=forward_hops + 1 {
1289            fwd_packet = process_packet_at_node(forward_hops + 1, hop, false, fwd_packet, |_| None)
1290                .context(format!("packet decoding failed at hop {hop}"))?;
1291
1292            match &fwd_packet {
1293                HoprPacket::Final(incoming) => {
1294                    assert_eq!(hop - 1, forward_hops, "final packet must be at the last hop");
1295                    assert!(
1296                        incoming.plain_text.is_empty(),
1297                        "must not receive plaintext on surbs only packet"
1298                    );
1299                    assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
1300                    assert_eq!(2, incoming.surbs.len(), "invalid number of received surbs per packet");
1301                    assert_eq!(pseudonym, incoming.sender, "invalid sender");
1302                    assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
1303                    received_surbs.extend(incoming.surbs.clone());
1304                }
1305                HoprPacket::Forwarded(fwd) => {
1306                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
1307                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
1308                    assert_eq!(forward_hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
1309                }
1310                HoprPacket::Outgoing { .. } => bail!("invalid packet state at hop {hop}"),
1311            }
1312        }
1313
1314        assert_eq!(2, received_surbs.len(), "invalid number of surbs");
1315        for recv_surb in &received_surbs {
1316            assert_eq!(
1317                return_hops as u8 + 1,
1318                recv_surb
1319                    .1
1320                    .additional_data_receiver
1321                    .proof_of_relay_values()
1322                    .chain_length(),
1323                "surb has invalid por chain length"
1324            );
1325        }
1326
1327        let mut openers_fn = |p: &HoprSenderId| {
1328            assert_eq!(p.pseudonym(), pseudonym);
1329            let (id, opener) = openers.remove(0);
1330            assert_eq!(id, p.surb_id());
1331            Some(opener)
1332        };
1333
1334        // The reply packet
1335        for (i, recv_surb) in received_surbs.into_iter().enumerate() {
1336            let re_msg = format!("some testing reply message {i}");
1337            let mut re_packet = create_packet_from_surb(
1338                forward_hops + 1,
1339                recv_surb.0,
1340                recv_surb.1,
1341                &pseudonym,
1342                re_msg.as_bytes(),
1343            )?;
1344
1345            match &re_packet {
1346                HoprPacket::Outgoing { .. } => {}
1347                _ => bail!("invalid packet initial state in reply {i}"),
1348            }
1349
1350            let mut received_re_plain_text = Bytes::new();
1351            for hop in (0..=return_hops).rev() {
1352                re_packet = process_packet_at_node(return_hops + 1, hop, true, re_packet, &mut openers_fn)
1353                    .context(format!("packet decoding failed at hop {hop} in reply {i}"))?;
1354
1355                match &re_packet {
1356                    HoprPacket::Final(incoming) => {
1357                        assert_eq!(hop, 0, "final packet must be at the last hop for reply {i}");
1358                        assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
1359                        assert!(
1360                            incoming.surbs.is_empty(),
1361                            "must not receive surbs on reply for reply {i}"
1362                        );
1363                        assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
1364                        received_re_plain_text = incoming.plain_text.clone();
1365                    }
1366                    HoprPacket::Forwarded(fwd) => {
1367                        assert_eq!(
1368                            PEERS[hop + 1].1.public(),
1369                            &fwd.previous_hop,
1370                            "invalid previous hop in reply {i}"
1371                        );
1372                        assert_eq!(
1373                            PEERS[hop - 1].1.public(),
1374                            &fwd.outgoing.next_hop,
1375                            "invalid next hop in reply {i}"
1376                        );
1377                        assert_eq!(hop, fwd.path_pos as usize, "invalid path position in reply {i}");
1378                    }
1379                    HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop} in reply {i}"),
1380                }
1381            }
1382
1383            assert_eq!(
1384                received_re_plain_text.as_ref(),
1385                re_msg.as_bytes(),
1386                "invalid plaintext in reply {i}"
1387            );
1388        }
1389        Ok(())
1390    }
1391
1392    /// The checked constructor must report a replay through its own error, after having called the check exactly
1393    /// once, and before returning a packet.
1394    #[test]
1395    fn a_rejected_tag_should_stop_the_decode() -> anyhow::Result<()> {
1396        let (packet, _) = create_packet(1, SimplePseudonym::random(), vec![], b"replay checked")?;
1397        let wire = packet.to_bytes();
1398        let mut calls = 0;
1399        let mut commits = 0;
1400
1401        let result = HoprPacket::from_incoming_checked(
1402            &wire,
1403            &PEERS[1].1,
1404            *PEERS[0].1.public(),
1405            &*MAPPER,
1406            |_| None,
1407            |_| {
1408                calls += 1;
1409                true
1410            },
1411            |_| {
1412                commits += 1;
1413                false
1414            },
1415        );
1416
1417        assert!(
1418            matches!(result, Err(crate::errors::PacketError::PacketReplay)),
1419            "must report a replay"
1420        );
1421        assert_eq!(1, calls, "the check must be asked exactly once");
1422        assert_eq!(0, commits, "a packet rejected by the check must not be committed");
1423        Ok(())
1424    }
1425
1426    /// A tag that the check accepts must let the packet through unchanged, and both callbacks must have seen the
1427    /// tag the decoded packet carries - the invariant the decoder's replay filter relies on.
1428    #[test]
1429    fn an_accepted_tag_should_decode_to_the_same_packet() -> anyhow::Result<()> {
1430        let (packet, _) = create_packet(2, SimplePseudonym::random(), vec![], b"replay checked")?;
1431        let wire = packet.to_bytes();
1432        let mut seen = None;
1433        let mut committed = None;
1434
1435        let checked = HoprPacket::from_incoming_checked(
1436            &wire,
1437            &PEERS[1].1,
1438            *PEERS[0].1.public(),
1439            &*MAPPER,
1440            |_| None,
1441            |tag| {
1442                seen = Some(*tag);
1443                false
1444            },
1445            |tag| {
1446                committed = Some(*tag);
1447                false
1448            },
1449        )?;
1450        let unchecked = HoprPacket::from_incoming(&wire, &PEERS[1].1, *PEERS[0].1.public(), &*MAPPER, |_| None)?;
1451
1452        assert_eq!(
1453            seen.as_ref(),
1454            checked.packet_tag(),
1455            "the check must see the tag the packet carries"
1456        );
1457        assert_eq!(
1458            committed.as_ref(),
1459            checked.packet_tag(),
1460            "the commit must see the tag the packet carries"
1461        );
1462        assert_eq!(
1463            checked.packet_tag(),
1464            unchecked.packet_tag(),
1465            "the checked and unchecked constructors must derive the same tag"
1466        );
1467        Ok(())
1468    }
1469
1470    /// A packet whose header MAC does not verify must not be committed, even though its tag was derivable and the
1471    /// check let it through. This is what makes a committed token cost a well-formed packet rather than the node's
1472    /// public key.
1473    #[test]
1474    fn a_packet_failing_the_header_mac_should_not_be_committed() -> anyhow::Result<()> {
1475        let (packet, _) = create_packet(1, SimplePseudonym::random(), vec![], b"replay checked")?;
1476        let mut wire = packet.to_bytes().to_vec();
1477
1478        // Keep the alpha, so the secret - and hence the tag - is derivable, but corrupt the header after it.
1479        const ALPHA_LEN: usize = 32;
1480        wire[ALPHA_LEN..ALPHA_LEN + 64].fill(0xff);
1481
1482        let mut checked = 0;
1483        let mut committed = 0;
1484        let result = HoprPacket::from_incoming_checked(
1485            &wire,
1486            &PEERS[1].1,
1487            *PEERS[0].1.public(),
1488            &*MAPPER,
1489            |_| None,
1490            |_| {
1491                checked += 1;
1492                false
1493            },
1494            |_| {
1495                committed += 1;
1496                false
1497            },
1498        );
1499
1500        assert!(result.is_err(), "a corrupted header must not decode");
1501        assert_eq!(1, checked, "the tag is derivable, so the check runs");
1502        assert_eq!(0, committed, "a packet failing the header MAC must not be committed");
1503        Ok(())
1504    }
1505
1506    /// Every hop re-blinds the secret, so the tag a node sees differs from its predecessor's - otherwise the second
1507    /// hop would reject a legitimate packet.
1508    #[test]
1509    fn the_tag_should_differ_between_hops_of_the_same_packet() -> anyhow::Result<()> {
1510        let (packet, _) = create_packet(2, SimplePseudonym::random(), vec![], b"replay checked")?;
1511
1512        let first_tag = {
1513            let mut seen = None;
1514            HoprPacket::from_incoming_checked(
1515                &packet.to_bytes(),
1516                &PEERS[1].1,
1517                *PEERS[0].1.public(),
1518                &*MAPPER,
1519                |_| None,
1520                |tag| {
1521                    seen = Some(*tag);
1522                    false
1523                },
1524                |_| false,
1525            )?;
1526            seen.context("the check must have been called")?
1527        };
1528
1529        let forwarded = process_packet_at_node(3, 1, false, packet, |_| None)?;
1530        let second_tag = {
1531            let mut seen = None;
1532            HoprPacket::from_incoming_checked(
1533                &forwarded.to_bytes(),
1534                &PEERS[2].1,
1535                *PEERS[1].1.public(),
1536                &*MAPPER,
1537                |_| None,
1538                |tag| {
1539                    seen = Some(*tag);
1540                    false
1541                },
1542                |_| false,
1543            )?;
1544            seen.context("the check must have been called")?
1545        };
1546
1547        assert_ne!(first_tag, second_tag, "the shared secret must change at every hop");
1548        Ok(())
1549    }
1550
1551    fn outgoing_tag(packet: &HoprPacket) -> anyhow::Result<Option<PacketTag>> {
1552        match packet {
1553            HoprPacket::Outgoing(out) => Ok(out.final_packet_tag),
1554            _ => bail!("not an outgoing packet"),
1555        }
1556    }
1557
1558    /// The sender knows the tag the recipient will derive, for any path length, and it differs per packet.
1559    #[parameterized(hops = { 0, 1, 2, 3 })]
1560    fn the_final_packet_tag_should_be_known_to_the_sender(hops: usize) -> anyhow::Result<()> {
1561        let (packet, _) = create_packet(hops, SimplePseudonym::random(), vec![], b"tagged")?;
1562        let (other, _) = create_packet(hops, SimplePseudonym::random(), vec![], b"tagged")?;
1563        let sent = outgoing_tag(&packet)?.context("forward packet must carry the tag")?;
1564        assert_ne!(Some(sent), outgoing_tag(&other)?, "tags must differ per packet");
1565        let size = packet.to_bytes().len();
1566
1567        let mut packet = packet;
1568        for hop in 1..=hops + 1 {
1569            packet = process_packet_at_node(hops + 1, hop, false, packet, |_| None)?;
1570        }
1571        match packet {
1572            HoprPacket::Final(incoming) => assert_eq!(sent, incoming.packet_tag),
1573            _ => bail!("expected the final packet"),
1574        }
1575        assert_eq!(HoprPacket::SIZE, size, "the packet size must not change");
1576        Ok(())
1577    }
1578
1579    #[test]
1580    fn surb_and_no_ack_packets_should_carry_no_final_packet_tag() -> anyhow::Result<()> {
1581        let pseudonym = SimplePseudonym::random();
1582        let (packet, _) = create_packet(0, pseudonym, vec![0], b"with a surb")?;
1583        let received = process_packet_at_node(1, 1, false, packet, |_| None)?;
1584        let HoprPacket::Final(incoming) = received else {
1585            bail!("expected the final packet");
1586        };
1587        let (surb_id, surb) = incoming.surbs[0].clone();
1588        let reply = create_packet_from_surb(1, surb_id, surb, &pseudonym, b"reply")?;
1589        assert_eq!(None, outgoing_tag(&reply)?);
1590
1591        let ticket = mock_ticket(PEERS[1].0.public(), 1)?;
1592        let ssa_gen = hopr_protocol_pix::SsaShareGenerator::new(SsaGeneratorConfig::default());
1593        let (no_ack, _) = HoprPacket::into_outgoing(
1594            b"probe",
1595            &pseudonym,
1596            PacketRouting::<TransportPath>::NoAck(*PEERS[1].1.public()),
1597            &PEERS[0].0,
1598            ticket,
1599            &*MAPPER,
1600            &DirectKeyExpander,
1601            &Hash::default(),
1602            &ssa_gen,
1603            FLAGS,
1604        )?;
1605        assert_eq!(None, outgoing_tag(&no_ack)?);
1606        Ok(())
1607    }
1608
1609    /// A packet whose size is wrong must be rejected before either callback runs, so a caller whose filter is keyed
1610    /// on the tag is never asked about a buffer that has none.
1611    #[test]
1612    fn a_wrong_size_packet_should_not_reach_the_replay_predicate() {
1613        let checked = std::cell::Cell::new(0);
1614        let committed = std::cell::Cell::new(0);
1615        let result = HoprPacket::from_incoming_checked(
1616            &[0u8; 100],
1617            &PEERS[1].1,
1618            *PEERS[0].1.public(),
1619            &*MAPPER,
1620            |_| None,
1621            |_| {
1622                checked.set(checked.get() + 1);
1623                false
1624            },
1625            |_| {
1626                committed.set(committed.get() + 1);
1627                false
1628            },
1629        );
1630
1631        assert!(result.is_err(), "a short buffer must not decode");
1632        assert_eq!(0, checked.get(), "the check must not be called for a wrong-size buffer");
1633        assert_eq!(
1634            0,
1635            committed.get(),
1636            "the commit must not be called for a wrong-size buffer"
1637        );
1638    }
1639}