Skip to main content

dlms_cosem_kit/xdlms/
gbt.rs

1//! General block transfer.
2//!
3//! GBT moves an APDU that does not fit the negotiated maximum size, in either
4//! direction, independently of which service it carries. The procedure was rewritten in
5//! Green Book edition 9 with an explicit window, a streaming sub-procedure and a retry
6//! sub-procedure; this is that version.
7//!
8//! The block control byte packs three things: the last-block flag, the streaming flag,
9//! and a six-bit window size. A window of zero is not "no window" — it is the value a
10//! sender uses when it is not streaming, and treating it as a window of one is how a
11//! streaming peer ends up waiting forever for an acknowledgement that is not coming.
12//!
13//! # How the window and streaming fields are read — derived
14//!
15//! The Green Book excerpt on disk does not print the GBT clauses, so this reading rests on
16//! the crate's reading of the Ed 9 procedure and on one second implementation (Gurux,
17//! which writes its own window setting into every block it emits, acknowledgements
18//! included). It is labelled derived for that reason:
19//!
20//! * the **window** field announces the *sender's own receive window* — how many blocks
21//!   it can take before it must acknowledge;
22//! * the **streaming** bit says *more blocks of this window follow without an
23//!   acknowledgement*. The block that clears it — or carries the last-block flag — is the
24//!   one the receiver answers.
25//!
26//! The second rule is chosen because it cannot deadlock whichever way a peer reads the
27//! first: a receiver acknowledges on the block the sender marks, and also when its own
28//! window fills, so a sender that ignores the bit cannot overrun it either.
29
30use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, SliceWriter, Writer};
31
32/// The block control byte.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub struct BlockControl(pub u8);
35
36impl BlockControl {
37    /// A control byte.
38    #[must_use]
39    pub const fn new(last_block: bool, streaming: bool, window: u8) -> Self {
40        let mut v = window & 0x3F;
41        if last_block {
42            v |= 0x80;
43        }
44        if streaming {
45            v |= 0x40;
46        }
47        Self(v)
48    }
49
50    /// True when no further block follows.
51    #[must_use]
52    pub const fn last_block(self) -> bool {
53        self.0 & 0x80 != 0
54    }
55
56    /// True when the sender is streaming: it will send a whole window without waiting.
57    #[must_use]
58    pub const fn streaming(self) -> bool {
59        self.0 & 0x40 != 0
60    }
61
62    /// How many blocks the sender will send before it expects an acknowledgement.
63    #[must_use]
64    pub const fn window(self) -> u8 {
65        self.0 & 0x3F
66    }
67}
68
69/// One block of a general block transfer.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct GeneralBlockTransfer<'a> {
72    /// Last-block flag, streaming flag and window size.
73    pub control: BlockControl,
74    /// This block's number, counting from one.
75    pub block_number: u16,
76    /// The highest block number the sender has received from the peer.
77    pub block_number_ack: u16,
78    /// The fragment of the carried APDU.
79    pub block_data: &'a [u8],
80}
81
82impl GeneralBlockTransfer<'_> {
83    /// An acknowledgement carrying no data, used to open the next window.
84    #[must_use]
85    pub const fn ack(block_number_ack: u16, window: u8) -> Self {
86        Self {
87            control: BlockControl::new(false, false, window),
88            block_number: 0,
89            block_number_ack,
90            block_data: &[],
91        }
92    }
93}
94
95impl Encode for GeneralBlockTransfer<'_> {
96    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
97        w.write_u8(self.control.0)?;
98        w.write_u16(self.block_number)?;
99        w.write_u16(self.block_number_ack)?;
100        w.write_length_prefixed(self.block_data)
101    }
102}
103
104impl<'a> Decode<'a> for GeneralBlockTransfer<'a> {
105    fn decode(r: &mut Reader<'a>) -> Result<Self> {
106        Ok(Self {
107            control: BlockControl(r.u8()?),
108            block_number: r.u16()?,
109            block_number_ack: r.u16()?,
110            block_data: r.length_prefixed()?,
111        })
112    }
113}
114
115/// The largest window a sender will use, which is what the six-bit field can carry.
116pub const GBT_WINDOW_MAX: u8 = 0x3F;
117
118/// The state of sending one APDU as GBT blocks, independent of where the APDU lives.
119///
120/// An engine cannot hold a [`GbtSender`] across calls, because the sender borrows the
121/// APDU and the APDU lives in the engine. This is the same procedure with the bytes
122/// passed in on every call, so it can be stored next to them.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct GbtSendCursor {
125    len: usize,
126    /// The number of the last block emitted. Blocks count from one.
127    block: u16,
128    /// The highest block the peer has acknowledged.
129    acked: u16,
130    /// Bytes per block. Non-zero by construction: a `div_ceil` by a plain `usize` leaves a
131    /// divide-by-zero panic path in the object code.
132    fragment: core::num::NonZeroUsize,
133    /// How many blocks may be outstanding: the peer's window, clamped to ours.
134    send_window: u8,
135    /// The window announced in our blocks: how many we can take.
136    own_window: u8,
137}
138
139impl GbtSendCursor {
140    /// A cursor over an APDU of `len` bytes, cut into blocks of at most `fragment` bytes.
141    ///
142    /// Until the peer announces a window the cursor sends one block at a time, which is
143    /// the only rate a peer that has said nothing is known to accept.
144    ///
145    /// # Errors
146    /// [`ErrorKind::InvalidLength`] when `fragment` is zero, which would never finish, or
147    /// when the APDU needs more blocks than a sixteen-bit number can name.
148    pub fn new(len: usize, fragment: usize, own_window: u8) -> Result<Self> {
149        let Some(fragment) = core::num::NonZeroUsize::new(fragment) else {
150            return Err(Error::new(ErrorKind::InvalidLength, 0));
151        };
152        if u16::try_from(len.div_ceil(fragment.get()).max(1)).is_err() {
153            return Err(Error::new(ErrorKind::InvalidLength, 0));
154        }
155        let own_window = own_window.clamp(1, GBT_WINDOW_MAX);
156        Ok(Self { len, block: 0, acked: 0, fragment, send_window: 1, own_window })
157    }
158
159    /// How many bytes the APDU being sent has.
160    #[must_use]
161    pub const fn len(&self) -> usize {
162        self.len
163    }
164
165    /// True for an empty APDU, which is still sent as one (empty, last) block.
166    #[must_use]
167    pub const fn is_empty(&self) -> bool {
168        self.len == 0
169    }
170
171    /// How many blocks the whole APDU takes. An empty APDU is still one block: it has to
172    /// be sent for the peer to learn that it is the last one.
173    #[must_use]
174    pub const fn blocks(&self) -> u16 {
175        let n = self.len.div_ceil(self.fragment.get());
176        if n == 0 { 1 } else { n as u16 }
177    }
178
179    /// True once the last block has been emitted.
180    #[must_use]
181    pub const fn is_sent(&self) -> bool {
182        self.block >= self.blocks()
183    }
184
185    /// True when every block has been sent *and* acknowledged.
186    #[must_use]
187    pub const fn is_done(&self) -> bool {
188        self.acked >= self.blocks()
189    }
190
191    /// The number of the last block emitted; zero before the first.
192    #[must_use]
193    pub const fn block(&self) -> u16 {
194        self.block
195    }
196
197    /// The highest block the peer has acknowledged.
198    #[must_use]
199    pub const fn acknowledged(&self) -> u16 {
200        self.acked
201    }
202
203    /// Let `window` blocks be outstanding at once, as a peer that announced it would.
204    /// Clamped to `1..=` [`GBT_WINDOW_MAX`].
205    pub fn set_send_window(&mut self, window: u8) {
206        self.send_window = window.clamp(1, GBT_WINDOW_MAX);
207    }
208
209    /// Emit the next block of `apdu`, or `None` when the window is full and an
210    /// acknowledgement is owed first, or when every block has gone.
211    ///
212    /// `ack_of_peer` is what this end has received of the peer's own blocks — zero for a
213    /// sender that is not also receiving.
214    ///
215    /// # Errors
216    /// When `apdu` is not the length the cursor was made for, or `out` is too small.
217    pub fn next_block(&mut self, apdu: &[u8], ack_of_peer: u16, out: &mut [u8]) -> Result<Option<usize>> {
218        if apdu.len() != self.len {
219            return Err(Error::new(ErrorKind::InvalidLength, 0));
220        }
221        let total = self.blocks();
222        if self.block >= total {
223            return Ok(None);
224        }
225        let outstanding = self.block.saturating_sub(self.acked);
226        if outstanding >= u16::from(self.send_window) {
227            return Ok(None);
228        }
229        let number = self.block.saturating_add(1);
230        let start = usize::from(self.block).saturating_mul(self.fragment.get());
231        let end = start.saturating_add(self.fragment.get()).min(self.len);
232        let last = number == total;
233        // More of this window follows when neither the window nor the APDU ends here.
234        let window_ends = outstanding.saturating_add(1) >= u16::from(self.send_window);
235        let streaming = !last && !window_ends;
236        let frame = GeneralBlockTransfer {
237            control: BlockControl::new(last, streaming, self.own_window),
238            block_number: number,
239            block_number_ack: ack_of_peer,
240            block_data: apdu.get(start..end).unwrap_or(&[]),
241        };
242        let mut w = SliceWriter::new(out);
243        frame.encode(&mut w)?;
244        self.block = number;
245        Ok(Some(w.written()))
246    }
247
248    /// Take the peer's acknowledgement, and the window it announced with it.
249    ///
250    /// One lower than the last block sent rewinds the cursor to just after it: that is
251    /// the retry sub-procedure.
252    ///
253    /// # Errors
254    /// [`ErrorKind::UnexpectedMessage`] when the peer acknowledges a block that was never
255    /// sent, or one below what it has already acknowledged. The second bound is what keeps
256    /// the retry finite: a peer that answers every window with a lower number than the
257    /// last would leave the sender resending the same run for ever.
258    pub fn acknowledge(&mut self, block_number_ack: u16, peer_window: u8) -> Result<()> {
259        if block_number_ack > self.block || block_number_ack < self.acked {
260            return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
261        }
262        self.acked = block_number_ack;
263        self.block = block_number_ack;
264        // Zero is "not streaming": one block at a time.
265        // The peer's window, never more than this end is configured to stream, and zero
266        // ("not streaming") is one block at a time.
267        self.set_send_window(peer_window.min(self.own_window));
268        Ok(())
269    }
270}
271
272/// Splits an APDU into general block transfer blocks, and takes acknowledgements back.
273///
274/// GBT is the *other* segmentation mechanism, and it is not a substitute for the
275/// service-specific one: block transfer cuts a **value** into APDUs, GBT cuts an
276/// **APDU** into blocks, and it does so for any service — including the ones that have
277/// no blocked form of their own, which is the whole reason it exists.
278///
279/// This is [`GbtSendCursor`] borrowing its APDU, for callers that hold the bytes
280/// themselves. The engines store the cursor.
281///
282/// ```
283/// use dlms_cosem_kit::codec::Decode;
284/// use dlms_cosem_kit::xdlms::{GbtAction, GbtReceiver, GbtSender, GeneralBlockTransfer};
285///
286/// let apdu = [0xC4u8; 300];                   // a get-response, too big for the link
287/// let mut sender = GbtSender::new(&apdu, 100, 4, true)?;
288/// let mut storage = [0u8; 512];
289/// let mut receiver = GbtReceiver::new(&mut storage);
290///
291/// let mut frame = [0u8; 256];
292/// while !sender.is_done() {
293///     while let Some(n) = sender.next_block(&mut frame)? {
294///         let block = GeneralBlockTransfer::from_bytes(&frame[..n])?;
295///         if receiver.push(&block)? != GbtAction::Await {
296///             sender.acknowledge(receiver.acknowledged())?;
297///         }
298///     }
299/// }
300/// assert_eq!(receiver.apdu(), &apdu[..]);
301/// # Ok::<(), dlms_cosem_kit::Error>(())
302/// ```
303#[derive(Debug, Clone, Copy)]
304pub struct GbtSender<'a> {
305    apdu: &'a [u8],
306    cursor: GbtSendCursor,
307    window: u8,
308}
309
310impl<'a> GbtSender<'a> {
311    /// Split `apdu` into blocks of at most `fragment` bytes.
312    ///
313    /// `window` is how many blocks may be outstanding when `streaming`; it is clamped to
314    /// [`GBT_WINDOW_MAX`] and forced to one when not streaming.
315    ///
316    /// # Errors
317    /// As [`GbtSendCursor::new`].
318    pub fn new(apdu: &'a [u8], fragment: usize, window: u8, streaming: bool) -> Result<Self> {
319        let window = if streaming { window.clamp(1, GBT_WINDOW_MAX) } else { 1 };
320        let mut cursor = GbtSendCursor::new(apdu.len(), fragment, window)?;
321        cursor.set_send_window(window);
322        Ok(Self { apdu, cursor, window })
323    }
324
325    /// How many blocks the whole APDU takes.
326    #[must_use]
327    pub const fn blocks(&self) -> u16 {
328        self.cursor.blocks()
329    }
330
331    /// True when every block has been sent *and* acknowledged.
332    #[must_use]
333    pub const fn is_done(&self) -> bool {
334        self.cursor.is_done()
335    }
336
337    /// The number of the last block emitted; zero before the first.
338    #[must_use]
339    pub const fn block(&self) -> u16 {
340        self.cursor.block()
341    }
342
343    /// Emit the next block, or `None` when the window is full and an acknowledgement is
344    /// owed first.
345    ///
346    /// # Errors
347    /// When `out` is too small for the block.
348    pub fn next_block(&mut self, out: &mut [u8]) -> Result<Option<usize>> {
349        self.cursor.next_block(self.apdu, 0, out)
350    }
351
352    /// Take the peer's acknowledgement; see [`GbtSendCursor::acknowledge`].
353    ///
354    /// # Errors
355    /// As [`GbtSendCursor::acknowledge`].
356    pub fn acknowledge(&mut self, block_number_ack: u16) -> Result<()> {
357        self.cursor.acknowledge(block_number_ack, self.window)
358    }
359
360    /// Take the peer's acknowledgement together with the window it announced.
361    ///
362    /// # Errors
363    /// As [`GbtSendCursor::acknowledge`].
364    pub fn acknowledge_with_window(&mut self, block_number_ack: u16, peer_window: u8) -> Result<()> {
365        self.cursor.acknowledge(block_number_ack, peer_window)
366    }
367}
368
369/// What a [`GbtReceiver`] wants done after a block.
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub enum GbtAction {
372    /// The sender is streaming and its window is not full. Keep reading.
373    Await,
374    /// Send an acknowledgement carrying [`GbtReceiver::acknowledged`].
375    Acknowledge,
376    /// The APDU is complete; [`GbtReceiver::apdu`] has it. Acknowledge as well.
377    Complete,
378}
379
380/// The state of reassembling one APDU from GBT blocks, independent of where it lands.
381///
382/// Out-of-order and duplicate blocks are answered rather than refused, because that is
383/// what the retry sub-procedure is made of. A block ahead of the run is **not** stored:
384/// acknowledging the last one received in order is how the receiver tells the sender
385/// where to resume.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub struct GbtRecvCursor {
388    len: usize,
389    /// The highest block received in order. Blocks count from one.
390    received: u16,
391    /// How many in-order blocks have arrived since the last acknowledgement.
392    since_ack: u8,
393    own_window: u8,
394    complete: bool,
395    /// An acknowledgement asking the sender to resume after `received` has gone out and
396    /// nothing in order has arrived since.
397    ///
398    /// The rest of a window that broke keeps arriving after the gap; answering each of
399    /// those blocks with the same retry request makes the sender rewind once per block,
400    /// and the lost block crosses the link once per request.
401    retry_requested: bool,
402}
403
404impl GbtRecvCursor {
405    /// A cursor that will acknowledge at least every `own_window` blocks.
406    #[must_use]
407    pub const fn new(own_window: u8) -> Self {
408        let own_window = if own_window == 0 {
409            1
410        } else if own_window > GBT_WINDOW_MAX {
411            GBT_WINDOW_MAX
412        } else {
413            own_window
414        };
415        Self { len: 0, received: 0, since_ack: 0, own_window, complete: false, retry_requested: false }
416    }
417
418    /// Take one block into `buf`.
419    ///
420    /// `buf` must be the same buffer on every call of one transfer.
421    ///
422    /// # Errors
423    /// [`ErrorKind::BufferTooSmall`] when the APDU does not fit, before anything is
424    /// copied.
425    pub fn push(&mut self, buf: &mut [u8], block: &GeneralBlockTransfer<'_>) -> Result<GbtAction> {
426        if self.complete {
427            // The previous APDU was taken; this is the start of the next one.
428            self.reset();
429        }
430        let expected = self.received.saturating_add(1);
431        if block.block_number != expected {
432            // A duplicate the sender resent, or one from beyond a gap: say where the run
433            // actually reaches and let the sender rewind to it — once. A retry request
434            // already outstanding covers every other block of the broken window.
435            if self.retry_requested {
436                return Ok(GbtAction::Await);
437            }
438            self.retry_requested = true;
439            self.since_ack = 0;
440            return Ok(GbtAction::Acknowledge);
441        }
442        self.retry_requested = false;
443        let at = self.len;
444        let end = at.saturating_add(block.block_data.len());
445        let capacity = buf.len();
446        let slot = buf.get_mut(at..end).ok_or_else(|| {
447            Error::new(ErrorKind::BufferTooSmall { needed: end.saturating_sub(capacity) }, at)
448        })?;
449        slot.copy_from_slice(block.block_data);
450        self.len = end;
451        self.received = block.block_number;
452        self.since_ack = self.since_ack.saturating_add(1);
453
454        if block.control.last_block() {
455            self.complete = true;
456            self.since_ack = 0;
457            return Ok(GbtAction::Complete);
458        }
459        if !block.control.streaming() || self.since_ack >= self.own_window {
460            self.since_ack = 0;
461            return Ok(GbtAction::Acknowledge);
462        }
463        Ok(GbtAction::Await)
464    }
465
466    /// The block number to acknowledge: the highest received in order.
467    #[must_use]
468    pub const fn acknowledged(&self) -> u16 {
469        self.received
470    }
471
472    /// The window this receiver announces.
473    #[must_use]
474    pub const fn window(&self) -> u8 {
475        self.own_window
476    }
477
478    /// How many bytes have been gathered.
479    #[must_use]
480    pub const fn len(&self) -> usize {
481        self.len
482    }
483
484    /// True before any block has been taken.
485    #[must_use]
486    pub const fn is_empty(&self) -> bool {
487        self.len == 0
488    }
489
490    /// True once the last block has been stored.
491    #[must_use]
492    pub const fn is_complete(&self) -> bool {
493        self.complete
494    }
495
496    /// Encode the acknowledgement this receiver owes.
497    ///
498    /// # Errors
499    /// When `out` is too small.
500    pub fn acknowledgement(&self, out: &mut [u8]) -> Result<usize> {
501        let mut w = SliceWriter::new(out);
502        GeneralBlockTransfer::ack(self.received, self.own_window).encode(&mut w)?;
503        Ok(w.written())
504    }
505
506    /// Discard everything, ready for the next APDU.
507    pub const fn reset(&mut self) {
508        self.len = 0;
509        self.received = 0;
510        self.since_ack = 0;
511        self.complete = false;
512        self.retry_requested = false;
513    }
514}
515
516/// Reassembles an APDU from general block transfer blocks into a caller's buffer.
517///
518/// This is [`GbtRecvCursor`] holding its buffer, for callers that own one.
519#[derive(Debug)]
520pub struct GbtReceiver<'a> {
521    buf: &'a mut [u8],
522    cursor: GbtRecvCursor,
523}
524
525impl<'a> GbtReceiver<'a> {
526    /// A receiver filling `buf`, acknowledging at least every [`GBT_WINDOW_MAX`] blocks.
527    #[must_use]
528    pub fn new(buf: &'a mut [u8]) -> Self {
529        Self { buf, cursor: GbtRecvCursor::new(GBT_WINDOW_MAX) }
530    }
531
532    /// Take one block.
533    ///
534    /// # Errors
535    /// [`ErrorKind::BufferTooSmall`] when the APDU does not fit.
536    pub fn push(&mut self, block: &GeneralBlockTransfer<'_>) -> Result<GbtAction> {
537        self.cursor.push(self.buf, block)
538    }
539
540    /// The block number to acknowledge: the highest received in order.
541    #[must_use]
542    pub const fn acknowledged(&self) -> u16 {
543        self.cursor.acknowledged()
544    }
545
546    /// Encode the acknowledgement this receiver owes, announcing `window`.
547    ///
548    /// # Errors
549    /// When `out` is too small.
550    pub fn acknowledgement(&self, window: u8, out: &mut [u8]) -> Result<usize> {
551        let mut w = SliceWriter::new(out);
552        GeneralBlockTransfer::ack(self.cursor.acknowledged(), window).encode(&mut w)?;
553        Ok(w.written())
554    }
555
556    /// The reassembled APDU. Empty until [`GbtReceiver::push`] has returned
557    /// [`GbtAction::Complete`].
558    #[must_use]
559    pub fn apdu(&self) -> &[u8] {
560        if self.cursor.is_complete() { self.buf.get(..self.cursor.len()).unwrap_or(&[]) } else { &[] }
561    }
562
563    /// How many bytes have been gathered, complete or not.
564    #[must_use]
565    pub const fn len(&self) -> usize {
566        self.cursor.len()
567    }
568
569    /// True before any block has been taken.
570    #[must_use]
571    pub const fn is_empty(&self) -> bool {
572        self.cursor.is_empty()
573    }
574
575    /// Discard everything, ready for the next APDU.
576    pub const fn reset(&mut self) {
577        self.cursor.reset();
578    }
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584
585    #[test]
586    fn control_bits_are_independent() {
587        let c = BlockControl::new(true, false, 7);
588        assert!(c.last_block());
589        assert!(!c.streaming());
590        assert_eq!(c.window(), 7);
591        assert_eq!(c.0, 0x87);
592
593        let c = BlockControl::new(false, true, 0);
594        assert!(!c.last_block());
595        assert!(c.streaming());
596        assert_eq!(c.window(), 0, "a window of zero is a value, not an absence");
597        assert_eq!(c.0, 0x40);
598    }
599
600    #[test]
601    fn a_block_round_trips() {
602        let b = GeneralBlockTransfer {
603            control: BlockControl::new(false, true, 4),
604            block_number: 1,
605            block_number_ack: 0,
606            block_data: &[0xC4, 0x01, 0x81],
607        };
608        let mut buf = [0u8; 32];
609        let mut w = crate::codec::SliceWriter::new(&mut buf);
610        b.encode(&mut w).unwrap();
611        assert_eq!(w.as_slice(), [0x44, 0x00, 0x01, 0x00, 0x00, 0x03, 0xC4, 0x01, 0x81]);
612        assert_eq!(GeneralBlockTransfer::from_bytes(w.as_slice()).unwrap(), b);
613    }
614
615    /// The retry sub-procedure rewinds, and rewinding is bounded progress only while
616    /// acknowledgements move forward. A peer that un-acknowledges a block it already
617    /// acknowledged leaves the sender resending the same run for ever — and GBT has no
618    /// clock behind it to notice, so the loop is the failure.
619    #[test]
620    fn an_acknowledgement_that_goes_backwards_is_refused() {
621        let apdu = [0xC4u8; 300];
622        let mut sender = GbtSender::new(&apdu, 100, 4, true).unwrap();
623        let mut frame = [0u8; 256];
624        while sender.next_block(&mut frame).unwrap().is_some() {}
625        assert_eq!(sender.block(), 3);
626
627        // A block that was never sent is not something an honest receiver names.
628        assert_eq!(sender.acknowledge(4).unwrap_err().kind, ErrorKind::UnexpectedMessage);
629        // One lower than the last sent is the retry rule, and is accepted.
630        sender.acknowledge(2).unwrap();
631        assert_eq!(sender.block(), 2, "and rewinds to just after it");
632        // Going back below what is already acknowledged is not a retry.
633        assert_eq!(sender.acknowledge(1).unwrap_err().kind, ErrorKind::UnexpectedMessage);
634        assert!(sender.acknowledge(2).is_ok(), "repeating the same acknowledgement is harmless");
635    }
636
637    /// Drive a whole APDU across, one block at a time, with no streaming.
638    #[test]
639    fn an_apdu_crosses_block_by_block_and_comes_back_identical() {
640        let apdu: alloc::vec::Vec<u8> = (0..1000u32).map(|i| (i % 251) as u8).collect();
641        for fragment in [1usize, 7, 128, 999, 1000, 1001] {
642            let mut sender = GbtSender::new(&apdu, fragment, 1, false).unwrap();
643            let mut storage = [0u8; 1100];
644            let mut receiver = GbtReceiver::new(&mut storage);
645            let mut frame = [0u8; 1100];
646            let mut blocks = 0;
647            while !sender.is_done() {
648                let Some(n) = sender.next_block(&mut frame).unwrap() else {
649                    panic!("a non-streaming sender must always have a block to send");
650                };
651                blocks += 1;
652                let block = GeneralBlockTransfer::from_bytes(&frame[..n]).unwrap();
653                let action = receiver.push(&block).unwrap();
654                assert_ne!(action, GbtAction::Await, "a window of one acknowledges every block");
655                sender.acknowledge(receiver.acknowledged()).unwrap();
656            }
657            assert_eq!(blocks, sender.blocks(), "at {fragment} bytes a block");
658            assert_eq!(receiver.apdu(), &apdu[..], "at {fragment} bytes a block");
659        }
660    }
661
662    /// Streaming: the sender puts a whole window on the wire before it waits.
663    #[test]
664    fn a_streaming_sender_fills_its_window_before_waiting() {
665        let apdu = [0xAAu8; 500];
666        let mut sender = GbtSender::new(&apdu, 50, 4, true).unwrap();
667        let mut frame = [0u8; 128];
668        // Four blocks go out with nothing coming back.
669        for _ in 0..4 {
670            assert!(sender.next_block(&mut frame).unwrap().is_some());
671        }
672        assert!(
673            sender.next_block(&mut frame).unwrap().is_none(),
674            "the fifth block waits for an acknowledgement"
675        );
676        sender.acknowledge(2).unwrap();
677        // Two are now clear, so two more may go — and they are blocks 3 and 4 again,
678        // because acknowledging 2 rewound the sender.
679        let n = sender.next_block(&mut frame).unwrap().unwrap();
680        assert_eq!(GeneralBlockTransfer::from_bytes(&frame[..n]).unwrap().block_number, 3);
681    }
682
683    /// The exit criterion for GBT: a dropped block is recovered by resuming after the
684    /// last one that arrived, not by restarting the transfer.
685    #[test]
686    fn a_dropped_block_is_recovered_by_retry_rather_than_by_starting_again() {
687        let apdu: alloc::vec::Vec<u8> = (0..600u32).map(|i| (i % 251) as u8).collect();
688        let mut sender = GbtSender::new(&apdu, 100, 6, true).unwrap();
689        let mut storage = [0u8; 700];
690        let mut receiver = GbtReceiver::new(&mut storage);
691        let mut frame = [0u8; 256];
692
693        let mut emitted = 0usize;
694        let mut dropped_once = false;
695        while !sender.is_done() {
696            let Some(n) = sender.next_block(&mut frame).unwrap() else {
697                sender.acknowledge(receiver.acknowledged()).unwrap();
698                continue;
699            };
700            emitted += 1;
701            let block = GeneralBlockTransfer::from_bytes(&frame[..n]).unwrap();
702            // Lose block 3 exactly once. Everything after it arrives, and must not be
703            // stored out of order.
704            if block.block_number == 3 && !dropped_once {
705                dropped_once = true;
706                continue;
707            }
708            if receiver.push(&block).unwrap() != GbtAction::Await {
709                sender.acknowledge(receiver.acknowledged()).unwrap();
710            }
711        }
712        assert!(dropped_once);
713        assert_eq!(receiver.apdu(), &apdu[..], "the APDU is whole and in order");
714        assert!(emitted > 6, "the lost block and the ones after it were sent again");
715        assert!(emitted < 6 * 3, "and the transfer did not restart from the beginning");
716    }
717
718    /// A receiver never stores a block from beyond a gap: acknowledging where the run
719    /// really reaches is what makes the sender come back for the missing one, and
720    /// keeping the future block as well would leave a hole nothing fills.
721    #[test]
722    fn a_block_from_beyond_a_gap_is_not_stored() {
723        let mut storage = [0u8; 64];
724        let mut receiver = GbtReceiver::new(&mut storage);
725        let block = |n, last, data| GeneralBlockTransfer {
726            control: BlockControl::new(last, false, 1),
727            block_number: n,
728            block_number_ack: 0,
729            block_data: data,
730        };
731        assert_eq!(receiver.push(&block(1, false, &[1, 2])).unwrap(), GbtAction::Acknowledge);
732        // Block 2 is lost; block 3 arrives.
733        assert_eq!(receiver.push(&block(3, false, &[9, 9])).unwrap(), GbtAction::Acknowledge);
734        assert_eq!(receiver.acknowledged(), 1, "the run still only reaches block one");
735        assert_eq!(receiver.len(), 2, "and nothing from beyond the gap was kept");
736        // A duplicate of what is already held changes nothing either — and asks for no
737        // second retry, because one is already outstanding.
738        assert_eq!(receiver.push(&block(1, false, &[1, 2])).unwrap(), GbtAction::Await);
739        assert_eq!(receiver.len(), 2);
740        // The retry closes the gap.
741        assert_eq!(receiver.push(&block(2, false, &[3, 4])).unwrap(), GbtAction::Acknowledge);
742        assert_eq!(receiver.push(&block(3, true, &[5, 6])).unwrap(), GbtAction::Complete);
743        assert_eq!(receiver.apdu(), [1, 2, 3, 4, 5, 6]);
744    }
745
746    #[test]
747    fn an_acknowledgement_of_a_block_never_sent_is_refused() {
748        let apdu = [0u8; 100];
749        let mut sender = GbtSender::new(&apdu, 50, 1, false).unwrap();
750        let mut frame = [0u8; 128];
751        sender.next_block(&mut frame).unwrap();
752        assert_eq!(sender.acknowledge(7).unwrap_err().kind, ErrorKind::UnexpectedMessage);
753    }
754
755    #[test]
756    fn a_fragment_of_zero_would_never_finish() {
757        assert_eq!(GbtSender::new(&[1, 2, 3], 0, 1, false).unwrap_err().kind, ErrorKind::InvalidLength);
758    }
759
760    fn blk(n: u16, last: bool, streaming: bool, data: &[u8]) -> GeneralBlockTransfer<'_> {
761        GeneralBlockTransfer {
762            control: BlockControl::new(last, streaming, 1),
763            block_number: n,
764            block_number_ack: 0,
765            block_data: data,
766        }
767    }
768
769    /// 001-large-transfers-driver/SR-003: a duplicated block is answered, never stored twice.
770    #[test]
771    fn a_duplicated_block_is_stored_once() {
772        let mut buf = [0u8; 16];
773        let mut rx = GbtRecvCursor::new(4);
774        for (n, last) in [(1, false), (2, false), (2, false), (3, false), (4, false), (5, true)] {
775            rx.push(&mut buf, &blk(n, last, true, &[n as u8])).unwrap();
776        }
777        assert!(rx.is_complete());
778        assert_eq!(&buf[..rx.len()], [1, 2, 3, 4, 5]);
779    }
780
781    /// 001-large-transfers-driver/SR-002: a peer window is clamped to ours, and zero means
782    /// one block at a time.
783    #[test]
784    fn a_peer_window_is_clamped_and_zero_means_one() {
785        let apdu = [0u8; 1000];
786        let mut out = [0u8; 64];
787        let mut tx = GbtSendCursor::new(apdu.len(), 10, 4).unwrap();
788        assert!(tx.next_block(&apdu, 0, &mut out).unwrap().is_some());
789        assert!(tx.next_block(&apdu, 0, &mut out).unwrap().is_none(), "one block before the peer speaks");
790        tx.acknowledge(1, 63).unwrap();
791        let mut sent = 0;
792        while tx.next_block(&apdu, 0, &mut out).unwrap().is_some() {
793            sent += 1;
794        }
795        assert_eq!(sent, 4, "63 announced, 4 configured: 4 go");
796        tx.acknowledge(5, 0).unwrap();
797        assert!(tx.next_block(&apdu, 0, &mut out).unwrap().is_some());
798        assert!(tx.next_block(&apdu, 0, &mut out).unwrap().is_none(), "window 0 is one block per ack");
799    }
800
801    /// The streaming bit marks every block of a window but the one the receiver answers.
802    #[test]
803    fn streaming_is_clear_on_the_block_that_ends_a_window() {
804        let apdu = [0u8; 100];
805        let mut out = [0u8; 64];
806        let mut tx = GbtSendCursor::new(apdu.len(), 10, 3).unwrap();
807        tx.set_send_window(3);
808        let mut flags = alloc::vec::Vec::new();
809        while let Some(n) = tx.next_block(&apdu, 0, &mut out).unwrap() {
810            let b = GeneralBlockTransfer::from_bytes(&out[..n]).unwrap();
811            flags.push(b.control.streaming());
812            assert_eq!(b.control.window(), 3, "the window field is our own");
813        }
814        assert_eq!(flags, [true, true, false]);
815    }
816
817    /// 001-large-transfers-driver/SR-001: a block that would overflow is refused before it
818    /// is copied, and nothing already gathered moves.
819    #[test]
820    fn an_overflowing_block_is_refused_before_copying() {
821        let mut buf = [0u8; 4];
822        let mut rx = GbtRecvCursor::new(4);
823        rx.push(&mut buf, &blk(1, false, false, &[1, 2, 3])).unwrap();
824        let e = rx.push(&mut buf, &blk(2, true, false, &[4, 5])).unwrap_err();
825        assert!(matches!(e.kind, ErrorKind::BufferTooSmall { needed: 1 }));
826        assert_eq!(rx.len(), 3);
827        assert_eq!(buf, [1, 2, 3, 0]);
828    }
829
830    #[test]
831    fn a_receiver_acknowledges_when_its_own_window_fills_even_if_the_sender_keeps_streaming() {
832        let mut buf = [0u8; 16];
833        let mut rx = GbtRecvCursor::new(2);
834        assert_eq!(rx.push(&mut buf, &blk(1, false, true, &[1])).unwrap(), GbtAction::Await);
835        assert_eq!(rx.push(&mut buf, &blk(2, false, true, &[2])).unwrap(), GbtAction::Acknowledge);
836    }
837}