1#![deny(missing_docs)]
2#![forbid(unsafe_code)]
3
4use std::borrow::Borrow;
5use std::fmt;
6use std::num::NonZeroU64;
7use std::sync::Arc;
8#[cfg(test)]
9use std::sync::LazyLock;
10#[cfg(test)]
11use std::sync::Mutex;
12
13use async_trait::async_trait;
14use bytes::Bytes;
15use serde::de::DeserializeOwned;
16use serde::Deserialize;
17use serde::Serialize;
18
19use super::encoder::Decoder;
20use super::encoder::Encoded;
21use super::encoder::Encoder;
22use super::protocols::DomainTag;
23use super::protocols::HopBudget;
24use super::protocols::MessageRelay;
25use super::protocols::MessageSigner;
26use super::protocols::MessageVerification;
27use super::protocols::MessageVerificationExt;
28use super::replay::StreamKey;
29use super::replay::TransactionDigest;
30use crate::delegation::DelegateeKey;
31use crate::delegation::Delegation;
32use crate::delegation::DelegatorAuthorization;
33use crate::dht::delivery::NextHop;
34use crate::dht::delivery::RouteStage;
35use crate::dht::Did;
36use crate::dht::PeerRing;
37use crate::domain_tag;
38use crate::ecc::keccak256;
39use crate::error::Error;
40use crate::error::Result;
41use crate::message::verify_message_under;
42use crate::message::Message;
43use crate::message::MessageCategory;
44use crate::message::MessageKind;
45#[cfg(test)]
46use crate::utils::get_epoch_ms;
47
48mod frame;
49mod wire;
50
51pub(crate) use self::frame::may_start_compressed_payload;
52pub use self::frame::PeerWireVersion;
53pub use self::frame::WireVersionMismatch;
54pub use self::frame::WIRE_VERSION;
55pub(crate) use self::wire::DelegationRef;
56pub(crate) use self::wire::LinkControl;
57pub(crate) use self::wire::LinkFrame;
58pub(crate) use self::wire::PerSlot;
59pub(crate) use self::wire::SlotEncoding;
60pub(crate) use self::wire::WirePayload;
61pub(crate) use self::wire::MAX_COMPRESSED_FRAME_WIRE_BYTES;
62#[cfg(test)]
63pub(crate) use self::wire::MAX_COMPRESSED_PAYLOAD_BYTES;
64#[cfg(test)]
65pub(crate) use self::wire::WIRE_COMPRESSION_DICT;
66
67const TRANSACTION_DOMAIN_TAG: DomainTag =
69 domain_tag!("rings-core:message-verification:transaction");
70const PAYLOAD_DOMAIN_TAG: DomainTag = domain_tag!("rings-core:message-verification:payload");
74#[cfg(test)]
75static TEST_TRANSACTION_SEQUENCES: LazyLock<Mutex<std::collections::BTreeMap<StreamKey, u64>>> =
76 LazyLock::new(|| Mutex::new(std::collections::BTreeMap::new()));
77
78#[cfg(test)]
79fn next_test_transaction_sequence(key: StreamKey) -> Result<u64> {
80 let mut sequences = TEST_TRANSACTION_SEQUENCES
81 .lock()
82 .map_err(|_| Error::TransactionReplayStateInvalid)?;
83 let Some(last) = sequences.get_mut(&key) else {
84 sequences.insert(key, 0);
85 return Ok(0);
86 };
87 let next = last
88 .checked_add(1)
89 .ok_or(Error::TransactionSequenceExhausted { key })?;
90 *last = next;
91 Ok(next)
92}
93
94fn hash_transaction(
102 origin: Did,
103 destination: Did,
104 tx_id: uuid::Uuid,
105 sequence: u64,
106 reply_via: Option<Did>,
107 data: &[u8],
108) -> [u8; 32] {
109 let mut msg = vec![];
110
111 msg.extend_from_slice(origin.as_bytes());
112 msg.extend_from_slice(destination.as_bytes());
113 msg.extend_from_slice(tx_id.as_bytes());
114 msg.extend_from_slice(&sequence.to_be_bytes());
115 match reply_via {
116 Some(peer) => {
117 msg.push(1);
118 msg.extend_from_slice(peer.as_bytes());
119 }
120 None => msg.push(0),
121 }
122 msg.extend_from_slice(data);
123
124 keccak256(&msg)
125}
126
127#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
142pub struct Transaction {
143 pub destination: Did,
145 pub tx_id: uuid::Uuid,
148 pub sequence: u64,
150 pub reply_via: Option<Did>,
156 pub data: Vec<u8>,
158 pub verification: MessageVerification,
161}
162
163impl fmt::Debug for Transaction {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 f.debug_struct("Transaction")
166 .field("destination", &self.destination)
167 .field("tx_id", &self.tx_id)
168 .field("sequence", &self.sequence)
169 .field("reply_via", &self.reply_via)
170 .field("data_bytes", &self.data.len())
171 .finish()
172 }
173}
174
175#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
178pub struct MessagePayload {
179 pub transaction: Transaction,
181 pub relay: MessageRelay,
183 pub verification: MessageVerification,
186}
187
188impl fmt::Debug for MessagePayload {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 f.debug_struct("MessagePayload")
191 .field("transaction", &self.transaction)
192 .field("relay", &self.relay)
193 .finish()
194 }
195}
196
197impl Transaction {
198 pub fn new<T>(
203 destination: Did,
204 tx_id: uuid::Uuid,
205 sequence: u64,
206 reply_via: Option<Did>,
207 data: T,
208 signer: MessageSigner<impl Borrow<DelegateeKey>>,
209 ) -> Result<Self>
210 where
211 T: Serialize,
212 {
213 let data = rings_codec::serialize(&data).map_err(Error::CodecSerialize)?;
214 let msg_hash = hash_transaction(
215 signer.delegator_did(),
216 destination,
217 tx_id,
218 sequence,
219 reply_via,
220 &data,
221 );
222 let verification = signer.sign(TRANSACTION_DOMAIN_TAG, &msg_hash)?;
223 Ok(Self {
224 destination,
225 tx_id,
226 sequence,
227 reply_via,
228 data,
229 verification,
230 })
231 }
232
233 fn signed_hash(&self) -> [u8; 32] {
235 hash_transaction(
236 self.origin(),
237 self.destination,
238 self.tx_id,
239 self.sequence,
240 self.reply_via,
241 &self.data,
242 )
243 }
244
245 pub fn origin(&self) -> Did {
250 self.signer()
251 }
252
253 pub fn class(&self) -> Result<MessageCategory> {
257 MessageKind::from_wire(&self.data).map(MessageKind::class)
258 }
259
260 pub fn stream_key(&self, network_id: u32) -> Result<StreamKey> {
263 Ok(StreamKey::new(
264 network_id,
265 self.origin(),
266 self.destination,
267 self.class()?,
268 ))
269 }
270
271 pub fn digest(&self) -> Result<TransactionDigest> {
273 let wire = rings_codec::serialize(self).map_err(Error::CodecSerialize)?;
274 Ok(TransactionDigest::new(keccak256(&wire)))
275 }
276
277 pub fn data<T>(&self) -> Result<T>
279 where T: DeserializeOwned {
280 rings_codec::deserialize(&self.data).map_err(Error::CodecDeserialize)
281 }
282}
283
284impl MessagePayload {
285 pub fn new(
288 transaction: Transaction,
289 signer: MessageSigner<impl Borrow<DelegateeKey>>,
290 relay: MessageRelay,
291 ) -> Result<Self> {
292 let verification = signer.sign(PAYLOAD_DOMAIN_TAG, &transaction.signed_hash())?;
293 Ok(Self {
294 transaction,
295 relay,
296 verification,
297 })
298 }
299
300 pub fn new_send_with_sequence<T>(
303 data: T,
304 signer: MessageSigner<impl Borrow<DelegateeKey>>,
305 hop: NextHop,
306 destination: Did,
307 sequence: u64,
308 reply_via: Option<Did>,
309 ) -> Result<Self>
310 where
311 T: Serialize,
312 {
313 let tx_id = crate::utils::new_uuid();
314 let transaction = Transaction::new(
315 destination,
316 tx_id,
317 sequence,
318 reply_via,
319 data,
320 signer.by_ref(),
321 )?;
322 let relay = MessageRelay::new(hop, transaction.destination, HopBudget::MAX);
323 Self::new(transaction, signer.by_ref(), relay)
324 }
325
326 #[cfg(test)]
327 pub(crate) fn new_send<T>(
328 data: T,
329 signer: MessageSigner<impl Borrow<DelegateeKey>>,
330 next_hop: Did,
331 destination: Did,
332 ) -> Result<Self>
333 where
334 T: Serialize,
335 {
336 let class = rings_codec::serialize(&data)
339 .ok()
340 .and_then(|bytes| MessageKind::from_wire(&bytes).ok())
341 .map_or(MessageCategory::Application, MessageKind::class);
342 let sequence = next_test_transaction_sequence(StreamKey::new(
343 signer.network_id(),
344 signer.delegator_did(),
345 destination,
346 class,
347 ))?;
348 Self::new_send_with_sequence(
349 data,
350 signer,
351 NextHop::toward(next_hop),
352 destination,
353 sequence,
354 None,
355 )
356 }
357
358 pub(crate) const fn delegations(&self) -> PerSlot<&Delegation> {
360 PerSlot {
361 origin: &self.transaction.verification.delegation,
362 hop: &self.verification.delegation,
363 }
364 }
365
366 pub fn from_wire(data: &[u8]) -> Result<Self> {
373 Self::from_wire_with_uncompressed_len(data).map(|(payload, _)| payload)
374 }
375
376 pub(crate) fn from_wire_with_uncompressed_len(data: &[u8]) -> Result<(Self, usize)> {
378 match LinkFrame::from_wire_with_uncompressed_len(data)? {
379 (LinkFrame::Payload(frame), uncompressed_len) => {
380 Ok((frame.into_self_contained()?, uncompressed_len))
381 }
382 (LinkFrame::Control(_), _) => Err(Error::LinkControlOutsideLink),
383 }
384 }
385
386 pub fn to_wire(&self) -> Result<Bytes> {
389 WirePayload::inline(self).to_wire()
390 }
391
392 pub(crate) fn wire_size(&self) -> Result<usize> {
397 WirePayload::inline(self).wire_size()
398 }
399
400 pub(crate) fn is_relay_destination_for(&self, local: Did) -> bool {
402 self.relay.destination == local
403 }
404
405 pub(crate) fn should_forward_from(&self, local: Did) -> bool {
407 !self.is_relay_destination_for(local)
408 }
409
410 pub(crate) fn relay_destination_matches_transaction(&self) -> bool {
414 self.relay.destination == self.transaction.destination
415 || (MessageKind::from_wire(&self.transaction.data)
416 .is_ok_and(MessageKind::permits_destination_reset)
417 && self
418 .transaction
419 .data::<Message>()
420 .is_ok_and(|message| message.permits_destination_reset()))
421 }
422
423 #[cfg(test)]
425 pub(crate) fn verify_transaction_and_payload(&self, network_id: u32) -> bool {
426 self.verify_transaction_and_payload_at(network_id, get_epoch_ms())
427 }
428
429 pub(crate) fn verify_transaction_and_payload_at(&self, network_id: u32, now_ms: u128) -> bool {
431 self.verify_transaction_and_payload_under_at(
432 network_id,
433 now_ms,
434 PerSlot::full_verification(),
435 )
436 }
437
438 pub(crate) fn verify_transaction_and_payload_under_at(
442 &self,
443 network_id: u32,
444 now_ms: u128,
445 authorization: PerSlot<DelegatorAuthorization>,
446 ) -> bool {
447 verify_message_under(&self.transaction, network_id, now_ms, authorization.origin)
448 && verify_message_under(self, network_id, now_ms, authorization.hop)
449 && self.relay_destination_matches_transaction()
450 }
451}
452
453impl MessageVerificationExt for Transaction {
454 const DOMAIN_TAG: DomainTag = TRANSACTION_DOMAIN_TAG;
455
456 fn verification_data(&self) -> Result<Vec<u8>> {
457 Ok(self.signed_hash().to_vec())
458 }
459
460 fn verification(&self) -> &MessageVerification {
461 &self.verification
462 }
463}
464
465impl MessageVerificationExt for MessagePayload {
466 const DOMAIN_TAG: DomainTag = PAYLOAD_DOMAIN_TAG;
467
468 fn verification_data(&self) -> Result<Vec<u8>> {
469 self.transaction.verification_data()
470 }
471
472 fn verification(&self) -> &MessageVerification {
473 &self.verification
474 }
475}
476
477impl Encoder for MessagePayload {
478 fn encode(&self) -> Result<Encoded> {
479 self.to_wire()?.encode()
480 }
481}
482
483impl Decoder for MessagePayload {
484 fn from_encoded(encoded: &Encoded) -> Result<Self> {
485 let v: Bytes = encoded.decode()?;
486 Self::from_wire(&v)
487 }
488}
489
490#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
492#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
493pub trait PayloadSender {
494 fn message_signer(&self) -> MessageSigner<DelegateeKey>;
496
497 fn dht(&self) -> Arc<PeerRing>;
499
500 fn is_connected(&self, did: Did) -> bool;
502
503 async fn reserve_transaction_sequences(
506 &self,
507 destination: Did,
508 class: MessageCategory,
509 count: NonZeroU64,
510 ) -> Result<std::ops::RangeInclusive<u64>>;
511
512 async fn do_send_payload(&self, did: Did, payload: MessagePayload) -> Result<()>;
514
515 fn next_hop_toward(&self, destination: Did, stage: RouteStage) -> Result<NextHop> {
521 self.dht()
522 .delivery_step(destination, stage, |peer| self.is_connected(peer))?
523 .ok_or(Error::RelayDestinationUnreachable { destination })
524 }
525
526 async fn originate(
541 &self,
542 msg: Message,
543 destination: Did,
544 next_hop: Option<Did>,
545 ) -> Result<MessagePayload> {
546 let (hop, reply_via) = match next_hop {
547 Some(peer) => (
548 NextHop::toward(peer),
549 self.dht().reply_via(|peer| self.is_connected(peer))?,
550 ),
551 None => {
552 let origination = self
553 .dht()
554 .origination(destination, |peer| self.is_connected(peer))?;
555 let hop = origination
556 .hop
557 .ok_or(Error::RelayDestinationUnreachable { destination })?;
558 (hop, origination.reply_via)
559 }
560 };
561 self.originate_through(msg, hop, destination, reply_via)
562 .await
563 }
564
565 async fn originate_through(
569 &self,
570 msg: Message,
571 hop: NextHop,
572 destination: Did,
573 reply_via: Option<Did>,
574 ) -> Result<MessagePayload> {
575 let sequence = self.next_sequence(destination, &msg).await?;
576 let signer = self.message_signer();
577 MessagePayload::new_send_with_sequence(
578 msg,
579 signer.by_ref(),
580 hop,
581 destination,
582 sequence,
583 reply_via,
584 )
585 }
586
587 async fn next_sequence(&self, destination: Did, msg: &Message) -> Result<u64> {
590 let class = MessageKind::from_message(msg).class();
591 Ok(*self
592 .reserve_transaction_sequences(destination, class, NonZeroU64::MIN)
593 .await?
594 .start())
595 }
596
597 async fn send_payload(&self, payload: MessagePayload) -> Result<()> {
599 self.do_send_payload(payload.relay.next_hop, payload).await
600 }
601
602 async fn send_message_by_hop(
604 &self,
605 msg: Message,
606 destination: Did,
607 next_hop: Did,
608 ) -> Result<uuid::Uuid> {
609 let payload = self.originate(msg, destination, Some(next_hop)).await?;
610 let tx_id = payload.transaction.tx_id;
611 self.send_payload(payload).await?;
612 Ok(tx_id)
613 }
614
615 async fn send_message(&self, msg: Message, destination: Did) -> Result<uuid::Uuid> {
617 let payload = self.originate(msg, destination, None).await?;
618 let tx_id = payload.transaction.tx_id;
619 self.send_payload(payload).await?;
620 Ok(tx_id)
621 }
622
623 async fn send_direct_message(&self, msg: Message, destination: Did) -> Result<uuid::Uuid> {
625 self.send_message_by_hop(msg, destination, destination)
626 .await
627 }
628
629 async fn send_report_message(&self, payload: &MessagePayload, msg: Message) -> Result<()> {
638 let origin = payload.transaction.origin();
639 let reply_via = payload
640 .transaction
641 .reply_via
642 .filter(|_| msg.returns_through_reply_via());
643 let hop = self.next_hop_toward(origin, RouteStage::replying_via(reply_via))?;
644 let relay = payload.relay.report(self.dht().did, origin, hop)?;
645 self.send_reply(payload, relay, payload.transaction.tx_id, msg)
646 .await
647 }
648
649 async fn send_reply(
652 &self,
653 request: &MessagePayload,
654 relay: MessageRelay,
655 tx_id: uuid::Uuid,
656 msg: Message,
657 ) -> Result<()> {
658 let origin = request.transaction.origin();
659 let signer = self.message_signer();
660 let sequence = self.next_sequence(origin, &msg).await?;
661 let transaction = Transaction::new(origin, tx_id, sequence, None, msg, signer.by_ref())?;
662 let payload = MessagePayload::new(transaction, signer.by_ref(), relay)?;
663 self.send_payload(payload).await
664 }
665
666 async fn forward_by_relay(&self, payload: &MessagePayload, relay: MessageRelay) -> Result<()> {
669 let signer = self.message_signer();
670 let new_pl = MessagePayload::new(payload.transaction.clone(), signer.by_ref(), relay)?;
671 self.send_payload(new_pl).await
672 }
673
674 async fn forward_payload(&self, payload: &MessagePayload, next_hop: Option<Did>) -> Result<()> {
683 let (local, destination) = (self.dht().did, payload.relay.destination);
684 let return_hop =
685 if MessageKind::from_wire(&payload.transaction.data)?.carries_signaling_path() {
686 payload
687 .relay
688 .linked_return_hop(|peer| self.is_connected(peer))?
689 } else {
690 None
691 };
692 let hop = match (return_hop, next_hop) {
693 (Some(hop), _) => NextHop::new(hop, payload.relay.stage),
694 (None, None) => self.next_hop_toward(destination, payload.relay.stage)?,
695 (None, Some(_)) if self.is_connected(destination) => {
696 NextHop::new(destination, payload.relay.stage)
697 }
698 (None, Some(next_hop)) => NextHop::new(next_hop, payload.relay.stage),
699 };
700 let relay = payload.relay.forward(local, hop)?;
701 self.forward_by_relay(payload, relay).await
702 }
703
704 async fn reset_destination(&self, payload: &MessagePayload, next_hop: Did) -> Result<()> {
707 let hop = self.next_hop_toward(next_hop, RouteStage::TOWARD)?;
708 let relay = payload
709 .relay
710 .reset_destination(next_hop)
711 .forward(self.dht().did, hop)?;
712 self.forward_by_relay(payload, relay).await
713 }
714}
715
716#[cfg(test)]
717pub mod test_payload;
718#[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
719mod test_wire_goldens;