Skip to main content

rings_core/message/payload/
mod.rs

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
67/// Message family of the [`Transaction`] signature: the origin's authorship of a message.
68const TRANSACTION_DOMAIN_TAG: DomainTag =
69    domain_tag!("rings-core:message-verification:transaction");
70/// Message family of the [`MessagePayload`] signature: one hop's authorship of a forwarded
71/// envelope. Distinct from [`TRANSACTION_DOMAIN_TAG`] so the two signatures over the same
72/// transaction hash are never interchangeable.
73const 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
94/// The digest both signatures of a payload cover: every signed field of the transaction,
95/// bound to the origin delegator DID so swapping the delegation slot for another delegator
96/// sharing the same delegatee key invalidates the transaction signature.
97///
98/// `origin` and `destination` are fixed-width 20-byte DIDs, and `reply_via` is encoded as a
99/// presence byte followed by the DID when present, before the variable-length `data`, so the
100/// encoding stays injective.
101fn 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/// All messages transmitted in RingsNetwork should be wrapped by `Transaction`.
128/// It additionally offer destination, tx_id and verification.
129///
130/// Every reply to a transaction is addressed to the transaction's [origin](Self::origin), and
131/// takes one of two routes. Only the successor answer a node needs while it has no
132/// predecessor (`FindSuccessorReport`) first goes through [`reply_via`](Self::reply_via) when
133/// the origin signed one; a connect-signaling reply retraces, hop by linked hop, the path its
134/// request recorded (#947); every other report routes straight toward the origin. No other
135/// return address exists, so a request can direct no reply at a third party except the one
136/// bounded successor answer at the one peer the origin itself named, which receives it whole
137/// and hands it on only over a direct link to the origin (see [`crate::dht::delivery`]).
138///
139/// To transmit `Transaction` in RingsNetwork, user should build
140/// [MessagePayload] and use [PayloadSender] to send.
141#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
142pub struct Transaction {
143    /// The destination of this message.
144    pub destination: Did,
145    /// The transaction ID.
146    /// Remote peer should use same tx_id when response.
147    pub tx_id: uuid::Uuid,
148    /// Monotonic sequence inside the origin account's destination-scoped stream.
149    pub sequence: u64,
150    /// The peer the origin's successor answers (`FindSuccessorReport`) return through while no
151    /// node is known to route to the origin: its nearest linked successor whenever it has no
152    /// predecessor, i.e. while it joins and again after its predecessor departs until a new one
153    /// notifies it; `None` otherwise. Signed with the rest of the transaction, so only the
154    /// origin chooses it.
155    pub reply_via: Option<Did>,
156    /// data
157    pub data: Vec<u8>,
158    /// This field holds a signature from a node,
159    /// which is used to prove that the transaction was created by that node.
160    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/// `MessagePayload` is used to transmit data between nodes.
176/// The data should be packed by [Transaction].
177#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
178pub struct MessagePayload {
179    /// Payload data
180    pub transaction: Transaction,
181    /// The relay carrier: the next hop, the destination, and the forwards left.
182    pub relay: MessageRelay,
183    /// This field holds a signature from a node,
184    /// which is used to prove that payload was created by that node.
185    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    /// Wrap data: serialize it with [rings_codec::serialize], then sign it, `reply_via`
199    /// included, with `signer`. `reply_via` names the peer the origin's successor answers
200    /// return through; a reply, or any transaction whose origin has a predecessor, names
201    /// `None`.
202    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    /// The digest both the origin's and each hop's signature cover.
234    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    /// The origin of this transaction: the account that authorized the session it is signed
246    /// by, i.e. [`MessageVerificationExt::signer`] under the name the routing layer uses for it.
247    /// This is the ring position a request is authorized against and the address its report is
248    /// routed to; it is never the session id, which names a key, not a node.
249    pub fn origin(&self) -> Did {
250        self.signer()
251    }
252
253    /// Traffic class implied by this transaction's signed data: the class of the message
254    /// kind it carries. Sender and receiver both derive a stream's class this way, so the
255    /// class needs no field of its own on the wire.
256    pub fn class(&self) -> Result<MessageCategory> {
257        MessageKind::from_wire(&self.data).map(MessageKind::class)
258    }
259
260    /// Destination-scoped stream identity under the receiver's overlay: one sequence stream
261    /// per `(origin, destination, class)`.
262    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    /// Digest of this exact signed transaction, including its delegation and signature.
272    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    /// Deserializes the data field into a `T` instance.
278    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    /// Create new `MessagePayload`.
286    /// Need [Transaction], [MessageSigner] and [MessageRelay].
287    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    /// A locally originated payload: a fresh carrier with the full hop budget leaving along
301    /// the delivery decision `hop`, over a transaction that names `reply_via`.
302    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        // Tests also sign data that is not a `Message`; it implies no class, and its sequence
337        // comes from the Application stream.
338        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    /// The sessions in the two slots of this payload: the origin's and the current hop's.
359    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    /// Deserializes a self-contained `MessagePayload` from the Rings wire encoding: a payload
367    /// frame with both sessions inline.
368    ///
369    /// A frame that references a session is meaningful only on the link that carried it inline,
370    /// and is refused here with [`Error::DelegationReferenceUnresolved`]; a link resolves such
371    /// frames before they reach a `MessagePayload`.
372    pub fn from_wire(data: &[u8]) -> Result<Self> {
373        Self::from_wire_with_uncompressed_len(data).map(|(payload, _)| payload)
374    }
375
376    /// [`Self::from_wire`], together with the uncompressed wire frame length in bytes.
377    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    /// Serializes the `MessagePayload` into the self-contained Rings wire encoding: a payload
387    /// frame with both sessions inline, valid on any link and outside one.
388    pub fn to_wire(&self) -> Result<Bytes> {
389        WirePayload::inline(self).to_wire()
390    }
391
392    /// The uncompressed length of [`Self::to_wire`], without allocating the wire buffer. A link
393    /// may send fewer bytes (a referenced session is shorter than an inline one, and a
394    /// compressible `DhtControl` or `Storage` frame travels as `FrameKind::CompressedPayload`),
395    /// never more.
396    pub(crate) fn wire_size(&self) -> Result<usize> {
397        WirePayload::inline(self).wire_size()
398    }
399
400    /// Returns whether `local` is the relay destination of this payload.
401    pub(crate) fn is_relay_destination_for(&self, local: Did) -> bool {
402        self.relay.destination == local
403    }
404
405    /// Returns whether `local` should forward this payload to another node.
406    pub(crate) fn should_forward_from(&self, local: Did) -> bool {
407        !self.is_relay_destination_for(local)
408    }
409
410    /// Whether `relay.destination` obeys the destination binding of the carried message kind:
411    /// every message that cannot undergo `reset_destination` must keep
412    /// `relay.destination == transaction.destination`.
413    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    /// Verify both the immutable origin transaction and the current payload carrier.
424    #[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    /// Verify both the immutable origin transaction and the current payload carrier at `now_ms`.
430    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    /// [`Self::verify_transaction_and_payload_at`] with each slot's delegator authorization treated
439    /// as `authorization` says: the origin slot's for the transaction, the hop slot's for the
440    /// carrier.
441    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/// Trait of PayloadSender
491#[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    /// The authority that signs every payload this sender emits.
495    fn message_signer(&self) -> MessageSigner<DelegateeKey>;
496
497    /// Get access to DHT.
498    fn dht(&self) -> Arc<PeerRing>;
499
500    /// Whether `did` is a directly linked peer.
501    fn is_connected(&self, did: Did) -> bool;
502
503    /// Persistently reserve sender sequences of `class` for one final destination before
504    /// signing. Each class has its own stream, because only a class lane preserves order.
505    async fn reserve_transaction_sequences(
506        &self,
507        destination: Did,
508        class: MessageCategory,
509        count: NonZeroU64,
510    ) -> Result<std::ops::RangeInclusive<u64>>;
511
512    /// Send a message payload to a specified DID.
513    async fn do_send_payload(&self, did: Did, payload: MessagePayload) -> Result<()>;
514
515    /// The delivery decision at this node for a payload addressed to the node `destination`
516    /// whose carrier is in `stage`: [`delivery_step`](crate::dht::delivery::delivery_step) over
517    /// this node's view and direct links. No hop passes its aim except by one marked handoff,
518    /// and a route that cannot continue ends here with
519    /// [`Error::RelayDestinationUnreachable`] instead of spending its hop budget.
520    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    /// Build a locally originated payload for `destination`: with [`Self::originate_through`],
527    /// which it ends in, the only constructor of a transaction this node authors, other than a
528    /// reply to a received request ([`Self::send_reply`], which authors both a report and a
529    /// connect-signaling reply).
530    ///
531    /// The first hop is `next_hop` when the caller fixed it, otherwise the delivery decision;
532    /// the transaction names this node's [`reply_via`](crate::dht::delivery::reply_via). When
533    /// the hop is decided here, both come from one topology snapshot
534    /// ([`origination`](crate::dht::delivery::origination)), as they do for a rerouted
535    /// placement, which decides its hop itself and calls [`Self::originate_through`]. Every
536    /// locally originated payload passes through one of the two, so the law "a node without a
537    /// predecessor names its nearest linked successor" holds for all of them. That includes a
538    /// manually signalled connection answer, which names the hint harmlessly: no report is ever
539    /// sent for it, and its only reader is the peer it is sent to.
540    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    /// Build a locally originated payload for `destination` through the decided first `hop`,
566    /// naming `reply_via`, after durably reserving its stream sequence: [`Self::originate`]
567    /// once the hop is decided.
568    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    /// Durably reserve the next sender sequence of `msg`'s class toward `destination`: the one
588    /// sequence a transaction this node signs for `msg` carries.
589    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    /// Alias for `do_send_payload` that sets the next hop to `payload.relay.next_hop`.
598    async fn send_payload(&self, payload: MessagePayload) -> Result<()> {
599        self.do_send_payload(payload.relay.next_hop, payload).await
600    }
601
602    /// Send a message to a specified destination by specified next hop.
603    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    /// Send a message to a specified destination.
616    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    /// Send a direct message to a specified destination.
624    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    /// Send the report `msg` for the request carried by `payload`: a fresh payload routed to
630    /// the request's origin under the same transaction id.
631    ///
632    /// A successor answer (`FindSuccessorReport`) starts in stage `(via reply_via, ⊥)` when
633    /// the signed request names one; every other report routes straight toward the origin, so
634    /// a request can reflect at most one bounded report toward the peer it names. The first
635    /// stage depends on the signed request alone, never on the request's carrier. Connect
636    /// signaling replies do not come here: they retrace the request's recorded path (#947).
637    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    /// Send `msg` back to the origin of `request` under the fresh carrier `relay`, as a
650    /// transaction `tx_id` this node signs: the common tail of every reply.
651    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    /// Forward a payload message by relay.
667    /// It just create a new payload, cloned data, resigned with session and send
668    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    /// Forward a payload one hop on toward its relay destination.
675    ///
676    /// Connect signaling retracing a recorded path takes the path's return hop, which must be
677    /// linked here (#947); no other message consults a path. Otherwise, with `next_hop = None`
678    /// the hop is the delivery decision for the carrier's stage (see [`Self::next_hop_toward`]).
679    /// A fixed `next_hop` is taken as given, as the owner-lookup protocols choose it from
680    /// `find_successor`, unless the destination is directly linked; the stage is then carried
681    /// unchanged.
682    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    /// Reset the destination to a secp DID, routing via a live intermediate hop when the target
705    /// is not directly connected.
706    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;