Skip to main content

hopr_crypto_packet/
packet.rs

1use std::fmt::Formatter;
2
3use hopr_crypto_sphinx::prelude::*;
4#[cfg(feature = "rayon")]
5use hopr_parallelize::cpu::rayon::prelude::*;
6use hopr_types::{
7    crypto::prelude::*,
8    internal::{
9        prelude::*,
10        routing::{HoprSenderId, HoprSurbId},
11    },
12    primitive::prelude::*,
13};
14
15use crate::{
16    HoprPseudonym, HoprReplyOpener, HoprSphinxHeaderSpec, HoprSphinxSuite, HoprSurb, PAYLOAD_SIZE_INT,
17    errors::{
18        PacketError::{PacketConstructionError, PacketDecodingError},
19        Result,
20    },
21    por::{
22        ProofOfRelayString, ProofOfRelayValues, SurbReceiverInfo, derive_ack_key_share, generate_proof_of_relay,
23        pre_verify,
24    },
25    types::{HoprPacketMessage, HoprPacketParts, PacketSignals},
26};
27
28/// Represents an outgoing packet that has been only partially instantiated.
29///
30/// It contains [`PartialPacket`], required Proof-of-Relay
31/// fields, and the [`Ticket`], but it does not contain the payload.
32///
33/// This can be used to pre-compute packets for certain destinations,
34/// and [convert](PartialHoprPacket::into_hopr_packet) them to full packets
35/// once the payload is known.
36#[derive(Clone)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38pub struct PartialHoprPacket {
39    partial_packet: PartialPacket<HoprSphinxSuite, HoprSphinxHeaderSpec>,
40    surbs: Vec<HoprSurb>,
41    openers: Vec<HoprReplyOpener>,
42    ticket: Ticket,
43    next_hop: OffchainPublicKey,
44    ack_challenge: HalfKeyChallenge,
45}
46
47/// Shared key data for a path.
48///
49/// This contains the derived shared secrets and Proof of Relay data for a path.
50struct PathKeyData {
51    /// Shared secrets for the path.
52    pub shared_keys: SharedKeys<<HoprSphinxSuite as SphinxSuite>::E, <HoprSphinxSuite as SphinxSuite>::G>,
53    /// Proof of Relay data for each hop on the path.
54    pub por_strings: Vec<ProofOfRelayString>,
55    /// Proof of Relay values for the first ticket on the path.
56    pub por_values: ProofOfRelayValues,
57}
58
59impl PathKeyData {
60    fn new(path: &[OffchainPublicKey]) -> Result<Self> {
61        let shared_keys = HoprSphinxSuite::new_shared_keys(path)?;
62        let (por_strings, por_values) = generate_proof_of_relay(&shared_keys.secrets)?;
63
64        Ok(Self {
65            shared_keys,
66            por_strings,
67            por_values,
68        })
69    }
70
71    /// Computes `PathKeyData` for the given paths.
72    ///
73    /// Uses parallel processing if the `rayon` feature is enabled.
74    fn iter_from_paths(paths: Vec<&[OffchainPublicKey]>) -> Result<impl Iterator<Item = Self> + use<>> {
75        #[cfg(not(feature = "rayon"))]
76        let paths = paths.into_iter();
77
78        #[cfg(feature = "rayon")]
79        let paths = paths.into_par_iter();
80
81        paths
82            .map(Self::new)
83            .collect::<Result<Vec<_>>>()
84            .map(|paths| paths.into_iter())
85    }
86}
87
88impl PartialHoprPacket {
89    /// Instantiates a new partial HOPR packet.
90    ///
91    /// # Arguments
92    ///
93    /// * `pseudonym` our pseudonym as packet sender.
94    /// * `routing` routing to the destination.
95    /// * `chain_keypair` private key of the local node.
96    /// * `ticket` ticket builder for the first hop on the path.
97    /// * `mapper` of the public key identifiers.
98    /// * `domain_separator` channels contract domain separator.
99    pub fn new<
100        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
101        P: NonEmptyPath<OffchainPublicKey> + Send,
102    >(
103        pseudonym: &HoprPseudonym,
104        routing: PacketRouting<P>,
105        chain_keypair: &ChainKeypair,
106        ticket: TicketBuilder,
107        mapper: &M,
108        domain_separator: &Hash,
109    ) -> Result<Self> {
110        match routing {
111            PacketRouting::ForwardPath {
112                forward_path,
113                return_paths,
114            } => {
115                // Create shared secrets and PoR challenge chain for forward and return paths
116                let mut key_data = PathKeyData::iter_from_paths(
117                    std::iter::once(forward_path.hops())
118                        .chain(return_paths.iter().map(|p| p.hops()))
119                        .collect(),
120                )?;
121
122                let PathKeyData {
123                    shared_keys,
124                    por_strings,
125                    por_values,
126                } = key_data
127                    .next()
128                    .ok_or_else(|| PacketConstructionError("empty path".into()))?;
129
130                let receiver_data = HoprSenderId::new(pseudonym);
131
132                // Create SURBs if some return paths were specified
133                // Possibly makes little sense to parallelize this iterator via rayon,
134                // as in most cases the number of return paths is 1.
135                let (surbs, openers): (Vec<_>, Vec<_>) = key_data
136                    .zip(return_paths)
137                    .zip(receiver_data.into_sequence())
138                    .map(|((key_data, rp), data)| create_surb_for_path((rp, key_data), data, mapper))
139                    .collect::<Result<Vec<_>>>()?
140                    .into_iter()
141                    .unzip();
142
143                // Update the ticket with the challenge
144                let ticket = ticket
145                    .eth_challenge(por_values.ticket_challenge())
146                    .build_signed(chain_keypair, domain_separator)?
147                    .leak();
148
149                Ok(Self {
150                    partial_packet: PartialPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec>::new(
151                        MetaPacketRouting::ForwardPath {
152                            shared_keys,
153                            forward_path: &forward_path,
154                            receiver_data: &receiver_data,
155                            additional_data_relayer: &por_strings,
156                            no_ack: false,
157                        },
158                        mapper,
159                    )?,
160                    surbs,
161                    openers,
162                    ticket,
163                    next_hop: forward_path[0],
164                    ack_challenge: por_values.acknowledgement_challenge(),
165                })
166            }
167            PacketRouting::Surb(id, surb) => {
168                // Update the ticket with the challenge
169                let ticket = ticket
170                    .eth_challenge(surb.additional_data_receiver.proof_of_relay_values().ticket_challenge())
171                    .build_signed(chain_keypair, domain_separator)?
172                    .leak();
173
174                Ok(Self {
175                    ticket,
176                    next_hop: mapper.map_id_to_public(&surb.first_relayer).ok_or_else(|| {
177                        PacketConstructionError(format!(
178                            "failed to map key id {} to public key",
179                            surb.first_relayer.to_hex()
180                        ))
181                    })?,
182                    ack_challenge: surb
183                        .additional_data_receiver
184                        .proof_of_relay_values()
185                        .acknowledgement_challenge(),
186                    partial_packet: PartialPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec>::new(
187                        MetaPacketRouting::Surb(surb, &HoprSenderId::from_pseudonym_and_id(pseudonym, id)),
188                        mapper,
189                    )?,
190                    surbs: vec![],
191                    openers: vec![],
192                })
193            }
194            PacketRouting::NoAck(destination) => {
195                // Create shared secrets and PoR challenge chain
196                let PathKeyData {
197                    shared_keys,
198                    por_strings,
199                    por_values,
200                    ..
201                } = PathKeyData::new(&[destination])?;
202
203                // Update the ticket with the challenge
204                let ticket = ticket
205                    .eth_challenge(por_values.ticket_challenge())
206                    .build_signed(chain_keypair, domain_separator)?
207                    .leak();
208
209                Ok(Self {
210                    partial_packet: PartialPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec>::new(
211                        MetaPacketRouting::ForwardPath {
212                            shared_keys,
213                            forward_path: &[destination],
214                            receiver_data: &HoprSenderId::new(pseudonym),
215                            additional_data_relayer: &por_strings,
216                            no_ack: true, // Indicate this is a no-acknowledgement probe packet
217                        },
218                        mapper,
219                    )?,
220                    ticket,
221                    next_hop: destination,
222                    ack_challenge: por_values.acknowledgement_challenge(),
223                    surbs: vec![],
224                    openers: vec![],
225                })
226            }
227        }
228    }
229
230    /// Turns this partial HOPR packet into a full [`Outgoing`](HoprPacket::Outgoing) [`HoprPacket`] by
231    /// attaching the given payload `msg` and optional packet `signals` for the recipient.
232    ///
233    /// No `signals` are equivalent to `0`.
234    pub fn into_hopr_packet<S: Into<PacketSignals>>(
235        self,
236        msg: &[u8],
237        signals: S,
238    ) -> Result<(HoprPacket, Vec<HoprReplyOpener>)> {
239        let msg = HoprPacketMessage::try_from(HoprPacketParts {
240            surbs: self.surbs,
241            payload: msg.into(),
242            signals: signals.into(),
243        })?;
244        Ok((
245            HoprPacket::Outgoing(
246                HoprOutgoingPacket {
247                    packet: self.partial_packet.into_meta_packet(msg.into()),
248                    ticket: self.ticket,
249                    next_hop: self.next_hop,
250                    ack_challenge: self.ack_challenge,
251                }
252                .into(),
253            ),
254            self.openers,
255        ))
256    }
257}
258
259/// Represents a packet incoming to its final destination.
260#[derive(Clone)]
261pub struct HoprIncomingPacket {
262    /// Packet's authentication tag.
263    pub packet_tag: PacketTag,
264    /// Acknowledgement to be sent to the previous hop.
265    ///
266    /// In case an acknowledgement is not required, this field is `None`. This arises specifically
267    /// in case the message payload is used to send one or more acknowledgements in the payload.
268    pub ack_key: Option<HalfKey>,
269    /// Address of the previous hop.
270    pub previous_hop: OffchainPublicKey,
271    /// Decrypted packet payload.
272    pub plain_text: Box<[u8]>,
273    /// Pseudonym of the packet creator.
274    pub sender: HoprPseudonym,
275    /// List of [`SURBs`](SURB) to be used for replies sent to the packet creator.
276    pub surbs: Vec<(HoprSurbId, HoprSurb)>,
277    /// Additional packet signals from the lower protocol layer passed from the packet sender.
278    ///
279    /// Zero if no signal flags were specified.
280    pub signals: PacketSignals,
281}
282
283impl std::fmt::Debug for HoprIncomingPacket {
284    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
285        f.debug_struct("HoprIncomingPacket")
286            .field("packet_tag", &self.packet_tag)
287            .field("ack_key", &self.ack_key)
288            .field("previous_hop", &self.previous_hop)
289            .field("sender", &self.sender)
290            .field("signals", &self.signals)
291            .finish_non_exhaustive()
292    }
293}
294
295/// Represents a packet destined for another node.
296#[derive(Clone)]
297pub struct HoprOutgoingPacket {
298    /// Encrypted packet.
299    pub packet: MetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>,
300    /// Ticket for this node.
301    pub ticket: Ticket,
302    /// Next hop this packet should be sent to.
303    pub next_hop: OffchainPublicKey,
304    /// Acknowledgement challenge solved once the next hop sends us an acknowledgement.
305    pub ack_challenge: HalfKeyChallenge,
306}
307
308impl std::fmt::Debug for HoprOutgoingPacket {
309    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
310        f.debug_struct("HoprOutgoingPacket")
311            .field("ticket", &self.ticket)
312            .field("next_hop", &self.next_hop)
313            .field("ack_challenge", &self.ack_challenge)
314            .finish_non_exhaustive()
315    }
316}
317
318/// Represents a [`HoprOutgoingPacket`] with additional forwarding information.
319#[derive(Clone)]
320pub struct HoprForwardedPacket {
321    /// Packet to be sent.
322    pub outgoing: HoprOutgoingPacket,
323    /// Authentication tag of the packet's header.
324    pub packet_tag: PacketTag,
325    /// Acknowledgement to be sent to the previous hop.
326    pub ack_key: HalfKey,
327    /// Sender of this packet.
328    pub previous_hop: OffchainPublicKey,
329    /// Key used to verify our challenge.
330    pub own_key: HalfKey,
331    /// Challenge for the next hop.
332    pub next_challenge: EthereumChallenge,
333    /// Our position in the path.
334    pub path_pos: u8,
335}
336
337impl std::fmt::Debug for HoprForwardedPacket {
338    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
339        f.debug_struct("HoprForwardedPacket")
340            .field("outgoing", &self.outgoing)
341            .field("packet_tag", &hex::encode(self.packet_tag))
342            .field("ack_key", &self.ack_key)
343            .field("previous_hop", &self.previous_hop)
344            .field("own_key", &self.own_key)
345            .field("next_challenge", &self.next_challenge)
346            .field("path_pos", &self.path_pos)
347            .finish_non_exhaustive()
348    }
349}
350
351/// Contains HOPR packet and its variants.
352///
353/// See [`HoprIncomingPacket`], [`HoprForwardedPacket`] and [`HoprOutgoingPacket`] for details.
354///
355/// The members are intentionally boxed to equalize the variant sizes.
356#[derive(Clone, Debug, strum::EnumTryAs, strum::EnumIs, strum::IntoStaticStr, strum::Display)]
357pub enum HoprPacket {
358    /// The packet is intended for us
359    #[strum(to_string = "Final")]
360    Final(Box<HoprIncomingPacket>),
361    /// The packet must be forwarded
362    #[strum(to_string = "Forwarded")]
363    Forwarded(Box<HoprForwardedPacket>),
364    /// The packet that is being sent out by us
365    #[strum(to_string = "Outgoing")]
366    Outgoing(Box<HoprOutgoingPacket>),
367}
368
369impl HoprPacket {
370    /// Returns the [`PacketTag`] of forwarded or final packets, or `None` for outgoing packets.
371    pub fn packet_tag(&self) -> Option<&PacketTag> {
372        match self {
373            HoprPacket::Final(packet) => Some(&packet.packet_tag),
374            HoprPacket::Forwarded(packet) => Some(&packet.packet_tag),
375            HoprPacket::Outgoing(_) => None,
376        }
377    }
378}
379
380/// Determines options on how HOPR packet can be routed to its destination.
381#[derive(Clone)]
382pub enum PacketRouting<P: NonEmptyPath<OffchainPublicKey> = TransportPath> {
383    /// The packet is routed directly via the given path.
384    /// Optionally, return paths for
385    /// attached SURBs can be specified.
386    ForwardPath { forward_path: P, return_paths: Vec<P> },
387    /// The packet is routed via an existing SURB that corresponds to a pseudonym.
388    Surb(HoprSurbId, HoprSurb),
389    /// No acknowledgement packet: a special type of 0-hop packet that is not going to be acknowledged but can carry a
390    /// payload.
391    NoAck(OffchainPublicKey),
392}
393
394fn create_surb_for_path<
395    M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
396    P: NonEmptyPath<OffchainPublicKey>,
397>(
398    return_path: (P, PathKeyData),
399    recv_data: HoprSenderId,
400    mapper: &M,
401) -> Result<(HoprSurb, HoprReplyOpener)> {
402    let (
403        return_path,
404        PathKeyData {
405            shared_keys,
406            por_strings,
407            por_values,
408        },
409    ) = return_path;
410
411    Ok(create_surb::<HoprSphinxSuite, HoprSphinxHeaderSpec>(
412        shared_keys,
413        &return_path
414            .iter()
415            .map(|k| {
416                mapper
417                    .map_key_to_id(k)
418                    .ok_or_else(|| PacketConstructionError(format!("failed to map key {} to id", k.to_hex())))
419            })
420            .collect::<Result<Vec<_>>>()?,
421        &por_strings,
422        recv_data,
423        SurbReceiverInfo::new(por_values, [0u8; 32]),
424    )
425    .map(|(s, r)| (s, (recv_data.surb_id(), r)))?)
426}
427
428impl HoprPacket {
429    /// The maximum number of SURBs that fit into a packet that contains no message.
430    pub const MAX_SURBS_IN_PACKET: usize = HoprPacket::PAYLOAD_SIZE / HoprSurb::SIZE;
431    /// Maximum message size when no SURBs are present in the packet.
432    ///
433    /// See [`HoprPacket::max_surbs_with_message`].
434    pub const PAYLOAD_SIZE: usize = PAYLOAD_SIZE_INT - HoprPacketMessage::HEADER_LEN;
435    /// The size of the packet including header, padded payload, ticket, and ack challenge.
436    pub const SIZE: usize =
437        MetaPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>::PACKET_LEN + Ticket::SIZE;
438
439    /// Constructs a new outgoing packet with the given path.
440    ///
441    /// # Arguments
442    /// * `msg` packet payload.
443    /// * `pseudonym` our pseudonym as packet sender.
444    /// * `routing` routing to the destination.
445    /// * `chain_keypair` private key of the local node.
446    /// * `ticket` ticket builder for the first hop on the path.
447    /// * `mapper` of the public key identifiers.
448    /// * `domain_separator` channels contract domain separator.
449    /// * `signals` optional signals passed to the packet's final destination.
450    ///
451    /// **NOTE**
452    /// For the given pseudonym, the [`ReplyOpener`] order matters.
453    #[allow(clippy::too_many_arguments)] // TODO: needs refactoring (perhaps introduce a builder pattern?)
454    pub fn into_outgoing<
455        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
456        P: NonEmptyPath<OffchainPublicKey> + Send,
457        S: Into<PacketSignals>,
458    >(
459        msg: &[u8],
460        pseudonym: &HoprPseudonym,
461        routing: PacketRouting<P>,
462        chain_keypair: &ChainKeypair,
463        ticket: TicketBuilder,
464        mapper: &M,
465        domain_separator: &Hash,
466        signals: S,
467    ) -> Result<(Self, Vec<HoprReplyOpener>)> {
468        PartialHoprPacket::new(pseudonym, routing, chain_keypair, ticket, mapper, domain_separator)?
469            .into_hopr_packet(msg, signals)
470    }
471
472    /// Calculates how many SURBs can be fitted into a packet that
473    /// also carries a message of the given length.
474    pub const fn max_surbs_with_message(msg_len: usize) -> usize {
475        HoprPacket::PAYLOAD_SIZE.saturating_sub(msg_len) / HoprSurb::SIZE
476    }
477
478    /// Calculates the maximum length of the message that can be carried by a packet
479    /// with the given number of SURBs.
480    pub const fn max_message_with_surbs(num_surbs: usize) -> usize {
481        HoprPacket::PAYLOAD_SIZE.saturating_sub(num_surbs * HoprSurb::SIZE)
482    }
483
484    /// Deserializes the packet and performs the forward-transformation, so the
485    /// packet can be further delivered (relayed to the next hop or read).
486    pub fn from_incoming<M, F>(
487        data: &[u8],
488        node_keypair: &OffchainKeypair,
489        previous_hop: OffchainPublicKey,
490        mapper: &M,
491        reply_openers: F,
492    ) -> Result<Self>
493    where
494        M: ProtocolKeyIdMapper<HoprSphinxSuite, HoprSphinxHeaderSpec>,
495        F: FnMut(&HoprSenderId) -> Option<ReplyOpener>,
496    {
497        if data.len() == Self::SIZE {
498            let (pre_packet, pre_ticket) =
499                data.split_at(MetaPacket::<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT>::PACKET_LEN);
500
501            let mp: MetaPacket<HoprSphinxSuite, HoprSphinxHeaderSpec, PAYLOAD_SIZE_INT> =
502                MetaPacket::try_from(pre_packet)?;
503
504            match mp.into_forwarded(node_keypair, mapper, reply_openers)? {
505                ForwardedMetaPacket::Relayed {
506                    packet,
507                    derived_secret,
508                    additional_info,
509                    packet_tag,
510                    next_node,
511                    path_pos,
512                    ..
513                } => {
514                    let ack_key = derive_ack_key_share(&derived_secret);
515
516                    let ticket = Ticket::try_from(pre_ticket)?;
517                    let verification_output = pre_verify(&derived_secret, &additional_info, &ticket.challenge)?;
518                    Ok(Self::Forwarded(
519                        HoprForwardedPacket {
520                            outgoing: HoprOutgoingPacket {
521                                packet,
522                                ticket,
523                                next_hop: next_node,
524                                ack_challenge: verification_output.ack_challenge,
525                            },
526                            packet_tag,
527                            ack_key,
528                            previous_hop,
529                            path_pos,
530                            own_key: verification_output.own_key,
531                            next_challenge: verification_output.next_ticket_challenge,
532                        }
533                        .into(),
534                    ))
535                }
536                ForwardedMetaPacket::Final {
537                    packet_tag,
538                    plain_text,
539                    derived_secret,
540                    receiver_data,
541                    no_ack,
542                } => {
543                    // The pre_ticket is not parsed nor verified on the final hop
544                    let HoprPacketParts {
545                        surbs,
546                        payload,
547                        signals,
548                    } = HoprPacketMessage::from(plain_text).try_into()?;
549                    let should_acknowledge = !no_ack;
550                    Ok(Self::Final(
551                        HoprIncomingPacket {
552                            packet_tag,
553                            ack_key: should_acknowledge.then(|| derive_ack_key_share(&derived_secret)),
554                            previous_hop,
555                            plain_text: payload.into(),
556                            surbs: receiver_data.into_sequence().map(|d| d.surb_id()).zip(surbs).collect(),
557                            sender: receiver_data.pseudonym(),
558                            signals,
559                        }
560                        .into(),
561                    ))
562                }
563            }
564        } else {
565            Err(PacketDecodingError("packet has invalid size".into()))
566        }
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use anyhow::{Context, bail};
573    use bimap::BiHashMap;
574    use hex_literal::hex;
575    use hopr_types::crypto_random::Randomizable;
576    use parameterized::parameterized;
577
578    use super::*;
579    use crate::types::PacketSignal;
580
581    lazy_static::lazy_static! {
582        static ref PEERS: [(ChainKeypair, OffchainKeypair); 5] = [
583            (hex!("a7c486ceccf5ab53bd428888ab1543dc2667abd2d5e80aae918da8d4b503a426"), hex!("5eb212d4d6aa5948c4f71574d45dad43afef6d330edb873fca69d0e1b197e906")),
584            (hex!("9a82976f7182c05126313bead5617c623b93d11f9f9691c87b1a26f869d569ed"), hex!("e995db483ada5174666c46bafbf3628005aca449c94ebdc0c9239c3f65d61ae0")),
585            (hex!("ca4bdfd54a8467b5283a0216288fdca7091122479ccf3cfb147dfa59d13f3486"), hex!("9dec751c00f49e50fceff7114823f726a0425a68a8dc6af0e4287badfea8f4a4")),
586            (hex!("e306ebfb0d01d0da0952c9a567d758093a80622c6cb55052bf5f1a6ebd8d7b5c"), hex!("9a82976f7182c05126313bead5617c623b93d11f9f9691c87b1a26f869d569ed")),
587            (hex!("492057cf93e99b31d2a85bc5e98a9c3aa0021feec52c227cc8170e8f7d047775"), hex!("e0bf93e9c916104da00b1850adc4608bd7e9087bbd3f805451f4556aa6b3fd6e")),
588        ].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")));
589
590        static ref MAPPER: SimpleBiMapper<HoprSphinxSuite, HoprSphinxHeaderSpec> = PEERS
591            .iter()
592            .enumerate()
593            .map(|(i, (_, k))| (KeyIdent::from(i as u32), *k.public()))
594            .collect::<BiHashMap<_, _>>()
595            .into();
596    }
597
598    fn forward(
599        mut packet: HoprPacket,
600        chain_keypair: &ChainKeypair,
601        next_ticket: TicketBuilder,
602        domain_separator: &Hash,
603    ) -> HoprPacket {
604        if let HoprPacket::Forwarded(fwd) = &mut packet {
605            fwd.outgoing.ticket = next_ticket
606                .eth_challenge(fwd.next_challenge)
607                .build_signed(chain_keypair, domain_separator)
608                .expect("ticket should create")
609                .leak();
610        }
611
612        packet
613    }
614
615    impl HoprPacket {
616        pub fn to_bytes(&self) -> Box<[u8]> {
617            let dummy_ticket = hex!(
618                "67f0ca18102feec505e5bfedcc25963e9c64a6f8a250adcad7d2830dd607585700000000000000000000000000000000000000000000000000000000000000003891bf6fd4a78e868fc7ad477c09b16fc70dd01ea67e18264d17e3d04f6d8576de2e6472b0072e510df6e9fa1dfcc2727cc7633edfeb9ec13860d9ead29bee71d68de3736c2f7a9f42de76ccd57a5f5847bc7349"
619            );
620            let (packet, ticket) = match self {
621                Self::Final(packet) => (packet.plain_text.clone(), dummy_ticket.as_ref().into()),
622                Self::Forwarded(fwd) => (
623                    Vec::from(fwd.outgoing.packet.as_ref()).into_boxed_slice(),
624                    fwd.outgoing.ticket.into_boxed(),
625                ),
626                Self::Outgoing(out) => (
627                    Vec::from(out.packet.as_ref()).into_boxed_slice(),
628                    out.ticket.into_boxed(),
629                ),
630            };
631
632            let mut ret = Vec::with_capacity(Self::SIZE);
633            ret.extend_from_slice(packet.as_ref());
634            ret.extend_from_slice(&ticket);
635            ret.into_boxed_slice()
636        }
637    }
638
639    fn mock_ticket(next_peer_channel_key: &PublicKey, path_len: usize) -> anyhow::Result<TicketBuilder> {
640        assert!(path_len > 0);
641        let price_per_packet: U256 = 10000000000000000u128.into();
642
643        if path_len > 1 {
644            Ok(TicketBuilder::default()
645                .counterparty(next_peer_channel_key.to_address())
646                .amount(price_per_packet.div_f64(1.0)? * U256::from(path_len as u64 - 1))
647                .index(1)
648                .win_prob(WinningProbability::ALWAYS)
649                .channel_epoch(1)
650                .eth_challenge(Default::default()))
651        } else {
652            Ok(TicketBuilder::zero_hop().counterparty(next_peer_channel_key.to_address()))
653        }
654    }
655
656    const FLAGS: PacketSignal = PacketSignal::OutOfSurbs;
657
658    fn create_packet(
659        forward_hops: usize,
660        pseudonym: HoprPseudonym,
661        return_hops: Vec<usize>,
662        msg: &[u8],
663    ) -> anyhow::Result<(HoprPacket, Vec<HoprReplyOpener>)> {
664        assert!((0..=3).contains(&forward_hops), "forward hops must be between 1 and 3");
665        assert!(
666            return_hops.iter().all(|h| (0..=3).contains(h)),
667            "return hops must be between 1 and 3"
668        );
669
670        let ticket = mock_ticket(PEERS[1].0.public(), forward_hops + 1)?;
671        let forward_path = TransportPath::new(PEERS[1..=forward_hops + 1].iter().map(|kp| *kp.1.public()))?;
672
673        let return_paths = return_hops
674            .into_iter()
675            .map(|h| TransportPath::new(PEERS[0..=h].iter().rev().map(|kp| *kp.1.public())))
676            .collect::<std::result::Result<Vec<_>, hopr_types::internal::errors::PathError>>()?;
677
678        Ok(HoprPacket::into_outgoing(
679            msg,
680            &pseudonym,
681            PacketRouting::ForwardPath {
682                forward_path,
683                return_paths,
684            },
685            &PEERS[0].0,
686            ticket,
687            &*MAPPER,
688            &Hash::default(),
689            FLAGS,
690        )?)
691    }
692
693    fn create_packet_from_surb(
694        sender_node: usize,
695        surb_id: HoprSurbId,
696        surb: HoprSurb,
697        hopr_pseudonym: &HoprPseudonym,
698        msg: &[u8],
699    ) -> anyhow::Result<HoprPacket> {
700        assert!((1..=4).contains(&sender_node), "sender_node must be between 1 and 4");
701
702        let ticket = mock_ticket(
703            PEERS[sender_node - 1].0.public(),
704            surb.additional_data_receiver.proof_of_relay_values().chain_length() as usize,
705        )?;
706
707        Ok(HoprPacket::into_outgoing(
708            msg,
709            hopr_pseudonym,
710            PacketRouting::<TransportPath>::Surb(surb_id, surb),
711            &PEERS[sender_node].0,
712            ticket,
713            &*MAPPER,
714            &Hash::default(),
715            FLAGS,
716        )?
717        .0)
718    }
719
720    fn process_packet_at_node<F>(
721        path_len: usize,
722        node_pos: usize,
723        is_reply: bool,
724        packet: HoprPacket,
725        openers: F,
726    ) -> anyhow::Result<HoprPacket>
727    where
728        F: FnMut(&HoprSenderId) -> Option<ReplyOpener>,
729    {
730        assert!((0..=4).contains(&node_pos), "node position must be between 1 and 3");
731
732        let prev_hop = match (node_pos, is_reply) {
733            (1, false) => *PEERS[0].1.public(),
734            (_, false) => *PEERS[node_pos - 1].1.public(),
735            (3, true) => *PEERS[4].1.public(),
736            (_, true) => *PEERS[node_pos + 1].1.public(),
737        };
738
739        let packet = HoprPacket::from_incoming(&packet.to_bytes(), &PEERS[node_pos].1, prev_hop, &*MAPPER, openers)
740            .context(format!("deserialization failure at hop {node_pos}"))?;
741
742        match &packet {
743            HoprPacket::Final(_) => Ok(packet),
744            HoprPacket::Forwarded(_) => {
745                let next_hop = match (node_pos, is_reply) {
746                    (3, false) => *PEERS[4].0.public(),
747                    (_, false) => *PEERS[node_pos + 1].0.public(),
748                    (1, true) => *PEERS[0].0.public(),
749                    (_, true) => *PEERS[node_pos - 1].0.public(),
750                };
751
752                let next_ticket = mock_ticket(&next_hop, path_len)?;
753                Ok(forward(
754                    packet.clone(),
755                    &PEERS[node_pos].0,
756                    next_ticket,
757                    &Hash::default(),
758                ))
759            }
760            HoprPacket::Outgoing(_) => bail!("invalid packet state"),
761        }
762    }
763
764    #[parameterized(hops = { 0,1,2,3 })]
765    fn test_packet_forward_message_no_surb(hops: usize) -> anyhow::Result<()> {
766        let msg = b"some testing forward message";
767        let pseudonym = SimplePseudonym::random();
768        let (mut packet, opener) = create_packet(hops, pseudonym, vec![], msg)?;
769
770        assert!(opener.is_empty());
771        match &packet {
772            HoprPacket::Outgoing { .. } => {}
773            _ => bail!("invalid packet initial state"),
774        }
775
776        let mut actual_plain_text = Box::default();
777        for hop in 1..=hops + 1 {
778            packet = process_packet_at_node(hops + 1, hop, false, packet, |_| None)
779                .context(format!("packet decoding failed at hop {hop}"))?;
780
781            match &packet {
782                HoprPacket::Final(packet) => {
783                    assert_eq!(hop - 1, hops, "final packet must be at the last hop");
784                    assert!(packet.ack_key.is_some(), "must not be a no-ack packet");
785                    assert_eq!(PacketSignals::from(FLAGS), packet.signals);
786                    actual_plain_text = packet.plain_text.clone();
787                }
788                HoprPacket::Forwarded(fwd) => {
789                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
790                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
791                    assert_eq!(hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
792                }
793                HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop}"),
794            }
795        }
796
797        assert_eq!(actual_plain_text.as_ref(), msg, "invalid plaintext");
798        Ok(())
799    }
800
801    #[parameterized(forward_hops = { 0,1,2,3 }, return_hops = { 0, 1, 2, 3})]
802    fn test_packet_forward_message_with_surb(forward_hops: usize, return_hops: usize) -> anyhow::Result<()> {
803        let msg = b"some testing forward message";
804        let pseudonym = SimplePseudonym::random();
805        let (mut packet, openers) = create_packet(forward_hops, pseudonym, vec![return_hops], msg)?;
806
807        assert_eq!(1, openers.len(), "invalid number of openers");
808        match &packet {
809            HoprPacket::Outgoing { .. } => {}
810            _ => bail!("invalid packet initial state"),
811        }
812
813        let mut received_plain_text = Box::default();
814        let mut received_surbs = vec![];
815        for hop in 1..=forward_hops + 1 {
816            packet = process_packet_at_node(forward_hops + 1, hop, false, packet, |_| None)
817                .context(format!("packet decoding failed at hop {hop}"))?;
818
819            match &packet {
820                HoprPacket::Final(packet) => {
821                    assert_eq!(hop - 1, forward_hops, "final packet must be at the last hop");
822                    assert_eq!(pseudonym, packet.sender, "invalid sender");
823                    assert!(packet.ack_key.is_some(), "must not be a no-ack packet");
824                    assert_eq!(PacketSignals::from(FLAGS), packet.signals);
825                    received_plain_text = packet.plain_text.clone();
826                    received_surbs.extend(packet.surbs.clone());
827                }
828                HoprPacket::Forwarded(fwd) => {
829                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
830                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
831                    assert_eq!(forward_hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
832                }
833                HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop}"),
834            }
835        }
836
837        assert_eq!(received_plain_text.as_ref(), msg, "invalid plaintext");
838        assert_eq!(1, received_surbs.len(), "invalid number of surbs");
839        assert_eq!(
840            return_hops as u8 + 1,
841            received_surbs[0]
842                .1
843                .additional_data_receiver
844                .proof_of_relay_values()
845                .chain_length(),
846            "surb has invalid por chain length"
847        );
848
849        Ok(())
850    }
851
852    #[parameterized(
853        forward_hops = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 },
854        return_hops  = { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }
855    )]
856    fn test_packet_forward_and_reply_message(forward_hops: usize, return_hops: usize) -> anyhow::Result<()> {
857        let pseudonym = SimplePseudonym::random();
858
859        // Forward packet
860        let fwd_msg = b"some testing forward message";
861        let (mut fwd_packet, mut openers) = create_packet(forward_hops, pseudonym, vec![return_hops], fwd_msg)?;
862
863        assert_eq!(1, openers.len(), "invalid number of openers");
864        match &fwd_packet {
865            HoprPacket::Outgoing { .. } => {}
866            _ => bail!("invalid packet initial state"),
867        }
868
869        let mut received_fwd_plain_text = Box::default();
870        let mut received_surbs = vec![];
871        for hop in 1..=forward_hops + 1 {
872            fwd_packet = process_packet_at_node(forward_hops + 1, hop, false, fwd_packet, |_| None)
873                .context(format!("packet decoding failed at hop {hop}"))?;
874
875            match &fwd_packet {
876                HoprPacket::Final(incoming) => {
877                    assert_eq!(hop - 1, forward_hops, "final packet must be at the last hop");
878                    assert_eq!(pseudonym, incoming.sender, "invalid sender");
879                    assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
880                    assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
881                    received_fwd_plain_text = incoming.plain_text.clone();
882                    received_surbs.extend(incoming.surbs.clone());
883                }
884                HoprPacket::Forwarded(fwd) => {
885                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
886                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
887                    assert_eq!(forward_hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
888                }
889                HoprPacket::Outgoing { .. } => bail!("invalid packet state at hop {hop}"),
890            }
891        }
892
893        assert_eq!(received_fwd_plain_text.as_ref(), fwd_msg, "invalid plaintext");
894        assert_eq!(1, received_surbs.len(), "invalid number of surbs");
895        assert_eq!(
896            return_hops as u8 + 1,
897            received_surbs[0]
898                .1
899                .additional_data_receiver
900                .proof_of_relay_values()
901                .chain_length(),
902            "surb has invalid por chain length"
903        );
904
905        // The reply packet
906        let re_msg = b"some testing reply message";
907        let mut re_packet = create_packet_from_surb(
908            forward_hops + 1,
909            received_surbs[0].0,
910            received_surbs[0].1.clone(),
911            &pseudonym,
912            re_msg,
913        )?;
914
915        let mut openers_fn = |p: &HoprSenderId| {
916            assert_eq!(p.pseudonym(), pseudonym);
917            let opener = openers.pop();
918            assert!(opener.as_ref().is_none_or(|(id, _)| id == &p.surb_id()));
919            opener.map(|(_, opener)| opener)
920        };
921
922        match &re_packet {
923            HoprPacket::Outgoing { .. } => {}
924            _ => bail!("invalid packet initial state"),
925        }
926
927        let mut received_re_plain_text = Box::default();
928        for hop in (0..=return_hops).rev() {
929            re_packet = process_packet_at_node(return_hops + 1, hop, true, re_packet, &mut openers_fn)
930                .context(format!("packet decoding failed at hop {hop}"))?;
931
932            match &re_packet {
933                HoprPacket::Final(incoming) => {
934                    assert_eq!(hop, 0, "final packet must be at the last hop");
935                    assert_eq!(pseudonym, incoming.sender, "invalid sender");
936                    assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
937                    assert!(incoming.surbs.is_empty(), "must not receive surbs on reply");
938                    assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
939                    received_re_plain_text = incoming.plain_text.clone();
940                }
941                HoprPacket::Forwarded(fwd) => {
942                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.previous_hop, "invalid previous hop");
943                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
944                    assert_eq!(hop, fwd.path_pos as usize, "invalid path position");
945                }
946                HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop}"),
947            }
948        }
949
950        assert_eq!(received_re_plain_text.as_ref(), re_msg, "invalid plaintext");
951        Ok(())
952    }
953
954    #[parameterized(
955        forward_hops = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 },
956        return_hops  = { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }
957    )]
958    fn test_packet_surbs_only_and_reply_message(forward_hops: usize, return_hops: usize) -> anyhow::Result<()> {
959        let pseudonym = SimplePseudonym::random();
960
961        // Forward packet
962        let (mut fwd_packet, mut openers) = create_packet(forward_hops, pseudonym, vec![return_hops; 2], &[])?;
963
964        assert_eq!(2, openers.len(), "invalid number of openers");
965        match &fwd_packet {
966            HoprPacket::Outgoing { .. } => {}
967            _ => bail!("invalid packet initial state"),
968        }
969
970        let mut received_surbs = vec![];
971        for hop in 1..=forward_hops + 1 {
972            fwd_packet = process_packet_at_node(forward_hops + 1, hop, false, fwd_packet, |_| None)
973                .context(format!("packet decoding failed at hop {hop}"))?;
974
975            match &fwd_packet {
976                HoprPacket::Final(incoming) => {
977                    assert_eq!(hop - 1, forward_hops, "final packet must be at the last hop");
978                    assert!(
979                        incoming.plain_text.is_empty(),
980                        "must not receive plaintext on surbs only packet"
981                    );
982                    assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
983                    assert_eq!(2, incoming.surbs.len(), "invalid number of received surbs per packet");
984                    assert_eq!(pseudonym, incoming.sender, "invalid sender");
985                    assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
986                    received_surbs.extend(incoming.surbs.clone());
987                }
988                HoprPacket::Forwarded(fwd) => {
989                    assert_eq!(PEERS[hop - 1].1.public(), &fwd.previous_hop, "invalid previous hop");
990                    assert_eq!(PEERS[hop + 1].1.public(), &fwd.outgoing.next_hop, "invalid next hop");
991                    assert_eq!(forward_hops + 1 - hop, fwd.path_pos as usize, "invalid path position");
992                }
993                HoprPacket::Outgoing { .. } => bail!("invalid packet state at hop {hop}"),
994            }
995        }
996
997        assert_eq!(2, received_surbs.len(), "invalid number of surbs");
998        for recv_surb in &received_surbs {
999            assert_eq!(
1000                return_hops as u8 + 1,
1001                recv_surb
1002                    .1
1003                    .additional_data_receiver
1004                    .proof_of_relay_values()
1005                    .chain_length(),
1006                "surb has invalid por chain length"
1007            );
1008        }
1009
1010        let mut openers_fn = |p: &HoprSenderId| {
1011            assert_eq!(p.pseudonym(), pseudonym);
1012            let (id, opener) = openers.remove(0);
1013            assert_eq!(id, p.surb_id());
1014            Some(opener)
1015        };
1016
1017        // The reply packet
1018        for (i, recv_surb) in received_surbs.into_iter().enumerate() {
1019            let re_msg = format!("some testing reply message {i}");
1020            let mut re_packet = create_packet_from_surb(
1021                forward_hops + 1,
1022                recv_surb.0,
1023                recv_surb.1,
1024                &pseudonym,
1025                re_msg.as_bytes(),
1026            )?;
1027
1028            match &re_packet {
1029                HoprPacket::Outgoing { .. } => {}
1030                _ => bail!("invalid packet initial state in reply {i}"),
1031            }
1032
1033            let mut received_re_plain_text = Box::default();
1034            for hop in (0..=return_hops).rev() {
1035                re_packet = process_packet_at_node(return_hops + 1, hop, true, re_packet, &mut openers_fn)
1036                    .context(format!("packet decoding failed at hop {hop} in reply {i}"))?;
1037
1038                match &re_packet {
1039                    HoprPacket::Final(incoming) => {
1040                        assert_eq!(hop, 0, "final packet must be at the last hop for reply {i}");
1041                        assert!(incoming.ack_key.is_some(), "must not be a no-ack packet");
1042                        assert!(
1043                            incoming.surbs.is_empty(),
1044                            "must not receive surbs on reply for reply {i}"
1045                        );
1046                        assert_eq!(PacketSignals::from(FLAGS), incoming.signals);
1047                        received_re_plain_text = incoming.plain_text.clone();
1048                    }
1049                    HoprPacket::Forwarded(fwd) => {
1050                        assert_eq!(
1051                            PEERS[hop + 1].1.public(),
1052                            &fwd.previous_hop,
1053                            "invalid previous hop in reply {i}"
1054                        );
1055                        assert_eq!(
1056                            PEERS[hop - 1].1.public(),
1057                            &fwd.outgoing.next_hop,
1058                            "invalid next hop in reply {i}"
1059                        );
1060                        assert_eq!(hop, fwd.path_pos as usize, "invalid path position in reply {i}");
1061                    }
1062                    HoprPacket::Outgoing(_) => bail!("invalid packet state at hop {hop} in reply {i}"),
1063                }
1064            }
1065
1066            assert_eq!(
1067                received_re_plain_text.as_ref(),
1068                re_msg.as_bytes(),
1069                "invalid plaintext in reply {i}"
1070            );
1071        }
1072        Ok(())
1073    }
1074}