hopr_protocol_hopr/types.rs
1use bytes::Bytes;
2use hopr_api::types::{crypto::prelude::*, internal::prelude::*};
3use hopr_crypto_packet::prelude::*;
4use hopr_protocol_pix::TaggedEncryptedPartialSsaShare;
5
6/// Packet that is being sent out by us.
7pub struct OutgoingPacket {
8 /// Offchain public key of the next hop.
9 pub next_hop: OffchainPublicKey,
10 /// Challenge to be solved from the acknowledgement of the next hop.
11 pub ack_challenge: HalfKeyChallenge,
12 /// Optional encrypted partial SSA share for PIX protocol.
13 pub encrypted_pix_share: Option<TaggedEncryptedPartialSsaShare<HoprPixSpec>>,
14 /// Encoded HOPR packet.
15 pub data: Bytes,
16 /// SURBs minted onto this packet, in the order of the return paths that produced them.
17 ///
18 /// Surfaced so a layer above can pair each SURB with the return path it encodes — the ids exist
19 /// only inside packet construction, and the routing that produced them only outside it, so this
20 /// is the single point where the two can be associated. Empty for packets carrying no SURBs.
21 pub minted_surbs: Vec<HoprSurbId>,
22}
23
24impl std::fmt::Debug for OutgoingPacket {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 f.debug_struct("OutgoingPacket")
27 .field("next_hop", &self.next_hop)
28 .field("ack_challenge", &self.ack_challenge)
29 .field("encrypted_pix_share", &self.encrypted_pix_share)
30 .finish_non_exhaustive()
31 }
32}
33
34/// Contains some miscellaneous information about a received packet.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
36pub struct AuxiliaryPacketInfo {
37 /// Packet signals that the packet carried.
38 ///
39 /// Zero if no signal flags were specified.
40 pub packet_signals: PacketSignals,
41 /// Number of SURBs that the packet carried.
42 pub num_surbs: usize,
43 /// How many SURBs the store lost on arrival: the ones that left it, or never entered it, because
44 /// the per-pseudonym buffer was already full ([`SurbInsertOutcome::evicted`], a share-less newcomer
45 /// the store turned away included), plus the ones a newer SURB generation wiped or an older one
46 /// refused ([`SurbInsertOutcome::superseded`]). The batch the packet itself carries is counted in
47 /// `num_surbs`, so a refused older-generation batch shows up here as its own size.
48 ///
49 /// This is the only point at which an overflow is visible per packet. The store gives up
50 /// share-less SURBs first, and refuses a share-less newcomer before it evicts a share-bearing
51 /// SURB, so what an eviction costs depends on what the buffer holds. A share-less SURB is only a
52 /// lost return path. A share-bearing one carries a partial SSA share that reaches the
53 /// reconstructor only when the SURB is *used*, so evicting it destroys the share. That only
54 /// happens once the buffer holds nothing but shares, which makes this count an upper bound on the
55 /// shares lost. The exact figure is [`SurbInsertOutcome::evicted_shares`]. It is deliberately not
56 /// carried here: it is the store's own business, reported in its eviction summary (the
57 /// `ring_share` value of the `cache` label of `hopr_surb_store_evictions_count`, and a warning per
58 /// report interval). The redundancy budget that absorbs those losses is a fixed surplus per
59 /// polynomial, and emission is windowed, so on deployed dimensions a burst of roughly
60 /// `surplus × SHARE_EMISSION_WINDOW` evicted share-bearing SURBs (40 448 at the deployed 79 surplus
61 /// shares and a window of 512) is enough to put polynomials below their threshold — and a cycle
62 /// short of recovery is worth nothing at all. See
63 /// [`SurbStoreConfig::rb_capacity`](crate::SurbStoreConfig::rb_capacity) and
64 /// `hopr_protocol_pix::SHARE_EMISSION_WINDOW`.
65 ///
66 /// The Exit's Session books this count into its SURB flow estimate — an evicted SURB has left the
67 /// buffer just as a spent one has — so the meaning above must not change: it is the total of
68 /// SURBs that left or never entered the store, not the number of lost shares. The superseded
69 /// ones belong in it for the same reason: after the Entry advances the SURB generation, the Exit's
70 /// stock is gone, and the keep-alive that reports its level must say so, or the Entry would read
71 /// the pre-wipe level back and never refill. See `counterparty_buffer_capacity` in
72 /// `hopr-transport-session`.
73 pub num_evicted_surbs: usize,
74 /// Fewest intermediate hops on the return path of any SURB the packet carried, or `None` if it
75 /// carried none.
76 ///
77 /// Read off each SURB's Proof-of-Relay chain length (`hops + 1`), the same value the reply
78 /// ticket is priced by, so it is the SURB creator's word rather than something this node checked.
79 /// `Some(0)` means at least one SURB routes the reply straight back to its creator, with no first
80 /// relayer to acknowledge it — and that acknowledgement is what a PIX share is decrypted with.
81 pub min_return_path_hops: Option<u8>,
82}
83
84/// An incoming packet with a payload intended for us.
85pub struct IncomingFinalPacket {
86 /// Packet tag.
87 pub packet_tag: PacketTag,
88 /// Offchain public key of the previous hop.
89 pub previous_hop: OffchainPublicKey,
90 /// Sender pseudonym.
91 pub sender: HoprPseudonym,
92 /// SURB this packet was a reply on, when it was one.
93 ///
94 /// `None` for a packet that was not sent using one of our SURBs. Surfaced because decoding
95 /// already resolves the sender id to find the reply opener, so the id is known here and
96 /// nowhere later.
97 pub replied_on_surb: Option<HoprSurbId>,
98 /// Plain text payload of the packet.
99 pub plain_text: Bytes,
100 /// Acknowledgement to be sent to the previous hop.
101 pub ack_key: HalfKey,
102 /// Miscellaneous information about the packet.
103 pub info: AuxiliaryPacketInfo,
104}
105
106impl std::fmt::Debug for IncomingFinalPacket {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.debug_struct("IncomingFinalPacket")
109 .field("packet_tag", &self.packet_tag)
110 .field("previous_hop", &self.previous_hop)
111 .field("sender", &self.sender)
112 .field("ack_key", &self.ack_key)
113 .field("info", &self.info)
114 .finish_non_exhaustive()
115 }
116}
117
118/// Incoming packet that must be forwarded.
119pub struct IncomingForwardedPacket {
120 /// Packet tag.
121 pub packet_tag: PacketTag,
122 /// Offchain public key of the previous hop.
123 pub previous_hop: OffchainPublicKey,
124 /// Offchain public key of the next hop.
125 pub next_hop: OffchainPublicKey,
126 /// Data to be forwarded to the next hop.
127 pub data: Bytes,
128 /// Challenge to be solved from the acknowledgement received from the next hop.
129 pub ack_challenge: HalfKeyChallenge,
130 /// Ticket to be acknowledged by solving the `ack_challenge`.
131 pub received_ticket: UnacknowledgedTicket,
132 /// Acknowledgement payload to be sent to the previous hop
133 pub ack_key_prev_hop: HalfKey,
134}
135
136impl std::fmt::Debug for IncomingForwardedPacket {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 f.debug_struct("IncomingForwardedPacket")
139 .field("packet_tag", &self.packet_tag)
140 .field("previous_hop", &self.previous_hop)
141 .field("next_hop", &self.next_hop)
142 .field("received_ticket", &self.received_ticket)
143 .field("ack_challenge", &self.ack_challenge)
144 .field("ack_key_prev_hop", &self.ack_key_prev_hop)
145 .finish_non_exhaustive()
146 }
147}
148
149/// Incoming packet that contains acknowledgements of delivered packets.
150pub struct IncomingAcknowledgementPacket {
151 /// Packet tag.
152 pub packet_tag: PacketTag,
153 /// Offchain public key of the previous hop which sent the acknowledgements.
154 pub previous_hop: OffchainPublicKey,
155 /// Unverified acknowledgements.
156 pub received_acks: Vec<Acknowledgement>,
157}
158
159impl std::fmt::Debug for IncomingAcknowledgementPacket {
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 f.debug_struct("IncomingAcknowledgementPacket")
162 .field("packet_tag", &self.packet_tag)
163 .field("previous_hop", &self.previous_hop)
164 .field("received_acks", &self.received_acks)
165 .finish()
166 }
167}
168
169/// Incoming HOPR packet.
170#[derive(Debug, strum::EnumTryAs)]
171pub enum IncomingPacket {
172 /// Packet is intended for us
173 Final(Box<IncomingFinalPacket>),
174 /// Packet must be forwarded
175 Forwarded(Box<IncomingForwardedPacket>),
176 /// The packet contains acknowledgements of delivered packets.
177 Acknowledgement(Box<IncomingAcknowledgementPacket>),
178}
179
180impl IncomingPacket {
181 /// Tag identifying the packet.
182 pub fn packet_tag(&self) -> &PacketTag {
183 match self {
184 IncomingPacket::Final(f) => &f.packet_tag,
185 IncomingPacket::Forwarded(f) => &f.packet_tag,
186 IncomingPacket::Acknowledgement(f) => &f.packet_tag,
187 }
188 }
189
190 /// Previous hop that sent us the packet.
191 pub fn previous_hop(&self) -> &OffchainPublicKey {
192 match self {
193 IncomingPacket::Final(f) => &f.previous_hop,
194 IncomingPacket::Forwarded(f) => &f.previous_hop,
195 IncomingPacket::Acknowledgement(f) => &f.previous_hop,
196 }
197 }
198}
199
200/// Contains a SURB found in the SURB ring buffer via `SurbStore::find_surb`.
201#[derive(Debug)]
202pub struct FoundSurb {
203 /// Complete sender ID of the SURB.
204 pub sender_id: HoprSenderId,
205 /// The SURB itself.
206 pub surb: HoprSurb,
207 /// Number of SURBs remaining in the ring buffer with the same pseudonym.
208 pub remaining: usize,
209}
210
211/// What storing SURBs via `SurbStore::insert_surbs` did to the ring buffer.
212///
213/// The `evicted` count exists because an overflow is otherwise entirely silent: the buffer drops a
214/// SURB to make room — a share-less one whenever there is one to drop — and the caller sees only that
215/// the insert "succeeded". That count is the only local evidence that the sender is producing faster
216/// than this side can hold. It does not say what the overflow cost, though. Under PIX a share reaches
217/// the reconstructor only when its SURB is *used*, so an evicted share-bearing SURB takes its share
218/// with it permanently, whereas a share-less one is only a lost return path. `evicted_shares` is the
219/// exact number of shares lost to overflow, which is what tells routine share-less churn from a loss
220/// that matters.
221///
222/// The `superseded` count is the other way SURBs leave the buffer: not capacity pressure, but a
223/// change of SURB generation. It is kept apart from `evicted` so that the eviction summary and the
224/// overflow log stay a statement about capacity, while a caller that must know what the store really
225/// holds (the Exit's flow estimate) can add the two.
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
227pub struct SurbInsertOutcome {
228 /// Number of SURBs held for the pseudonym after the insert.
229 pub retained: usize,
230 /// Number of SURBs that left, or never entered, the buffer to make room during this insert:
231 /// share-less ones first, oldest first, and the oldest share-bearing one only once none remain. A
232 /// share-less SURB turned away because the buffer held nothing but shares counts as well.
233 pub evicted: usize,
234 /// Of [`evicted`](Self::evicted), how many carried a PIX share: the exact number of shares this
235 /// insert lost to overflow, each of them for good. It is zero for as long as the buffer still has
236 /// share-less SURBs to give up, and for every refused share-less newcomer.
237 ///
238 /// `evicted - evicted_shares` is the number of share-less SURBs dropped or refused, which cost a
239 /// return path and nothing more.
240 pub evicted_shares: usize,
241 /// Number of SURBs the generation rule took out of play during this insert, which is not capacity
242 /// pressure and so is not part of [`evicted`](Self::evicted):
243 /// - on a **newer** generation, everything the buffer held (both tiers), cleared before the batch went in;
244 /// - on an **older** generation, the batch itself, refused as a late or reordered leftover.
245 ///
246 /// The Entry advances the generation when a relayer is judged dead, precisely so that the Exit
247 /// stops spending the SURBs it holds. Those SURBs are gone from the Exit's buffer all the same, and
248 /// the Exit's flow estimate has to say so.
249 pub superseded: usize,
250}
251
252/// Determines the result of how an acknowledgement was resolved.
253#[derive(Debug, strum::EnumTryAs)]
254pub enum ResolvedAcknowledgement {
255 /// The acknowledgement resulted in a winning ticket.
256 RelayingWin(Box<RedeemableTicket>),
257 /// The acknowledgement resulted in a losing ticket.
258 RelayingLoss(ChannelId),
259}