hopr_crypto_packet/
packet.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use hopr_crypto_sphinx::{
    derivation::derive_packet_tag,
    prp::{PRPParameters, PRP},
    routing::{forward_header, header_length, ForwardedHeader, RoutingInfo},
    shared_keys::{Alpha, GroupElement, SharedKeys, SharedSecret, SphinxSuite},
};
use hopr_crypto_types::{
    keypairs::Keypair,
    primitives::{DigestLike, SimpleMac},
    types::PacketTag,
};
use hopr_internal_types::prelude::*;
use hopr_primitive_types::prelude::*;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use typenum::Unsigned;

use crate::{
    errors::{PacketError::PacketDecodingError, Result},
    packet::ForwardedMetaPacket::{Final, Relayed},
    por::POR_SECRET_LENGTH,
};

/// Tag used to separate padding from data
const PADDING_TAG: &[u8] = b"HOPR";

/// Determines the total length (header + payload) of the packet given the header information.
pub const fn packet_length<S: SphinxSuite>(
    max_hops: usize,
    additional_data_relayer_len: usize,
    additional_data_last_hop_len: usize,
) -> usize {
    <S::P as Keypair>::Public::SIZE
        + header_length::<S>(max_hops, additional_data_relayer_len, additional_data_last_hop_len)
        + SimpleMac::SIZE
        + PAYLOAD_SIZE
        + PADDING_TAG.len()
}

// TODO: Make padding length prefixed in 3.0

fn add_padding(msg: &[u8]) -> Box<[u8]> {
    assert!(msg.len() <= PAYLOAD_SIZE, "message too long for padding");

    let padded_len = PAYLOAD_SIZE + PADDING_TAG.len();
    let mut ret = vec![0u8; padded_len];
    ret[padded_len - msg.len()..padded_len].copy_from_slice(msg);

    // Zeroes and the PADDING_TAG are prepended to the message to form padding
    ret[padded_len - msg.len() - PADDING_TAG.len()..padded_len - msg.len()].copy_from_slice(PADDING_TAG);
    ret.into_boxed_slice()
}

fn remove_padding(msg: &[u8]) -> Option<&[u8]> {
    assert_eq!(
        PAYLOAD_SIZE + PADDING_TAG.len(),
        msg.len(),
        "padded message must be {} bytes long",
        PAYLOAD_SIZE + PADDING_TAG.len()
    );
    let pos = msg
        .windows(PADDING_TAG.len())
        .position(|window| window == PADDING_TAG)?;
    Some(&msg.split_at(pos).1[PADDING_TAG.len()..])
}

/// An encrypted packet.
///
/// A sender can create a new packet via [MetaPacket::new] and send it.
/// Once received by the recipient, it is parsed first by calling [MetaPacket::try_from]
/// and then it can be transformed into [ForwardedMetaPacket] by calling
/// the [MetaPacket::into_forwarded] method. The [ForwardedMetaPacket] then contains the information
/// about the next recipient of this packet.
///
/// The packet format is directly dependent on the used [SphinxSuite].
pub struct MetaPacket<S: SphinxSuite> {
    packet: Box<[u8]>,
    _s: PhantomData<S>,
}

impl<S: SphinxSuite> Debug for MetaPacket<S> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}]", hex::encode(&self.packet))
    }
}

// Needs manual Clone implementation to not impose Clone restriction on `S`
impl<S: SphinxSuite> Clone for MetaPacket<S> {
    fn clone(&self) -> Self {
        Self {
            packet: self.packet.clone(),
            _s: PhantomData,
        }
    }
}

/// Represent a [MetaPacket] with one layer of encryption removed, exposing the details
/// about the next hop.
///
/// There are two possible states - either the packet is intended for the recipient,
/// and is thus [Final], or it is meant to be sent (relayed)
/// to the next hop - thus it is [Relayed].
#[allow(dead_code)]
pub enum ForwardedMetaPacket<S: SphinxSuite> {
    /// The content is another [MetaPacket] meant to be sent to the next hop.
    Relayed {
        /// Packet for the next hop.
        packet: MetaPacket<S>,
        /// Public key of the next hop.
        next_node: <S::P as Keypair>::Public,
        /// Position in the channel path of this packet.
        path_pos: u8,
        /// Contains the PoR challenge that will be solved when we receive
        /// the acknowledgement after we forward the inner packet to the next hop.
        additional_info: Box<[u8]>,
        /// Shared secret that was used to encrypt the removed layer.
        derived_secret: SharedSecret,
        /// Packet checksum.
        packet_tag: PacketTag,
    },
    /// The content is the actual payload for the packet's destination.
    Final {
        /// Decrypted payload
        plain_text: Box<[u8]>,
        /// Reserved for SURBs. Currently not used
        additional_data: Box<[u8]>,
        /// Shared secret that was used to encrypt the removed layer.
        derived_secret: SharedSecret,
        /// Packet checksum.
        packet_tag: PacketTag,
    },
}

impl<S: SphinxSuite> MetaPacket<S> {
    /// The fixed length of the Sphinx packet header.
    pub const HEADER_LEN: usize = header_length::<S>(INTERMEDIATE_HOPS + 1, POR_SECRET_LENGTH, 0);

    /// The fixed length of the padded packet.
    pub const PACKET_LEN: usize = packet_length::<S>(INTERMEDIATE_HOPS + 1, POR_SECRET_LENGTH, 0);

    /// Creates a new outgoing packet with the given payload `msg`, `path` and `shared_keys` computed along the path.
    ///
    /// The size of the `msg` must be less or equal [PAYLOAD_SIZE], otherwise the
    /// constructor will panic. The caller **must** ensure the size is correct beforehand.
    /// The `additional_data_relayer` contains the PoR challenges for the individual relayers along the path,
    /// each of the challenges has the same size of `additional_relayer_data_len`.
    ///
    /// Optionally, there could be some additional data (`additional_data_last_hop`) for the packet destination.
    /// This is reserved for the future use by SURBs.
    pub fn new(
        shared_keys: SharedKeys<S::E, S::G>,
        msg: &[u8],
        path: &[<S::P as Keypair>::Public],
        max_hops: usize,
        additional_relayer_data_len: usize,
        additional_data_relayer: &[&[u8]],
        additional_data_last_hop: Option<&[u8]>,
    ) -> Self {
        assert!(msg.len() <= PAYLOAD_SIZE, "message too long to fit into a packet");

        let mut payload = add_padding(msg);

        let routing_info = RoutingInfo::new::<S>(
            max_hops,
            path,
            &shared_keys.secrets,
            additional_relayer_data_len,
            additional_data_relayer,
            additional_data_last_hop,
        );

        // Encrypt packet payload using the derived shared secrets
        for secret in shared_keys.secrets.iter().rev() {
            let prp = PRP::from_parameters(PRPParameters::new(secret));
            prp.forward_inplace(&mut payload)
                .unwrap_or_else(|e| panic!("onion encryption error {e}"))
        }

        Self::new_from_parts(shared_keys.alpha, routing_info, &payload)
    }

    fn new_from_parts(
        alpha: Alpha<<S::G as GroupElement<S::E>>::AlphaLen>,
        routing_info: RoutingInfo,
        payload: &[u8],
    ) -> Self {
        assert!(
            !routing_info.routing_information.is_empty(),
            "routing info must not be empty"
        );
        assert_eq!(
            PAYLOAD_SIZE + PADDING_TAG.len(),
            payload.len(),
            "payload has incorrect length"
        );

        let mut packet = Vec::with_capacity(Self::SIZE);
        packet.extend_from_slice(&alpha);
        packet.extend_from_slice(&routing_info.routing_information);
        packet.extend_from_slice(&routing_info.mac);
        packet.extend_from_slice(payload);

        Self {
            packet: packet.into_boxed_slice(),
            _s: PhantomData,
        }
    }

    /// Returns the Alpha value subslice from the packet data.
    fn alpha(&self) -> &[u8] {
        let len = <S::G as GroupElement<S::E>>::AlphaLen::USIZE;
        &self.packet[..len]
    }

    /// Returns the routing info subslice from the packet data.
    fn routing_info(&self) -> &[u8] {
        let base = <S::G as GroupElement<S::E>>::AlphaLen::USIZE;
        &self.packet[base..base + Self::HEADER_LEN]
    }

    /// Returns the packet checksum (MAC) subslice from the packet data.
    fn mac(&self) -> &[u8] {
        let base = <S::G as GroupElement<S::E>>::AlphaLen::USIZE + Self::HEADER_LEN;
        &self.packet[base..base + SimpleMac::SIZE]
    }

    /// Returns the payload subslice from the packet data.
    fn payload(&self) -> &[u8] {
        let base = <S::G as GroupElement<S::E>>::AlphaLen::USIZE + Self::HEADER_LEN + SimpleMac::SIZE;
        &self.packet[base..base + PAYLOAD_SIZE + PADDING_TAG.len()]
    }

    /// Attempts to remove the layer of encryption of this packet by using the given `node_keypair`.
    /// This will transform this packet into the [ForwardedMetaPacket].
    pub fn into_forwarded(
        self,
        node_keypair: &S::P,
        max_hops: usize,
        additional_data_relayer_len: usize,
        additional_data_last_hop_len: usize,
    ) -> Result<ForwardedMetaPacket<S>> {
        let (alpha, secret) = SharedKeys::<S::E, S::G>::forward_transform(
            Alpha::<<S::G as GroupElement<S::E>>::AlphaLen>::from_slice(self.alpha()),
            &(node_keypair.into()),
            &(node_keypair.public().into()),
        )?;

        let mut routing_info_cpy: Vec<u8> = self.routing_info().into();
        let fwd_header = forward_header::<S>(
            &secret,
            &mut routing_info_cpy,
            self.mac(),
            max_hops,
            additional_data_relayer_len,
            additional_data_last_hop_len,
        )?;

        let prp = PRP::from_parameters(PRPParameters::new(&secret));
        let decrypted = prp.inverse(self.payload())?;

        Ok(match fwd_header {
            ForwardedHeader::RelayNode {
                header,
                mac,
                path_pos,
                next_node,
                additional_info,
            } => Relayed {
                packet: Self::new_from_parts(
                    alpha,
                    RoutingInfo {
                        routing_information: header,
                        mac,
                    },
                    &decrypted,
                ),
                packet_tag: derive_packet_tag(&secret),
                derived_secret: secret,
                next_node: <S::P as Keypair>::Public::try_from(&next_node)
                    .map_err(|_| PacketDecodingError("couldn't parse next node id".into()))?,
                path_pos,
                additional_info,
            },
            ForwardedHeader::FinalNode { additional_data } => Final {
                packet_tag: derive_packet_tag(&secret),
                derived_secret: secret,
                plain_text: remove_padding(&decrypted)
                    .ok_or(PacketDecodingError(format!(
                        "couldn't remove padding: {}",
                        hex::encode(decrypted.as_ref())
                    )))?
                    .into(),
                additional_data,
            },
        })
    }
}

impl<S: SphinxSuite> AsRef<[u8]> for MetaPacket<S> {
    fn as_ref(&self) -> &[u8] {
        self.packet.as_ref()
    }
}

impl<S: SphinxSuite> TryFrom<&[u8]> for MetaPacket<S> {
    type Error = GeneralError;

    fn try_from(value: &[u8]) -> std::result::Result<Self, Self::Error> {
        if value.len() == Self::SIZE {
            Ok(Self {
                packet: value.into(),
                _s: PhantomData,
            })
        } else {
            Err(GeneralError::ParseError("MetaPacket".into()))
        }
    }
}

impl<S: SphinxSuite> BytesRepresentable for MetaPacket<S> {
    const SIZE: usize = <S::G as GroupElement<S::E>>::AlphaLen::USIZE
        + Self::HEADER_LEN
        + SimpleMac::SIZE
        + PAYLOAD_SIZE
        + PADDING_TAG.len();
}

#[cfg(test)]
mod tests {
    use crate::packet::{add_padding, remove_padding, ForwardedMetaPacket, MetaPacket, PADDING_TAG};
    use crate::por::{ProofOfRelayString, POR_SECRET_LENGTH};
    use hopr_crypto_sphinx::{
        ec_groups::{Ed25519Suite, Secp256k1Suite, X25519Suite},
        shared_keys::SphinxSuite,
    };
    use hopr_crypto_types::keypairs::{ChainKeypair, Keypair, OffchainKeypair};
    use hopr_internal_types::protocol::INTERMEDIATE_HOPS;
    use parameterized::parameterized;

    #[test]
    fn test_padding() {
        let data = b"test";
        let padded = add_padding(data);

        let mut expected = vec![0u8; 492];
        expected.extend_from_slice(PADDING_TAG);
        expected.extend_from_slice(data);
        assert_eq!(&expected, padded.as_ref());

        let unpadded = remove_padding(&padded);
        assert!(unpadded.is_some());
        assert_eq!(data, &unpadded.unwrap());
    }

    fn generic_test_meta_packet<S: SphinxSuite>(keypairs: Vec<S::P>) -> anyhow::Result<()> {
        let pubkeys = keypairs.iter().map(|kp| kp.public().clone()).collect::<Vec<_>>();

        let shared_keys = S::new_shared_keys(&pubkeys)?;
        let por_strings = ProofOfRelayString::from_shared_secrets(&shared_keys.secrets);

        assert_eq!(shared_keys.secrets.len() - 1, por_strings.len());

        let msg = b"some random test message";

        let mut mp = MetaPacket::<S>::new(
            shared_keys,
            msg,
            &pubkeys,
            INTERMEDIATE_HOPS + 1,
            POR_SECRET_LENGTH,
            &por_strings.iter().map(|v| v.as_ref()).collect::<Vec<_>>(),
            None,
        );

        assert!(mp.as_ref().len() < 1492, "metapacket too long {}", mp.as_ref().len());

        for (i, pair) in keypairs.iter().enumerate() {
            let fwd = mp
                .clone()
                .into_forwarded(pair, INTERMEDIATE_HOPS + 1, POR_SECRET_LENGTH, 0)
                .unwrap_or_else(|_| panic!("failed to unwrap at {i}"));

            match fwd {
                ForwardedMetaPacket::Relayed { packet, .. } => {
                    assert!(i < keypairs.len() - 1);
                    mp = packet;
                }
                ForwardedMetaPacket::Final {
                    plain_text,
                    additional_data,
                    ..
                } => {
                    assert_eq!(keypairs.len() - 1, i);
                    assert_eq!(msg, plain_text.as_ref());
                    assert!(additional_data.is_empty());
                }
            }
        }

        Ok(())
    }

    #[parameterized(amount = { 4, 3, 2 })]
    fn test_x25519_meta_packet(amount: usize) -> anyhow::Result<()> {
        generic_test_meta_packet::<X25519Suite>((0..amount).map(|_| OffchainKeypair::random()).collect())
    }

    #[parameterized(amount = { 4, 3, 2 })]
    fn test_ed25519_meta_packet(amount: usize) -> anyhow::Result<()> {
        generic_test_meta_packet::<Ed25519Suite>((0..amount).map(|_| OffchainKeypair::random()).collect())
    }

    #[parameterized(amount = { 4, 3, 2 })]
    fn test_secp256k1_meta_packet(amount: usize) -> anyhow::Result<()> {
        generic_test_meta_packet::<Secp256k1Suite>((0..amount).map(|_| ChainKeypair::random()).collect())
    }
}