use crate::error::{Error, ErrorCode, Result, bail};
use crate::msg::{
Destination, MessageCounter, MessageHeader, NonceSource, ProtocolHeader, SessionId,
SessionKeys, SessionType, preview, protect, unprotect,
};
use crate::msg::{FabricIndex, GroupId, NodeId};
use crate::platform::PeerAddr;
use super::GroupContext;
use super::keys::{GroupKeys, OperationalKey};
use super::peers::{Admitted, PeerTable};
#[derive(Debug)]
pub struct Sender {
node: NodeId,
data: MessageCounter,
control: MessageCounter,
}
impl Sender {
#[must_use]
pub const fn new(node: NodeId, data: u32, control: u32) -> Self {
Self {
node,
data: MessageCounter::new(data),
control: MessageCounter::new(control),
}
}
#[must_use]
pub const fn restore(node: NodeId, data: u32, control: u32) -> Self {
Self {
node,
data: MessageCounter::at(data),
control: MessageCounter::at(control),
}
}
#[must_use]
pub const fn node(&self) -> NodeId {
self.node
}
#[expect(
clippy::too_many_arguments,
reason = "every one is a distinct fact about the message, the way `Messaging::send`'s \
are; bundling them would move the same list one line up"
)]
pub fn send(
&mut self,
key: &OperationalKey,
group: GroupId,
protocol_header: &ProtocolHeader,
payload: &[u8],
control: bool,
scratch: &mut [u8],
out: &mut [u8],
) -> Result<usize> {
let counter = if control {
self.control.take_with_rollover()
} else {
self.data.take_with_rollover()
};
let header = MessageHeader {
session_id: SessionId(key.session_id),
session_type: SessionType::Group,
message_counter: counter,
source: Some(self.node),
destination: Destination::Group(group),
privacy: true,
control,
};
let body = join(protocol_header, payload, scratch)?;
let keys = SessionKeys::from_encryption_key(key.key.clone())?;
protect(&header, NonceSource::Group, body, &keys, out)
}
}
#[derive(Debug)]
pub struct Inbound<'a> {
pub context: GroupContext,
pub protocol: ProtocolHeader,
pub payload: &'a [u8],
pub counter: u32,
pub control: bool,
}
#[derive(Debug)]
pub enum Received<'a> {
Message(Inbound<'a>),
Duplicate(GroupContext),
NeedsSync(GroupContext),
Untracked(GroupContext),
}
pub fn receive<
'b,
Cfg: crate::config::Config,
const K: usize,
const M: usize,
const D: usize,
const C: usize,
>(
buf: &'b mut [u8],
from: PeerAddr,
keys: &GroupKeys<Cfg, K, M>,
peers: &mut PeerTable<D, C>,
compressed: impl Fn(FabricIndex) -> Option<crate::fabric::CompressedFabricId>,
scratch: &mut [u8],
) -> Result<Received<'b>> {
let head = preview(buf)?;
if !matches!(head.session_type, SessionType::Group) {
bail!(InvalidArgument)
}
let original = scratch
.get_mut(..buf.len())
.ok_or(Error::new(ErrorCode::BufferTooSmall))?;
original.copy_from_slice(buf);
let candidates = keys.receiving_keys::<8>(compressed, head.session_id.0);
let mut authenticated = None;
for candidate in &candidates {
let Ok(session_keys) = SessionKeys::from_encryption_key(candidate.key.clone()) else {
continue;
};
buf.copy_from_slice(original);
if let Ok((header, range)) = unprotect(buf, &session_keys, NonceSource::Group) {
authenticated = Some((candidate, header, range));
break;
}
}
let Some((key, header, range)) = authenticated else {
bail!(IntegrityCheckFailed)
};
let source = header
.source
.ok_or(Error::new(ErrorCode::MessageReserved))?;
let Destination::Group(group) = header.destination else {
bail!(MessageReserved)
};
let context = GroupContext {
fabric_index: key.fabric_index,
group,
source,
from,
session_id: header.session_id.0,
key_set: key.key_set,
};
let admitted = peers.admit(
key.fabric_index,
source,
header.control,
header.message_counter,
key.policy,
);
match admitted {
Admitted::Duplicate => return Ok(Received::Duplicate(context)),
Admitted::NeedsSync => return Ok(Received::NeedsSync(context)),
Admitted::Untracked => return Ok(Received::Untracked(context)),
Admitted::Process => {}
}
let Some(payload) = buf.get(range) else {
bail!(MessageTruncated)
};
let (protocol, body) = ProtocolHeader::decode(payload)?;
Ok(Received::Message(Inbound {
context,
protocol,
payload: body,
counter: header.message_counter,
control: header.control,
}))
}
fn join<'a>(
protocol_header: &ProtocolHeader,
payload: &[u8],
scratch: &'a mut [u8],
) -> Result<&'a [u8]> {
let header_len = protocol_header.encode(scratch)?;
let end = header_len
.checked_add(payload.len())
.ok_or(Error::new(ErrorCode::BufferTooSmall))?;
let slot = scratch
.get_mut(header_len..end)
.ok_or(Error::new(ErrorCode::BufferTooSmall))?;
slot.copy_from_slice(payload);
scratch
.get(..end)
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
}