Merge pull request #6530 from nymtech/chore/rename-lp-message

chore: rename LpMessage to LpFrame
This commit is contained in:
Jędrzej Stuczyński
2026-03-09 13:44:39 +00:00
committed by GitHub
15 changed files with 159 additions and 158 deletions
+9 -9
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::LpError;
use crate::packet::{EncryptedLpPacket, InnerHeader, LpHeader, LpMessage, LpPacket};
use crate::packet::{EncryptedLpPacket, InnerHeader, LpFrame, LpHeader, LpPacket};
use bytes::BytesMut;
use libcrux_psq::Channel;
@@ -46,9 +46,9 @@ pub(crate) fn encrypt_lp_packet(
packet: LpPacket,
transport: &mut libcrux_psq::session::Transport,
) -> Result<EncryptedLpPacket, LpError> {
let mut plaintext = BytesMut::with_capacity(InnerHeader::SIZE + packet.message().len());
let mut plaintext = BytesMut::with_capacity(InnerHeader::SIZE + packet.frame().len());
packet.header().inner.encode(&mut plaintext);
packet.message().encode(&mut plaintext);
packet.frame().encode(&mut plaintext);
let ciphertext = encrypt_data(plaintext.as_ref(), transport)?;
@@ -67,14 +67,14 @@ pub(crate) fn decrypt_lp_packet(
let inner_header = InnerHeader::parse(&plaintext)?;
let payload = &plaintext[InnerHeader::SIZE..];
let message = LpMessage::decode(payload)?;
let frame = LpFrame::decode(payload)?;
Ok(LpPacket::new(
LpHeader {
outer: packet.outer_header(),
inner: inner_header,
},
message,
frame,
))
}
@@ -82,7 +82,7 @@ pub(crate) fn decrypt_lp_packet(
mod tests {
use crate::LpError;
use crate::codec::{decrypt_data, decrypt_lp_packet, encrypt_data, encrypt_lp_packet};
use crate::packet::{EncryptedLpPacket, LpHeader, LpMessage, LpPacket};
use crate::packet::{EncryptedLpPacket, LpFrame, LpHeader, LpPacket};
use crate::peer::mock_peers;
use crate::psq::initiator::{build_psq_ciphersuite, build_psq_principal};
use crate::psq::{PSQ_MSG2_SIZE, psq_msg1_size, responder};
@@ -261,7 +261,7 @@ mod tests {
// happy path
let packet = LpPacket::new(
LpHeader::new(123, 0, 1),
LpMessage::new_opaque(b"foomp".to_vec()),
LpFrame::new_opaque(b"foomp".to_vec()),
);
let ciphertext = encrypt_lp_packet(packet.clone(), &mut init_transport).unwrap();
@@ -273,7 +273,7 @@ mod tests {
// incomplete ciphertext
let packet = LpPacket::new(
LpHeader::new(123, 1, 1),
LpMessage::new_opaque(b"foomp".to_vec()),
LpFrame::new_opaque(b"foomp".to_vec()),
);
let ciphertext2 = encrypt_lp_packet(packet, &mut init_transport).unwrap();
let l = ciphertext2.ciphertext().len();
@@ -285,7 +285,7 @@ mod tests {
// too small buffer
let packet = LpPacket::new(
LpHeader::new(123, 1, 1),
LpMessage::new_opaque(b"foomp".to_vec()),
LpFrame::new_opaque(b"foomp".to_vec()),
);
let ciphertext3 = encrypt_lp_packet(packet, &mut resp_transport).unwrap();
let malformed = EncryptedLpPacket::new(ciphertext3.outer_header(), vec![]);
+4 -4
View File
@@ -11,8 +11,8 @@ pub enum MalformedLpPacketError {
#[error("provided insufficient data to fully deserialise the struct")]
InsufficientData,
#[error("{0} is not a valid LpDataKind")]
InvalidLpDataKind(u16),
#[error("{0} is not a valid LpFrameKind value")]
InvalidLpFrameKind(u16),
#[error("invalid payload size: expected {expected}, got {actual}")]
InvalidPayloadSize { expected: usize, actual: usize },
@@ -27,7 +27,7 @@ pub enum MalformedLpPacketError {
}
impl MalformedLpPacketError {
pub fn invalid_data_kind(message_type: u16) -> Self {
MalformedLpPacketError::InvalidLpDataKind(message_type)
pub fn invalid_data_kind(frame_kind: u16) -> Self {
MalformedLpPacketError::InvalidLpFrameKind(frame_kind)
}
}
@@ -7,32 +7,32 @@ use num_enum::{IntoPrimitive, TryFromPrimitive};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
#[derive(Debug, Clone, PartialEq)]
pub struct LpMessageHeader {
pub kind: LpMessageType,
pub message_attributes: [u8; 14],
pub struct LpFrameHeader {
pub kind: LpFrameKind,
pub frame_attributes: [u8; 14],
}
impl LpMessageHeader {
impl LpFrameHeader {
pub const SIZE: usize = 16; // message_kind(2) + message_attributes(14)
pub fn new(kind: LpMessageType, message_attributes: [u8; 14]) -> Self {
pub fn new(kind: LpFrameKind, frame_attributes: [u8; 14]) -> Self {
Self {
kind,
message_attributes,
frame_attributes,
}
}
pub fn new_no_attributes(kind: LpMessageType) -> Self {
pub fn new_no_attributes(kind: LpFrameKind) -> Self {
Self {
kind,
message_attributes: [0; 14],
frame_attributes: [0; 14],
}
}
/// Encode directly into a BytesMut buffer
pub fn encode(&self, dst: &mut BytesMut) {
dst.put_u16_le(self.kind as u16);
dst.put_slice(&self.message_attributes);
dst.put_slice(&self.frame_attributes);
}
pub fn parse(src: &[u8]) -> Result<Self, MalformedLpPacketError> {
@@ -41,35 +41,35 @@ impl LpMessageHeader {
}
let raw_kind = u16::from_le_bytes([src[0], src[1]]);
let kind = LpMessageType::try_from(raw_kind)
let kind = LpFrameKind::try_from(raw_kind)
.map_err(|_| MalformedLpPacketError::invalid_data_kind(raw_kind))?;
#[allow(clippy::unwrap_used)]
let message_attributes = src[2..16].try_into().unwrap();
Ok(Self {
kind,
message_attributes,
frame_attributes: message_attributes,
})
}
}
/// Represent application data being sent in Transport mode
#[derive(Debug, Clone, PartialEq)]
pub struct LpMessage {
pub header: LpMessageHeader,
pub struct LpFrame {
pub header: LpFrameHeader,
pub content: Bytes,
}
impl AsRef<[u8]> for LpMessage {
impl AsRef<[u8]> for LpFrame {
fn as_ref(&self) -> &[u8] {
&self.content
}
}
impl LpMessage {
pub fn new(kind: LpMessageType, content: impl Into<Bytes>) -> Self {
impl LpFrame {
pub fn new(kind: LpFrameKind, content: impl Into<Bytes>) -> Self {
Self {
header: LpMessageHeader::new_no_attributes(kind),
header: LpFrameHeader::new_no_attributes(kind),
content: content.into(),
}
}
@@ -81,37 +81,37 @@ impl LpMessage {
}
pub fn decode(src: &[u8]) -> Result<Self, MalformedLpPacketError> {
let header = LpMessageHeader::parse(src)?;
let content = src[LpMessageHeader::SIZE..].to_vec().into();
let header = LpFrameHeader::parse(src)?;
let content = src[LpFrameHeader::SIZE..].to_vec().into();
Ok(Self { header, content })
}
pub fn kind(&self) -> LpMessageType {
pub fn kind(&self) -> LpFrameKind {
self.header.kind
}
pub fn new_opaque(content: impl Into<Bytes>) -> Self {
Self::new(LpMessageType::Opaque, content)
Self::new(LpFrameKind::Opaque, content)
}
pub fn new_registration(data: impl Into<Bytes>) -> Self {
Self::new(LpMessageType::Registration, data)
Self::new(LpFrameKind::Registration, data)
}
pub fn new_forward(data: impl Into<Bytes>) -> Self {
Self::new(LpMessageType::Forward, data)
Self::new(LpFrameKind::Forward, data)
}
pub(crate) fn len(&self) -> usize {
LpMessageHeader::SIZE + self.content.len()
LpFrameHeader::SIZE + self.content.len()
}
}
/// Represent kind of application data being sent in Transport mode
#[derive(Clone, Copy, PartialEq, Eq, Debug, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum LpMessageType {
pub enum LpFrameKind {
Opaque = 0,
Registration = 1,
Forward = 2,
+10 -10
View File
@@ -6,12 +6,12 @@ use bytes::{BufMut, BytesMut};
use std::fmt::{Debug, Formatter};
pub use error::MalformedLpPacketError;
pub use frame::{ForwardPacketData, LpFrame};
pub use header::{InnerHeader, LpHeader, OuterHeader};
pub use message::{ForwardPacketData, LpMessage};
pub mod error;
pub mod frame;
pub mod header;
pub mod message;
pub mod replay;
pub mod utils;
@@ -81,7 +81,7 @@ impl EncryptedLpPacket {
#[derive(Clone, PartialEq)]
pub struct LpPacket {
pub(crate) header: LpHeader,
pub(crate) message: LpMessage,
pub(crate) frame: LpFrame,
}
impl Debug for LpPacket {
@@ -91,16 +91,16 @@ impl Debug for LpPacket {
}
impl LpPacket {
pub fn new(header: LpHeader, message: LpMessage) -> Self {
Self { header, message }
pub fn new(header: LpHeader, frame: LpFrame) -> Self {
Self { header, frame }
}
pub fn message(&self) -> &LpMessage {
&self.message
pub fn frame(&self) -> &LpFrame {
&self.frame
}
pub fn into_message(self) -> LpMessage {
self.message
pub fn into_frame(self) -> LpFrame {
self.frame
}
pub fn header(&self) -> &LpHeader {
@@ -115,6 +115,6 @@ impl LpPacket {
pub(crate) fn dbg_encode(&self, dst: &mut BytesMut) {
self.header.dbg_encode(dst);
self.message.encode(dst)
self.frame.encode(dst)
}
}
+22 -23
View File
@@ -6,7 +6,7 @@
//! This module implements session management functionality, including replay protection
use crate::codec::{decrypt_lp_packet, encrypt_lp_packet};
use crate::packet::{EncryptedLpPacket, LpHeader, LpMessage, LpPacket};
use crate::packet::{EncryptedLpPacket, LpFrame, LpHeader, LpPacket};
use crate::peer::{LpLocalPeer, LpRemotePeer};
use crate::peer_config::LpReceiverIndex;
use crate::psq::initiator::HandshakeMode;
@@ -32,7 +32,7 @@ pub enum LpInput {
ReceivePacket(EncryptedLpPacket),
/// Application wants to send data (only valid in Transport state).
SendData(LpMessage),
SendFrame(LpFrame),
}
/// Represents actions the state machine requests the environment to perform.
@@ -42,7 +42,7 @@ pub enum LpAction {
SendPacket(EncryptedLpPacket),
/// Deliver decrypted application data received from the peer.
DeliverData(LpMessage),
DeliverFrame(LpFrame),
}
pub type SessionId = [u8; 32];
@@ -234,10 +234,10 @@ impl LpTransportSession {
self.protocol_version
}
pub fn next_packet(&mut self, message: LpMessage) -> Result<LpPacket, LpError> {
pub fn next_packet(&mut self, frame: LpFrame) -> Result<LpPacket, LpError> {
let counter = self.next_counter();
let header = LpHeader::new(self.receiver_index(), counter, self.protocol_version);
let packet = LpPacket::new(header, message);
let packet = LpPacket::new(header, frame);
Ok(packet)
}
@@ -299,22 +299,19 @@ impl LpTransportSession {
self.receiving_counter.current_packet_cnt()
}
/// Encrypts a produced application using the established transport session
/// and produce an `EncryptedLpPacket`
/// Wrap the provided `LpFrame` into an `LpPacket` and encrypt its content using the established transport session
/// to produce an `EncryptedLpPacket`
///
/// # Arguments
///
/// * `data` - plaintext data to encrypt
/// * `frame` - structured `LpFrame` to wrap and encrypt
///
/// # Returns
///
/// * `Ok(EncryptedLpPacket)` containing the encrypted message ciphertext.
/// * `Err(LpError)` if the session is not in transport mode or encryption fails.
pub(crate) fn encrypt_application_data(
&mut self,
data: LpMessage,
) -> Result<EncryptedLpPacket, LpError> {
let packet = self.next_packet(data)?;
pub(crate) fn wrap_lp_frame(&mut self, frame: LpFrame) -> Result<EncryptedLpPacket, LpError> {
let packet = self.next_packet(frame)?;
encrypt_lp_packet(packet, &mut self.active_transport)
}
@@ -322,7 +319,7 @@ impl LpTransportSession {
///
/// # Arguments
///
/// * `ciphertext` - The encrypted packet
/// * `packet` - The encrypted packet
///
/// # Returns
///
@@ -358,11 +355,11 @@ impl LpTransportSession {
self.receiving_counter_mark(ctr)?;
// 4. deliver the message
Ok(LpAction::DeliverData(packet.message))
Ok(LpAction::DeliverFrame(packet.frame))
}
LpInput::SendData(data) => {
LpInput::SendFrame(data) => {
// Encrypt and send application data
match self.encrypt_application_data(data) {
match self.wrap_lp_frame(data) {
Ok(packet) => Ok(LpAction::SendPacket(packet)),
Err(e) => Err(e),
}
@@ -476,8 +473,9 @@ mod tests {
// --- Transport Phase ---
println!("--- Step 1: Initiator sends data ---");
let data_to_send_1 = LpMessage::new_opaque(b"hello responder".to_vec());
let init_actions_4 = initiator.process_input(LpInput::SendData(data_to_send_1.clone()));
let data_to_send_1 = LpFrame::new_opaque(b"hello responder".to_vec());
let init_actions_4 =
initiator.process_input(LpInput::SendFrame(data_to_send_1.clone()));
let data_packet_1 = if let Ok(LpAction::SendPacket(packet)) = init_actions_4 {
packet.clone()
} else {
@@ -487,7 +485,7 @@ mod tests {
println!("--- Step 2: Responder receives data ---");
let resp_actions_5 = responder.process_input(LpInput::ReceivePacket(data_packet_1));
let resp_data_1 = if let Ok(LpAction::DeliverData(data)) = resp_actions_5 {
let resp_data_1 = if let Ok(LpAction::DeliverFrame(data)) = resp_actions_5 {
data
} else {
panic!("Responder should deliver data");
@@ -495,8 +493,9 @@ mod tests {
assert_eq!(resp_data_1, data_to_send_1);
println!("--- Step 3: Responder sends data ---");
let data_to_send_2 = LpMessage::new_opaque(b"hello initiator".to_vec());
let resp_actions_6 = responder.process_input(LpInput::SendData(data_to_send_2.clone()));
let data_to_send_2 = LpFrame::new_opaque(b"hello initiator".to_vec());
let resp_actions_6 =
responder.process_input(LpInput::SendFrame(data_to_send_2.clone()));
let data_packet_2 = if let Ok(LpAction::SendPacket(packet)) = resp_actions_6 {
packet.clone()
} else {
@@ -506,7 +505,7 @@ mod tests {
println!("--- Step 4: Initiator receives data ---");
let init_actions_5 = initiator.process_input(LpInput::ReceivePacket(data_packet_2));
if let Ok(LpAction::DeliverData(data)) = init_actions_5 {
if let Ok(LpAction::DeliverFrame(data)) = init_actions_5 {
assert_eq!(data, data_to_send_2);
} else {
panic!("Initiator should deliver data");
+18 -20
View File
@@ -1,6 +1,6 @@
#[cfg(test)]
mod tests {
use crate::packet::{EncryptedLpPacket, LpMessage};
use crate::packet::{EncryptedLpPacket, LpFrame};
use crate::session::{LpAction, LpInput};
use crate::{LpError, SessionManager, SessionsMock};
use nym_kkt_ciphersuite::{IntoEnumIterator, KEM};
@@ -9,7 +9,7 @@ mod tests {
trait ActionExtract {
fn ciphertext(self) -> EncryptedLpPacket;
fn data(self) -> LpMessage;
fn data(self) -> LpFrame;
}
impl ActionExtract for LpAction {
@@ -21,8 +21,8 @@ mod tests {
}
}
fn data(self) -> LpMessage {
if let LpAction::DeliverData(data) = self {
fn data(self) -> LpFrame {
if let LpAction::DeliverFrame(data) = self {
data
} else {
panic!("invalid action");
@@ -54,7 +54,7 @@ mod tests {
// --- A sends to B ---
let plaintext_a = format!("A->B Message {i}").into_bytes();
let ciphertext_a = session_manager_1
.send_data(peer_a_sm, LpMessage::new_opaque(plaintext_a.clone()))
.send_frame(peer_a_sm, LpFrame::new_opaque(plaintext_a.clone()))
.unwrap()
.ciphertext();
@@ -68,7 +68,7 @@ mod tests {
// --- B sends to A ---
let plaintext_b = format!("B->A Message {i}").into_bytes();
let ciphertext_b = session_manager_2
.send_data(peer_b_sm, LpMessage::new_opaque(plaintext_b.clone()))
.send_frame(peer_b_sm, LpFrame::new_opaque(plaintext_b.clone()))
.unwrap()
.ciphertext();
@@ -183,15 +183,13 @@ mod tests {
// --- 3. Simulate Data Transfer via process_input ---
println!("Starting data transfer simulation via process_input...");
let plaintext_a_to_b =
LpMessage::new_opaque(b"Hello from A via process_input!".to_vec());
let plaintext_b_to_a =
LpMessage::new_opaque(b"Hello from B via process_input!".to_vec());
let plaintext_a_to_b = LpFrame::new_opaque(b"Hello from A via process_input!".to_vec());
let plaintext_b_to_a = LpFrame::new_opaque(b"Hello from B via process_input!".to_vec());
// --- A sends to B ---
println!(" A sends to B");
let action_a_send = session_manager_1
.process_input(session_id, LpInput::SendData(plaintext_a_to_b.clone()))
.process_input(session_id, LpInput::SendFrame(plaintext_a_to_b.clone()))
.expect("A SendData failed");
let data_packet_a = action_a_send.ciphertext();
@@ -202,7 +200,7 @@ mod tests {
.process_input(session_id, LpInput::ReceivePacket(data_packet_a))
.expect("B ReceivePacket (data) failed");
if let LpAction::DeliverData(data) = action_b_recv {
if let LpAction::DeliverFrame(data) = action_b_recv {
assert_eq!(data, plaintext_a_to_b, "Decrypted data mismatch A->B");
println!(
" B successfully decrypted: {:?}",
@@ -215,7 +213,7 @@ mod tests {
// --- B sends to A ---
println!(" B sends to A");
let action_b_send = session_manager_2
.process_input(session_id, LpInput::SendData(plaintext_b_to_a.clone()))
.process_input(session_id, LpInput::SendFrame(plaintext_b_to_a.clone()))
.expect("B SendData failed");
let data_packet_b = action_b_send.ciphertext();
@@ -229,7 +227,7 @@ mod tests {
.process_input(session_id, LpInput::ReceivePacket(data_packet_b))
.expect("A ReceivePacket (data) failed");
if let LpAction::DeliverData(data) = action_a_recv {
if let LpAction::DeliverFrame(data) = action_a_recv {
assert_eq!(data, plaintext_b_to_a, "Decrypted data mismatch B->A");
println!(
" A successfully decrypted: {:?}",
@@ -258,11 +256,11 @@ mod tests {
println!("Testing out-of-order reception via process_input...");
// A prepares N+1 then N
let data_n_plus_1 = LpMessage::new_opaque(b"Message N+1".to_vec());
let data_n = LpMessage::new_opaque(b"Message N".to_vec());
let data_n_plus_1 = LpFrame::new_opaque(b"Message N+1".to_vec());
let data_n = LpFrame::new_opaque(b"Message N".to_vec());
let action_send_n1 = session_manager_1
.process_input(session_id, LpInput::SendData(data_n_plus_1.clone()))
.process_input(session_id, LpInput::SendFrame(data_n_plus_1.clone()))
.unwrap();
let packet_n1 = match action_send_n1 {
LpAction::SendPacket(p) => p,
@@ -270,7 +268,7 @@ mod tests {
};
let action_send_n = session_manager_1
.process_input(session_id, LpInput::SendData(data_n.clone()))
.process_input(session_id, LpInput::SendFrame(data_n.clone()))
.unwrap();
let packet_n = match action_send_n {
LpAction::SendPacket(p) => p,
@@ -284,7 +282,7 @@ mod tests {
.process_input(session_id, LpInput::ReceivePacket(packet_n1))
.unwrap();
match action_recv_n1 {
LpAction::DeliverData(d) => assert_eq!(d, data_n_plus_1, "Data N+1 mismatch"),
LpAction::DeliverFrame(d) => assert_eq!(d, data_n_plus_1, "Data N+1 mismatch"),
_ => panic!("Expected DeliverData for N+1"),
}
@@ -294,7 +292,7 @@ mod tests {
.process_input(session_id, LpInput::ReceivePacket(packet_n))
.unwrap();
match action_recv_n {
LpAction::DeliverData(d) => assert_eq!(d, data_n, "Data N mismatch"),
LpAction::DeliverFrame(d) => assert_eq!(d, data_n, "Data N mismatch"),
_ => panic!("Expected DeliverData for N"),
}
+4 -4
View File
@@ -6,7 +6,7 @@
//! This module implements session lifecycle management functionality, handling
//! creation, retrieval, and storage of sessions.
use crate::packet::{EncryptedLpPacket, LpMessage};
use crate::packet::{EncryptedLpPacket, LpFrame};
use crate::peer_config::LpReceiverIndex;
use crate::{LpError, LpTransportSession};
use std::collections::HashMap;
@@ -39,12 +39,12 @@ impl SessionManager {
self.with_session_mut(lp_id, |sm| sm.process_input(input))?
}
pub fn send_data(
pub fn send_frame(
&mut self,
lp_id: LpReceiverIndex,
data: LpMessage,
frame: LpFrame,
) -> Result<LpAction, LpError> {
self.process_input(lp_id, LpInput::SendData(data))
self.process_input(lp_id, LpInput::SendFrame(frame))
}
pub fn receive_packet(
@@ -6,13 +6,13 @@ use crate::node::lp::control::{LP_DURATION_BUCKETS, LpConnectionStats};
use crate::node::lp::error::LpHandlerError;
use crate::node::lp::state::SharedLpClientControlState;
use dashmap::mapref::one::RefMut;
use nym_lp::packet::message::LpMessageType;
use nym_lp::packet::{EncryptedLpPacket, ForwardPacketData, LpMessage};
use nym_lp::packet::frame::LpFrameKind;
use nym_lp::packet::{EncryptedLpPacket, ForwardPacketData, LpFrame};
use nym_lp::peer_config::LpReceiverIndex;
use nym_lp::session::{LpAction, LpInput};
use nym_lp::transport::LpHandshakeChannel;
use nym_lp::transport::traits::LpTransportChannel;
use nym_lp::{LpTransportSession, packet::message::ExpectedResponseSize};
use nym_lp::{LpTransportSession, packet::frame::ExpectedResponseSize};
use nym_metrics::{add_histogram_obs, inc};
use nym_node_metrics::NymNodeMetrics;
use nym_registration_common::{LpRegistrationRequest, RegistrationStatus};
@@ -225,7 +225,7 @@ where
LpAction::SendPacket(response_packet) => {
self.send_serialised_packet(&response_packet).await
}
LpAction::DeliverData(data) => {
LpAction::DeliverFrame(data) => {
// Decrypted application data - process as registration/forwarding
self.handle_decrypted_payload(receiver_index, data).await
}
@@ -236,14 +236,14 @@ where
async fn handle_decrypted_payload(
&mut self,
receiver_idx: LpReceiverIndex,
decrypted_data: LpMessage,
decrypted_data: LpFrame,
) -> Result<(), LpHandlerError> {
let remote = self.remote_addr;
let header = decrypted_data.header;
let bytes = decrypted_data.content;
match header.kind {
LpMessageType::Registration => {
LpFrameKind::Registration => {
let request = LpRegistrationRequest::try_deserialise(&bytes)
.map_err(|source| LpHandlerError::MalformedRegistrationRequest { source })?;
@@ -255,13 +255,13 @@ where
self.handle_registration_request(receiver_idx, request)
.await
}
LpMessageType::Forward => {
LpFrameKind::Forward => {
let forward_data = ForwardPacketData::decode(&bytes)?;
self.handle_forwarding_request(receiver_idx, forward_data)
.await
}
typ @ LpMessageType::Opaque => {
typ @ LpFrameKind::Opaque => {
// Neither registration nor forwarding - unknown payload type
warn!(
"Unknown transport payload type from {remote} (receiver_idx={receiver_idx}). dropping {} bytes",
@@ -277,17 +277,17 @@ where
async fn send_response_packet(
&mut self,
serialised_response: Vec<u8>,
response_kind: LpMessageType,
response_kind: LpFrameKind,
) -> Result<(), LpHandlerError> {
let mut state_entry = self.state_entry_mut()?;
// Access session via state machine for subsession support
let state_machine = &mut state_entry.value_mut().state;
let wrapped_lp_data = LpMessage::new(response_kind, serialised_response);
let wrapped_lp_data = LpFrame::new(response_kind, serialised_response);
// Process packet through state machine
let action = state_machine.process_input(LpInput::SendData(wrapped_lp_data))?;
let action = state_machine.process_input(LpInput::SendFrame(wrapped_lp_data))?;
let packet = match action {
LpAction::SendPacket(packet) => packet,
@@ -312,7 +312,7 @@ where
.serialise()
.map_err(|source| LpHandlerError::MalformedRegistrationRequest { source })?;
self.send_response_packet(response_bytes, LpMessageType::Registration)
self.send_response_packet(response_bytes, LpFrameKind::Registration)
.await?;
match response.status {
@@ -349,7 +349,7 @@ where
// Forward the packet to the target gateway and retrieve its response
let response_bytes = self.handle_forward_packet(forward_data).await?;
self.send_response_packet(response_bytes, LpMessageType::Forward)
self.send_response_packet(response_bytes, LpFrameKind::Forward)
.await?;
debug!(
@@ -646,7 +646,7 @@ mod tests {
let packet = handler.receive_raw_packet().await?;
let header = packet.outer_header();
assert_eq!(packet.outer_header().receiver_idx, id);
let LpAction::DeliverData(data) = resp_sm.receive_packet(id, packet)? else {
let LpAction::DeliverFrame(data) = resp_sm.receive_packet(id, packet)? else {
panic!("illegal state")
};
Ok::<_, LpHandlerError>((header, data))
@@ -657,7 +657,7 @@ mod tests {
// Send a valid packet from client side
let LpAction::SendPacket(packet) = init_sm
.send_data(id, LpMessage::new_opaque(b"foomp".to_vec()))
.send_frame(id, LpFrame::new_opaque(b"foomp".to_vec()))
.unwrap()
else {
panic!("illegal state")
@@ -693,7 +693,7 @@ mod tests {
let (mut stream, _) = listener.accept().await.unwrap();
let LpAction::SendPacket(packet) = resp_sm
.send_data(id, LpMessage::new_opaque(b"foomp".to_vec()))
.send_frame(id, LpFrame::new_opaque(b"foomp".to_vec()))
.unwrap()
else {
panic!("illegal state")
@@ -716,7 +716,7 @@ mod tests {
.await
.unwrap();
let header = received.outer_header();
let LpAction::DeliverData(data) = init_sm.receive_packet(id, received).unwrap() else {
let LpAction::DeliverFrame(data) = init_sm.receive_packet(id, received).unwrap() else {
panic!("illegal state")
};
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2026 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use nym_lp::packet::message::LpMessageType;
use nym_lp::packet::frame::LpFrameKind;
use nym_lp::peer_config::LpReceiverIndex;
use nym_lp::session::LpAction;
use nym_lp::transport::LpTransportError;
@@ -43,7 +43,7 @@ pub enum LpHandlerError {
MalformedLpPacket(#[from] MalformedLpPacketError),
#[error("received payload type of an unexpected type: {typ:?}")]
UnexpectedLpPayload { typ: LpMessageType },
UnexpectedLpPayload { typ: LpFrameKind },
#[error("timed out while attempting to send to/receive from the connection")]
ConnectionTimeout,
@@ -5,7 +5,9 @@
use super::config::LpRegistrationConfig;
use super::error::{LpClientError, Result};
use crate::lp_client::helpers::{LpDataDeliverExt, LpDataSendExt, exponential_backoff_with_jitter};
use crate::lp_client::helpers::{
LpFrameDeliverExt, LpFrameSendExt, exponential_backoff_with_jitter,
};
use crate::lp_client::nested_session::connection::NestedConnection;
use crate::lp_client::session_helpers::{extract_forwarded_response, prepare_send_packet};
use nym_bandwidth_controller::{BandwidthTicketProvider, DEFAULT_TICKETS_TO_SPEND};
@@ -458,7 +460,7 @@ where
tracing::trace!("Built dVPN registration finalisation request");
// 3. Serialize the request
let lp_data = request.to_lp_data()?;
let lp_data = request.to_lp_frame()?;
// 4. Encrypt and prepare packet via state machine
let state_machine = self.transport_session_mut()?;
@@ -477,7 +479,7 @@ where
let received_data = extract_forwarded_response(response_packet, state_machine)?;
// 7. Extract decrypted data and deserialise the response
let response = LpRegistrationResponse::from_lp_data(received_data)?;
let response = LpRegistrationResponse::from_lp_frame(received_data)?;
let Some(dvpn_response) = response.into_dvpn_response() else {
return Err(LpClientError::unexpected_response(
"did not get a dvpn registration response after sending initial request",
@@ -545,7 +547,7 @@ where
tracing::trace!("Built dVPN registration request: {request:?}");
// 2. Serialize the request
let lp_data = request.to_lp_data()?;
let lp_data = request.to_lp_frame()?;
// 3. Encrypt and prepare packet via state machine
let state_machine = self.transport_session_mut()?;
@@ -564,7 +566,7 @@ where
let received_data = extract_forwarded_response(response_packet, state_machine)?;
// 6. Extract decrypted data and deserialise the response
let response = LpRegistrationResponse::from_lp_data(received_data)?;
let response = LpRegistrationResponse::from_lp_frame(received_data)?;
let Some(dvpn_response) = response.into_dvpn_response() else {
return Err(LpClientError::unexpected_response(
"did not get a dvpn registration response after sending initial request",
@@ -5,7 +5,7 @@
use nym_lp::LpError;
use nym_lp::packet::MalformedLpPacketError;
use nym_lp::packet::message::LpMessageType;
use nym_lp::packet::frame::LpFrameKind;
use nym_lp::session::LpAction;
use nym_lp::transport::LpTransportError;
use thiserror::Error;
@@ -43,7 +43,7 @@ pub enum LpClientError {
MalformedLpPacket(#[from] MalformedLpPacketError),
#[error("received payload type of an unexpected type: {typ:?}")]
UnexpectedLpPayload { typ: LpMessageType },
UnexpectedLpPayload { typ: LpFrameKind },
#[error("timed out while attempting to finish the KKT/PSQ handshake")]
HandshakeTimeout,
@@ -4,8 +4,8 @@
#![allow(dead_code)]
use crate::LpClientError;
use nym_lp::packet::message::LpMessageType;
use nym_lp::packet::{ForwardPacketData, LpMessage};
use nym_lp::packet::frame::LpFrameKind;
use nym_lp::packet::{ForwardPacketData, LpFrame};
use nym_lp::peer::LpRemotePeer;
use nym_lp::session::{LpAction, LpInput};
use nym_registration_common::{
@@ -13,16 +13,16 @@ use nym_registration_common::{
};
use rand09::Rng;
pub(crate) trait LpDataSendExt {
fn to_lp_data(&self) -> Result<LpMessage, LpClientError>;
pub(crate) trait LpFrameSendExt {
fn to_lp_frame(&self) -> Result<LpFrame, LpClientError>;
}
pub(crate) trait LpDataDeliverExt: Sized {
fn from_lp_data(data: LpMessage) -> Result<Self, LpClientError>;
pub(crate) trait LpFrameDeliverExt: Sized {
fn from_lp_frame(frame: LpFrame) -> Result<Self, LpClientError>;
}
impl LpDataSendExt for LpRegistrationRequest {
fn to_lp_data(&self) -> Result<LpMessage, LpClientError> {
impl LpFrameSendExt for LpRegistrationRequest {
fn to_lp_frame(&self) -> Result<LpFrame, LpClientError> {
let request_bytes = self.serialise().map_err(|e| {
LpClientError::SendRegistrationRequest(format!("Failed to serialize request: {e}"))
})?;
@@ -32,25 +32,25 @@ impl LpDataSendExt for LpRegistrationRequest {
request_bytes.len()
);
Ok(LpMessage::new_registration(request_bytes))
Ok(LpFrame::new_registration(request_bytes))
}
}
impl LpDataDeliverExt for LpRegistrationResponse {
fn from_lp_data(data: LpMessage) -> Result<Self, LpClientError> {
if data.kind() != LpMessageType::Registration {
return Err(LpClientError::UnexpectedLpPayload { typ: data.kind() });
impl LpFrameDeliverExt for LpRegistrationResponse {
fn from_lp_frame(frame: LpFrame) -> Result<Self, LpClientError> {
if frame.kind() != LpFrameKind::Registration {
return Err(LpClientError::UnexpectedLpPayload { typ: frame.kind() });
}
let response = LpRegistrationResponse::try_deserialise(&data.content)
let response = LpRegistrationResponse::try_deserialise(&frame.content)
.map_err(|source| LpClientError::MalformedRegistrationData { source })?;
Ok(response)
}
}
impl LpDataSendExt for ForwardPacketData {
fn to_lp_data(&self) -> Result<LpMessage, LpClientError> {
impl LpFrameSendExt for ForwardPacketData {
fn to_lp_frame(&self) -> Result<LpFrame, LpClientError> {
let request_bytes = self.to_bytes();
tracing::trace!(
@@ -58,21 +58,21 @@ impl LpDataSendExt for ForwardPacketData {
request_bytes.len()
);
Ok(LpMessage::new_forward(request_bytes))
Ok(LpFrame::new_forward(request_bytes))
}
}
pub(crate) fn convert_forward_data(request: ForwardPacketData) -> Result<LpInput, LpClientError> {
Ok(LpInput::SendData(request.to_lp_data()?))
Ok(LpInput::SendFrame(request.to_lp_frame()?))
}
pub(crate) fn try_convert_forward_response(action: LpAction) -> Result<Vec<u8>, LpClientError> {
let response_data = match action {
LpAction::DeliverData(data) => data,
LpAction::DeliverFrame(data) => data,
action => return Err(LpClientError::UnexpectedStateMachineAction { action }),
};
if response_data.kind() != LpMessageType::Forward {
if response_data.kind() != LpFrameKind::Forward {
return Err(LpClientError::UnexpectedLpPayload {
typ: response_data.kind(),
});
@@ -5,7 +5,7 @@ use crate::lp_client::helpers::{convert_forward_data, try_convert_forward_respon
use crate::{LpClientError, LpRegistrationClient};
use bytes::{BufMut, BytesMut};
use nym_lp::KEM;
use nym_lp::packet::{EncryptedLpPacket, ForwardPacketData, message::ExpectedResponseSize};
use nym_lp::packet::{EncryptedLpPacket, ForwardPacketData, frame::ExpectedResponseSize};
use nym_lp::session::{LpAction, LpInput};
use nym_lp::transport::traits::{HandshakeMessage, LpTransportChannel};
use nym_lp::transport::{LpHandshakeChannel, LpTransportError};
@@ -20,13 +20,15 @@
use super::client::LpRegistrationClient;
use super::error::{LpClientError, Result};
use crate::lp_client::helpers::{LpDataDeliverExt, LpDataSendExt, exponential_backoff_with_jitter};
use crate::lp_client::helpers::{
LpFrameDeliverExt, LpFrameSendExt, exponential_backoff_with_jitter,
};
use crate::lp_client::session_helpers::{extract_forwarded_response, prepare_send_packet};
use nym_bandwidth_controller::{BandwidthTicketProvider, DEFAULT_TICKETS_TO_SPEND};
use nym_credentials_interface::TicketType;
use nym_crypto::asymmetric::{ed25519, x25519};
use nym_lp::packet::version;
use nym_lp::packet::{EncryptedLpPacket, LpMessage};
use nym_lp::packet::{EncryptedLpPacket, LpFrame};
use nym_lp::peer::{DHKeyPair, LpLocalPeer, LpRemotePeer};
use nym_lp::psq::initiator::HandshakeMode;
use nym_lp::transport::LpHandshakeChannel;
@@ -126,19 +128,19 @@ impl NestedLpSession {
.ok_or(LpClientError::IncompleteHandshake)
}
/// Attempt to wrap the provided `LpData` into a `EncryptedLpPacket`
/// Attempt to wrap the provided `LpFrame` into a `EncryptedLpPacket`
/// using the inner state machine.
fn prepare_transport_packet(&mut self, data: LpMessage) -> Result<EncryptedLpPacket> {
fn prepare_transport_packet(&mut self, frame: LpFrame) -> Result<EncryptedLpPacket> {
let state_machine = self.state_machine_mut()?;
prepare_send_packet(data, state_machine)
prepare_send_packet(frame, state_machine)
}
/// Attempt to recover received `LpData` from the received `EncryptedLpPacket`
/// Attempt to recover received `LpFrame` from the received `EncryptedLpPacket`
/// using the inner state machine.
fn extract_forwarded_response(
&mut self,
response_packet: EncryptedLpPacket,
) -> Result<LpMessage> {
) -> Result<LpFrame> {
let state_machine = self.state_machine_mut()?;
extract_forwarded_response(response_packet, state_machine)
}
@@ -255,7 +257,7 @@ impl NestedLpSession {
tracing::trace!("Built dVPN registration finalisation request");
// Step 3: Serialize the request
let send_data = request.to_lp_data()?;
let send_data = request.to_lp_frame()?;
// Step 4: Encrypt and prepare packet via state machine
let forward_packet = self.prepare_transport_packet(send_data)?;
@@ -274,7 +276,7 @@ impl NestedLpSession {
let response_data = self.extract_forwarded_response(response)?;
// Step 8: Extract decrypted data and deserialise the response
let response = LpRegistrationResponse::from_lp_data(response_data)?;
let response = LpRegistrationResponse::from_lp_frame(response_data)?;
let Some(dvpn_response) = response.into_dvpn_response() else {
return Err(LpClientError::unexpected_response(
"did not get a dvpn registration response after sending initial request",
@@ -349,7 +351,7 @@ impl NestedLpSession {
let request = LpRegistrationRequest::new_initial_dvpn(wg_public_key, psk);
// Step 3: Serialize the request
let send_data = request.to_lp_data()?;
let send_data = request.to_lp_frame()?;
// Step 4: Encrypt and prepare packet via state machine
let forward_packet = self.prepare_transport_packet(send_data)?;
@@ -369,7 +371,7 @@ impl NestedLpSession {
let response_data = self.extract_forwarded_response(response)?;
// Step 8: Extract decrypted data and deserialise the response
let response = LpRegistrationResponse::from_lp_data(response_data)?;
let response = LpRegistrationResponse::from_lp_frame(response_data)?;
let Some(dvpn_response) = response.into_dvpn_response() else {
return Err(LpClientError::unexpected_response(
"did not get a dvpn registration response after sending initial request",
@@ -2,17 +2,17 @@
// SPDX-License-Identifier: Apache-2.0
use crate::LpClientError;
use nym_lp::packet::LpMessage;
use nym_lp::packet::LpFrame;
use nym_lp::session::{LpAction, LpInput};
use nym_lp::{LpTransportSession, packet::EncryptedLpPacket};
/// Attempt to prepare the provided data for sending by wrapping it in appropriate `LpAction`,
/// and attempting to extract `EncryptedLpPacket` from the provided state machine.
pub(crate) fn prepare_send_packet(
data: LpMessage,
frame: LpFrame,
state_machine: &mut LpTransportSession,
) -> Result<EncryptedLpPacket, LpClientError> {
let action = state_machine.process_input(LpInput::SendData(data))?;
let action = state_machine.process_input(LpInput::SendFrame(frame))?;
match action {
LpAction::SendPacket(packet) => Ok(packet),
@@ -25,11 +25,11 @@ pub(crate) fn prepare_send_packet(
pub(crate) fn extract_forwarded_response(
response_packet: EncryptedLpPacket,
state_machine: &mut LpTransportSession,
) -> Result<LpMessage, LpClientError> {
) -> Result<LpFrame, LpClientError> {
let action = state_machine.process_input(LpInput::ReceivePacket(response_packet))?;
match action {
LpAction::DeliverData(data) => Ok(data),
LpAction::DeliverFrame(frame) => Ok(frame),
action => Err(LpClientError::UnexpectedStateMachineAction { action }),
}
}