hopr_protocol_hopr/traits.rs
1use bytes::Bytes;
2use hopr_api::types::{crypto::prelude::*, internal::prelude::*};
3use hopr_crypto_packet::prelude::*;
4
5pub use crate::{
6 errors::IncomingPacketError,
7 types::{FoundSurb, IncomingPacket, OutgoingPacket, ResolvedAcknowledgement, SurbInsertOutcome},
8};
9
10/// A trait defining the operations required to store and retrieve SURBs (Single Use Reply Blocks) and their reply
11/// openers.
12///
13/// The sending side stores the reply openers, whereas the SURBs are stored by the replying side
14/// of the communication.
15#[auto_impl::auto_impl(&, Box, Arc)]
16pub trait SurbStore {
17 /// Tries to find SURB using the given [`matcher`](SurbMatcher).
18 ///
19 /// This is used by the replying side when it is about to send a reply packet back
20 /// to the sender.
21 fn find_surb(&self, matcher: SurbMatcher) -> Option<FoundSurb>;
22
23 /// Stores the `surbs` and associates them with the given [`pseudonym`](HoprPseudonym).
24 ///
25 /// This is used by the replying side when it receives packets containing SURBs from the sender
26 /// with the given `pseudonym`.
27 ///
28 /// Returns the total number of SURBs available for that `pseudonym` including the newly inserted
29 /// ones, along with how many had to be dropped to make room. The eviction count must not be
30 /// discarded lightly: it is the only evidence that the sender is over-producing. Evictions fall on
31 /// share-less SURBs first, so an evicted SURB takes an undelivered PIX share with it only once the
32 /// buffer holds nothing but share-bearing ones; [`SurbInsertOutcome::evicted_shares`] is the exact
33 /// number of shares lost that way. SURBs that a change of SURB generation took out of play (the
34 /// stock a newer generation cleared, or an older-generation batch that was refused) are not
35 /// evictions; they are reported apart, as [`SurbInsertOutcome::superseded`].
36 fn insert_surbs(&self, pseudonym: HoprPseudonym, surbs: Vec<(HoprSurbId, HoprSurb)>) -> SurbInsertOutcome;
37
38 /// How many SURBs are held for `pseudonym` in each of the store's tiers, as `(share-bearing,
39 /// share-less)`, or `None` if the store holds no SURBs for it or does not tell its SURBs apart that
40 /// way.
41 ///
42 /// For observability only (it feeds a trace line), so it may take a lock and need not be cheap.
43 /// The two numbers add up to [`SurbInsertOutcome::retained`] as of the last insert, unless a pop
44 /// or another insert got in between.
45 ///
46 /// Defaults to `None`, for stores that keep no such tiers.
47 fn tier_lens(&self, _pseudonym: &HoprPseudonym) -> Option<(usize, usize)> {
48 None
49 }
50
51 /// Stores the given [`opener`](ReplyOpener) for the given [`sender_id`](HoprSenderId).
52 ///
53 /// This is done by the sending side, when it creates a packet containing a SURB to be delivered
54 /// to the replying side.
55 ///
56 /// The operation should happen reasonably fast, as it is called from the packet processing code.
57 fn insert_reply_opener(&self, sender_id: HoprSenderId, opener: ReplyOpener);
58
59 /// Tries to find a [`ReplyOpener`] given the [`sender_id`](HoprSenderId), without consuming it.
60 ///
61 /// This is done by the sending side of the original packet when the reply to that packet is received and needs
62 /// to be decrypted. It is the read half of a check-then-use pair: the decoder peeks to decrypt the reply, and
63 /// [removes](SurbStore::remove_reply_opener) the opener only once the packet has been delivered. Consuming it
64 /// at lookup time instead would lose the reply when two copies of it are decoded concurrently - the copy that
65 /// loses the race would remove the opener and then fail, taking the winner's decryption key with it.
66 ///
67 /// The operation should happen reasonably fast, as it is called from the packet processing code.
68 fn find_reply_opener(&self, sender_id: &HoprSenderId) -> Option<ReplyOpener>;
69
70 /// Removes a [`ReplyOpener`] that has been used to deliver a reply.
71 ///
72 /// Called after the reply decrypted with this opener has been delivered, so a reply is only ever spent once it
73 /// has actually produced a packet. Removing an opener that is already gone is a no-op, which is what makes the
74 /// concurrent case safe: the two copies both decrypt, and only one removal is meaningful.
75 fn remove_reply_opener(&self, sender_id: &HoprSenderId);
76
77 /// Marks the edge from this node to `relayer` as unusable, so stored SURBs whose return path
78 /// starts there are no longer handed out.
79 ///
80 /// Used by the replying side once the payment channel towards `relayer` is closing or closed:
81 /// replying over it would only burn the SURB. SURBs with a direct return path are unaffected —
82 /// their first relayer is the final recipient and needs no channel.
83 ///
84 /// Defaults to a no-op, for stores that do not track edge validity.
85 fn invalidate_relayer(&self, _relayer: &HoprKeyIdent) {}
86
87 /// Reverts [`SurbStore::invalidate_relayer`] once the channel towards `relayer` re-opens.
88 ///
89 /// Defaults to a no-op, for stores that do not track edge validity.
90 fn revalidate_relayer(&self, _relayer: &HoprKeyIdent) {}
91
92 /// Current SURB-batch generation to stamp into SURBs minted for `pseudonym`.
93 ///
94 /// Used by the sending side at mint time. The value is written into every SURB of the batch so
95 /// the replying side can tell SURBs for the current return path from ones left over after a
96 /// return-path change (see [`SurbStore::bump_generation`]).
97 ///
98 /// Defaults to `0`, for stores that do not track generations.
99 fn current_generation(&self, _pseudonym: &HoprPseudonym) -> u8 {
100 0
101 }
102
103 /// Advances the SURB-batch generation for `pseudonym` and returns the new value.
104 ///
105 /// Called by the sending side when it changes the return path for a session (a re-plan): the
106 /// next batch it mints will carry the advanced generation, and the replying side drops the SURBs
107 /// it still holds for the superseded path. A `u8` serial (RFC-1982) is sufficient because only
108 /// two adjacent generations are ever in flight.
109 ///
110 /// Defaults to a no-op returning `0`, for stores that do not track generations.
111 fn bump_generation(&self, _pseudonym: &HoprPseudonym) -> u8 {
112 0
113 }
114
115 /// Admits `pseudonym` into the store's trusted class, behind an established Session, and returns
116 /// the raw number naming this admission.
117 ///
118 /// Until this is called, SURBs arriving for `pseudonym` are held in the store's untrusted class
119 /// (if it has one): tightly capped and short-lived, because the pseudonym a packet names is chosen
120 /// by its sender and no ticket on the receiving path binds it to a Session. Admission is what lifts
121 /// that cap, so it belongs to the Session lifecycle — never to a mere packet's arrival.
122 ///
123 /// `expected_surbs` is the Session's announced SURB target; the store sizes the admitted ring from
124 /// it and owns the headroom math. It may be `0` when no target was announced, which the store
125 /// treats as "unknown", not as "one SURB".
126 ///
127 /// An implementation that admits must never return `0`: that value is reserved for "no admission"
128 /// — the session side's `AdmissionToken::NONE` — and a [`retire`](SurbStore::retire) presenting it
129 /// must match nothing, so a store that minted it would let every teardown of a never-committed
130 /// Session release a live admission. Returning `0` from a store that does not admit is how the
131 /// default below honours the rule.
132 ///
133 /// Calling this twice for the same `pseudonym` must not discard what it already holds, and
134 /// invalidates the number the earlier admission returned.
135 ///
136 /// Defaults to a no-op, for stores that do not separate a trusted class.
137 fn admit(&self, _pseudonym: &HoprPseudonym, _expected_surbs: usize) -> u64 {
138 0
139 }
140
141 /// Retires `pseudonym` from the store's trusted class, on behalf of the admission `token` names.
142 ///
143 /// The counterpart of [`SurbStore::admit`], called on every teardown path. It must be idempotent —
144 /// retiring a pseudonym that was never admitted is a no-op — and must not touch any SURBs the
145 /// pseudonym still holds in the untrusted class, which expire there on their own short lifetime.
146 ///
147 /// `token` names the admission the teardown is retiring. A teardown may run its retire some time
148 /// after it closes the Session — the closing Session's own return-routed notification still needs
149 /// its ring while the packet pipeline resolves the route — so the store must treat a `token` that
150 /// no longer matches `pseudonym`'s current admission as a no-op: a successor Session was admitted
151 /// on the same pseudonym in the meantime, and its ring is not this retire's to release.
152 ///
153 /// Defaults to a no-op, for stores that do not separate a trusted class.
154 fn retire(&self, _pseudonym: &HoprPseudonym, _token: u64) {}
155
156 /// Total SURBs the store currently holds, across all classes.
157 ///
158 /// For tests and observability only; not a hot path and not required to be cheap. Defaults to `0`,
159 /// for stores that do not account for it.
160 fn surbs_held(&self) -> usize {
161 0
162 }
163}
164
165/// Trait defining encoder for [outgoing HOPR packets](OutgoingPacket).
166///
167/// These operations are done directly by the packet processing pipeline before
168/// the outgoing packet is handled to the underlying p2p transport.
169#[auto_impl::auto_impl(&, Box, Arc)]
170pub trait PacketEncoder {
171 type Error: std::error::Error + Send + Sync + 'static;
172
173 /// Encodes the given `data` and [`signals`](PacketSignals) for sending.
174 ///
175 /// The `data` MUST be already correctly sized for HOPR packets, otherwise the operation
176 /// must fail.
177 ///
178 /// `generation` is the SURB-batch generation to stamp onto SURBs minted for a forward packet's
179 /// return paths, captured when those return paths were resolved (see
180 /// [`PathPlanner::resolve_routing`](../../../hopr_transport/path/planner)). It must be captured
181 /// with the plan rather than read here, so a concurrent return-path re-plan cannot label an
182 /// already-chosen batch with a newer generation. `None` (no return path, or a non-forward
183 /// packet) falls back to the store's current generation.
184 fn encode_packet<T: AsRef<[u8]> + Send + 'static, S: Into<PacketSignals> + Send + 'static>(
185 &self,
186 data: T,
187 routing: ResolvedTransportRouting<HoprSurb>,
188 signals: S,
189 generation: Option<u8>,
190 ) -> Result<OutgoingPacket, Self::Error>;
191
192 /// Encodes the given vector of [`VerifiedAcknowledgements`](VerifiedAcknowledgement) as an outgoing packet to be
193 /// sent to the given [`destination`](OffchainPublicKey).
194 fn encode_acknowledgements(
195 &self,
196 acks: &[VerifiedAcknowledgement],
197 destination: &OffchainPublicKey,
198 ) -> Result<OutgoingPacket, Self::Error>;
199}
200
201/// Trait defining decoder HOPR packets.
202///
203/// This operation is done directly by the packet processing pipeline after
204/// the underlying p2p transport hands over incoming data packets.
205#[auto_impl::auto_impl(&, Box, Arc)]
206pub trait PacketDecoder {
207 type Error: std::error::Error + Send + Sync + 'static;
208
209 /// Decodes the `data` received from the given [`sender`](PeerId)
210 /// returns the corresponding [`IncomingPacket`] if the decoding into a HOPR packet was successful.
211 fn decode(&self, sender: PeerId, data: Bytes) -> Result<IncomingPacket, IncomingPacketError<Self::Error>>;
212}
213
214/// Defines errors returned by `UnacknowledgedTicketProcessor::acknowledge_ticket`.
215#[derive(Debug, thiserror::Error)]
216pub enum TicketAcknowledgementError<E> {
217 /// An acknowledgement from a peer was not expected.
218 #[error("acknowledgement from the peer was not expected")]
219 UnexpectedAcknowledgement,
220 /// An error occurred while processing the acknowledgement.
221 #[error(transparent)]
222 Inner(E),
223}
224
225impl<E> TicketAcknowledgementError<E> {
226 pub fn inner<F: Into<E>>(e: F) -> Self {
227 Self::Inner(e.into())
228 }
229}
230
231/// Performs necessary processing of unacknowledged tickets in the HOPR packet processing pipeline.
232#[auto_impl::auto_impl(&, Box, Arc)]
233pub trait UnacknowledgedTicketProcessor {
234 type Error: std::error::Error + Send + Sync + 'static;
235
236 /// Inserts a verified unacknowledged ticket from a delivered packet into the internal storage.
237 ///
238 /// The [`ticket`](UnacknowledgedTicket) corresponds to the given [`challenge`](HalfKeyChallenge)
239 /// and awaits to be [acknowledged](UnacknowledgedTicketProcessor::acknowledge_tickets)
240 /// once an [`Acknowledgement`] is received from the `next_hop`.
241 ///
242 /// Duplicates are detected per (issuer -> this node channel, epoch, index): `Err` is returned if
243 /// a ticket with the same index was already accepted on that channel and epoch (an attacker must
244 /// not be able to have many tickets accepted on the same index, since only one of them would
245 /// ever be redeemable). Implementations may bound how long an accepted index is remembered (the
246 /// HOPR implementation forgets it after `unack_ticket_timeout` or once its capacity is exceeded),
247 /// after which the same index is accepted again.
248 ///
249 /// This operation should be reasonably fast and should not block the main processing pipeline.
250 fn insert_unacknowledged_ticket(
251 &self,
252 next_hop: &OffchainPublicKey,
253 challenge: HalfKeyChallenge,
254 ticket: UnacknowledgedTicket,
255 ) -> Result<(), Self::Error>;
256
257 /// Returns `true` if the given [`Self::Error`] was produced by a duplicate ticket index
258 /// rejection ([`insert_unacknowledged_ticket`](Self::insert_unacknowledged_ticket) refusing a
259 /// ticket whose index was already accepted on the same channel and epoch).
260 ///
261 /// Used by the processing pipeline to give such rejections their own rejection metric label.
262 /// This method has no default so every processor must state explicitly whether its error type
263 /// can carry this rejection.
264 fn is_duplicate_ticket_index_error(error: &Self::Error) -> bool;
265
266 /// Finds and acknowledges previously inserted tickets, using incoming [`Acknowledgements`](Acknowledgement) from
267 /// the upstream [`peer`](OffchainPublicKey).
268 ///
269 /// Function should first check if any acknowledgements are expected from the given `peer`.
270 ///
271 /// Furthermore, the function must verify each given acknowledgement and find if it evaluates to any solutions
272 /// to challenges of previously [inserted tickets](UnacknowledgedTicketProcessor::insert_unacknowledged_ticket).
273 ///
274 /// On success, the [resolutions](ResolvedAcknowledgement) contain decisions whether the previously
275 /// stored ticket with a matching challenge was found, and whether it is winning (and thus also redeemable) or
276 /// losing.
277 /// Challenges for which tickets were not found are skipped.
278 ///
279 /// Must return [`TicketAcknowledgementError::UnexpectedAcknowledgement`] if no `Acknowledgements` from the given
280 /// `peer` was expected.
281 ///
282 /// This operation is expected to be somewhat long-running and significantly blocking.
283 fn acknowledge_tickets(
284 &self,
285 peer: OffchainPublicKey,
286 acks: Vec<Acknowledgement>,
287 ) -> Result<Vec<ResolvedAcknowledgement>, TicketAcknowledgementError<Self::Error>>;
288}