Skip to main content

ratify_protocol/v2/reference/
offline_device.rs

1//! Single-device offline profile (SPEC-v2 §7.13), TEST ONLY. Mirrors Go
2//! `v2reference/offline_device.go`.
3//!
4//! [`DeviceComponentTestOnly`] models the independent component the profile
5//! requires on one device: an independently programmed secure element or
6//! TPM-backed module with its own key. It holds the anchored complete-state
7//! digest of the primary ([`DevicePrimaryTestOnly`]), which the primary
8//! advances before every durable security-state change takes effect, and it
9//! records, for every receipt-log entry, the entry hash and the
10//! complete-state digest it acknowledged, advances monotonically, and signs
11//! each acknowledgement. Nothing here is durable or independent; it exists
12//! so the shared profile scenarios can exercise power loss, primary rollback
13//! with and without a changed receipt prefix, digest mismatch, full storage,
14//! clock regression, and offline recovery against exact semantics.
15
16use std::fmt;
17use std::sync::{Arc, Mutex, MutexGuard};
18
19use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey};
20
21use super::device_state::{DevicePrimaryTestOnly, PrimaryShared};
22use super::store::Store;
23use crate::v2::checkpoint_ack::V2CheckpointAcknowledgement;
24use crate::v2::claim_store::{V2AuthoritativeClock, V2StoreError};
25use crate::v2::context::V2Context;
26use crate::v2::errors::{V2Error, V2ErrorClass, V2Result};
27use crate::v2::release::V2ReceiptCheckpoint;
28
29/// The failures of the device component and checkpoint (Go
30/// `ErrDevicePowerLoss`, `ErrDeviceStorageFull`, `ErrDeviceStateMismatch`,
31/// `ErrDeviceFrozen`, and `ErrNotAcknowledged`), plus a store or clock
32/// failure passed through.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum DeviceErrorTestOnly {
35    /// Power was lost during a checkpoint submission. Before the component
36    /// commits nothing is recorded; after it commits, the acknowledgement is
37    /// durable but its response is lost.
38    PowerLoss,
39    /// The component has no space for another acknowledgement. It never
40    /// overwrites or wraps.
41    StorageFull,
42    /// A state anchor or submission does not extend the component's head:
43    /// the previous complete-state digest differs from the anchored one, the
44    /// previous entry hash differs, or the sequence is not the next one.
45    StateMismatch,
46    /// A different entry was submitted at an acknowledged sequence; the
47    /// component acknowledges nothing further.
48    Frozen,
49    /// The primary holds no appended entry with that hash at that sequence.
50    NotAcknowledged,
51    /// A security-clock, signature, or store failure.
52    Store(V2StoreError),
53}
54
55impl fmt::Display for DeviceErrorTestOnly {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            DeviceErrorTestOnly::PowerLoss => f.write_str("v2reference: power lost during the device checkpoint submission"),
59            DeviceErrorTestOnly::StorageFull => f.write_str("v2reference: device checkpoint storage is full"),
60            DeviceErrorTestOnly::StateMismatch => {
61                f.write_str("v2reference: submission does not extend the device checkpoint head")
62            }
63            DeviceErrorTestOnly::Frozen => f.write_str("v2reference: device checkpoint is frozen after a conflicting entry"),
64            DeviceErrorTestOnly::NotAcknowledged => f.write_str(super::store::ERR_NOT_ACKNOWLEDGED),
65            DeviceErrorTestOnly::Store(e) => write!(f, "{e:?}"),
66        }
67    }
68}
69
70impl std::error::Error for DeviceErrorTestOnly {}
71
72impl From<DeviceErrorTestOnly> for V2StoreError {
73    fn from(e: DeviceErrorTestOnly) -> Self {
74        match e {
75            DeviceErrorTestOnly::Store(inner) => inner,
76            other => V2StoreError::Unavailable(other.to_string()),
77        }
78    }
79}
80
81/// Where the next submission loses power (Go `DevicePowerLoss`).
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
83pub enum DevicePowerLoss {
84    #[default]
85    Ok,
86    BeforeCommit,
87    AfterCommit,
88}
89
90/// One signed component record (Go `DeviceAcknowledgementTestOnly`).
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct DeviceAcknowledgementTestOnly {
93    pub log_id: String,
94    pub sequence: i64,
95    pub entry_hash: Vec<u8>,
96    pub state_digest: Vec<u8>,
97    pub timestamp: i64,
98    pub signature: Vec<u8>,
99}
100
101fn lp_bytes(out: &mut Vec<u8>, b: &[u8]) {
102    out.extend_from_slice(&(b.len() as u64).to_be_bytes());
103    out.extend_from_slice(b);
104}
105
106/// Go `deviceAckMessage`: the exact byte string the component signs.
107fn device_ack_message(a: &DeviceAcknowledgementTestOnly) -> Vec<u8> {
108    let mut m = b"ratify-test-device-checkpoint-v2\0".to_vec();
109    lp_bytes(&mut m, a.log_id.as_bytes());
110    m.extend_from_slice(&(a.sequence as u64).to_be_bytes());
111    lp_bytes(&mut m, &a.entry_hash);
112    lp_bytes(&mut m, &a.state_digest);
113    m.extend_from_slice(&(a.timestamp as u64).to_be_bytes());
114    m
115}
116
117/// Go `VerifyDeviceAcknowledgementTestOnly`: check a record under the pinned
118/// component public key.
119pub fn verify_device_acknowledgement_test_only(public: &[u8], a: &DeviceAcknowledgementTestOnly) -> Result<(), String> {
120    let refused = || "v2reference: device acknowledgement signature does not verify".to_string();
121    let key: [u8; 32] = public.try_into().map_err(|_| refused())?;
122    let key = VerifyingKey::from_bytes(&key).map_err(|_| refused())?;
123    let signature = Signature::from_slice(&a.signature).map_err(|_| refused())?;
124    key.verify(&device_ack_message(a), &signature).map_err(|_| refused())
125}
126
127struct ComponentState {
128    records: Vec<DeviceAcknowledgementTestOnly>,
129    /// The anchored complete-state digest; `None` until provisioned.
130    state: Option<Vec<u8>>,
131    frozen: bool,
132    fault: DevicePowerLoss,
133}
134
135/// The independent monotonic authenticated component (Go
136/// `DeviceComponentTestOnly`). Its clock is the device's configured
137/// security-clock source.
138pub struct DeviceComponentTestOnly {
139    key: SigningKey,
140    clock: Arc<dyn V2AuthoritativeClock>,
141    capacity: usize,
142    state: Mutex<ComponentState>,
143}
144
145impl fmt::Debug for DeviceComponentTestOnly {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        let (head, _, frozen) = self.head();
148        f.debug_struct("DeviceComponentTestOnly")
149            .field("head", &head)
150            .field("frozen", &frozen)
151            .field("capacity", &self.capacity)
152            .finish_non_exhaustive()
153    }
154}
155
156impl DeviceComponentTestOnly {
157    /// Go `NewDeviceComponentTestOnly`: a component with its own signing
158    /// key (from a 32-byte test seed) and room for `capacity`
159    /// acknowledgements.
160    pub fn new(seed: &[u8], capacity: usize, clock: Arc<dyn V2AuthoritativeClock>) -> V2Result<Self> {
161        let seed: [u8; 32] = seed.try_into().map_err(|_| {
162            V2Error::new(
163                V2ErrorClass::ConfigurationInvalid,
164                "v2reference: device component needs a 32-byte seed, positive capacity, and a clock",
165            )
166        })?;
167        if capacity < 1 {
168            return Err(V2Error::new(
169                V2ErrorClass::ConfigurationInvalid,
170                "v2reference: device component needs a 32-byte seed, positive capacity, and a clock",
171            ));
172        }
173        Ok(DeviceComponentTestOnly {
174            key: SigningKey::from_bytes(&seed),
175            clock,
176            capacity,
177            state: Mutex::new(ComponentState {
178                records: Vec::new(),
179                state: None,
180                frozen: false,
181                fault: DevicePowerLoss::Ok,
182            }),
183        })
184    }
185
186    fn lock(&self) -> MutexGuard<'_, ComponentState> {
187        self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
188    }
189
190    /// The component key the primary pins.
191    pub fn public_key(&self) -> Vec<u8> {
192        self.key.verifying_key().to_bytes().to_vec()
193    }
194
195    /// Arm a power loss for the next submission only.
196    pub fn set_power_loss(&self, fault: DevicePowerLoss) {
197        self.lock().fault = fault;
198    }
199
200    /// The acknowledged sequence (0 before the first acknowledgement), the
201    /// anchored complete-state digest (`None` before provisioning), and
202    /// whether the component is frozen.
203    pub fn head(&self) -> (i64, Option<Vec<u8>>, bool) {
204        let s = self.lock();
205        (s.records.len() as i64, s.state.clone(), s.frozen)
206    }
207
208    /// Anchor the primary's initial complete-state digest. Accepted once,
209    /// before any other anchor or acknowledgement.
210    pub fn provision_state(&self, digest: &[u8]) -> V2Result<()> {
211        let mut s = self.lock();
212        if s.state.is_some() || !s.records.is_empty() || digest.len() != 48 {
213            return Err(V2Error::plain(
214                "v2reference: device component is already provisioned or the digest is not 48 bytes",
215            ));
216        }
217        s.state = Some(digest.to_vec());
218        Ok(())
219    }
220
221    /// Advance the anchored complete-state digest from `previous` to `next`.
222    /// `previous` must equal the anchored digest: a primary whose state was
223    /// rolled back, restored, or altered cannot extend it. The register only
224    /// moves forward through this call; nothing lowers or restores it.
225    pub fn anchor_state(&self, previous: &[u8], next: &[u8]) -> Result<(), DeviceErrorTestOnly> {
226        let mut s = self.lock();
227        if s.frozen {
228            return Err(DeviceErrorTestOnly::Frozen);
229        }
230        if s.state.as_deref() != Some(previous) || next.len() != 48 {
231            return Err(DeviceErrorTestOnly::StateMismatch);
232        }
233        s.state = Some(next.to_vec());
234        Ok(())
235    }
236
237    /// Go `Commit`: record the next receipt-log entry. It accepts only
238    /// sequence head+1 whose previous entry hash equals the head's and whose
239    /// state digest equals the anchored complete-state digest. An identical
240    /// retry (same log ID and entry hash) of an acknowledged sequence returns
241    /// the original record, and a different entry at an acknowledged
242    /// sequence freezes the component.
243    pub fn commit(
244        &self,
245        ctx: &V2Context,
246        log_id: &str,
247        sequence: i64,
248        previous_entry_hash: &[u8],
249        entry_hash: &[u8],
250        state: &[u8],
251    ) -> Result<DeviceAcknowledgementTestOnly, DeviceErrorTestOnly> {
252        // The security clock is read before the component lock: the
253        // primary's clock source may itself take the store lock, which is
254        // held while the store anchors state here.
255        let now = self.clock.authoritative_time_v2(ctx);
256        self.commit_at(now, log_id, sequence, previous_entry_hash, entry_hash, state)
257    }
258
259    /// Go `commitAt`: `commit` with a security-clock reading taken before
260    /// any lock, so a caller may hold the primary's anchor lock across it.
261    pub(crate) fn commit_at(
262        &self,
263        now: Result<i64, V2StoreError>,
264        log_id: &str,
265        sequence: i64,
266        previous_entry_hash: &[u8],
267        entry_hash: &[u8],
268        state: &[u8],
269    ) -> Result<DeviceAcknowledgementTestOnly, DeviceErrorTestOnly> {
270        let mut s = self.lock();
271        if s.frozen {
272            return Err(DeviceErrorTestOnly::Frozen);
273        }
274        let acknowledged = s.records.len() as i64;
275        if sequence >= 1 && sequence <= acknowledged {
276            let existing = &s.records[sequence as usize - 1];
277            if existing.log_id == log_id && existing.entry_hash == entry_hash {
278                return Ok(existing.clone());
279            }
280            s.frozen = true;
281            return Err(DeviceErrorTestOnly::Frozen);
282        }
283        let mut head_entry = vec![0u8; 48];
284        if let Some(last) = s.records.last() {
285            if last.log_id != log_id {
286                return Err(DeviceErrorTestOnly::StateMismatch);
287            }
288            head_entry = last.entry_hash.clone();
289        }
290        if sequence != acknowledged + 1 || head_entry != previous_entry_hash || s.state.as_deref() != Some(state) {
291            return Err(DeviceErrorTestOnly::StateMismatch);
292        }
293        if s.records.len() >= self.capacity {
294            return Err(DeviceErrorTestOnly::StorageFull);
295        }
296        let fault = std::mem::take(&mut s.fault);
297        if fault == DevicePowerLoss::BeforeCommit {
298            return Err(DeviceErrorTestOnly::PowerLoss);
299        }
300        let now = now.map_err(DeviceErrorTestOnly::Store)?;
301        let mut ack = DeviceAcknowledgementTestOnly {
302            log_id: log_id.to_string(),
303            sequence,
304            entry_hash: entry_hash.to_vec(),
305            state_digest: state.to_vec(),
306            timestamp: now,
307            signature: Vec::new(),
308        };
309        ack.signature = self.key.sign(&device_ack_message(&ack)).to_bytes().to_vec();
310        s.records.push(ack.clone());
311        if fault == DevicePowerLoss::AfterCommit {
312            return Err(DeviceErrorTestOnly::PowerLoss);
313        }
314        Ok(ack)
315    }
316
317    /// The record for `sequence`, or `AcknowledgementNotFound`.
318    pub fn get(&self, log_id: &str, sequence: i64) -> Result<DeviceAcknowledgementTestOnly, V2StoreError> {
319        let s = self.lock();
320        match s.records.get((sequence.max(1) - 1) as usize) {
321            Some(r) if sequence >= 1 && r.log_id == log_id => Ok(r.clone()),
322            _ => Err(V2StoreError::AcknowledgementNotFound),
323        }
324    }
325}
326
327impl Store {
328    /// Go `CorruptSealedStateTestOnly`: flip one byte of a committed claim's
329    /// sealed terminal result, modelling corrupted primary storage.
330    pub fn corrupt_sealed_state_test_only(&self, claim_id: &str) {
331        if let Some(record) = self.lock().claims.get_mut(claim_id) {
332            if let Some(first) = record.terminal.first_mut() {
333                *first ^= 1;
334            }
335        }
336    }
337
338    /// Go `appendedEntry`: the entry hash of an appended receipt-log entry.
339    pub(crate) fn appended_entry(&self, sequence: i64) -> Option<Vec<u8>> {
340        if sequence < 1 {
341            return None;
342        }
343        let s = self.lock();
344        s.outbox
345            .get(sequence as usize - 1)
346            .filter(|e| e.wire.is_some())
347            .map(|e| e.digest.clone())
348    }
349
350    /// The signed wire of an appended receipt-log entry.
351    fn appended_wire(&self, sequence: i64) -> Option<Vec<u8>> {
352        if sequence < 1 {
353            return None;
354        }
355        self.lock().outbox.get(sequence as usize - 1).and_then(|e| e.wire.clone())
356    }
357
358    fn log_id(&self) -> String {
359        self.lock().log_id.clone()
360    }
361}
362
363/// The result of the primary's startup comparison with the component head
364/// (Go `DeviceStartupStatus`).
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum DeviceStartupStatus {
367    /// The primary's state at the component head equals the acknowledged
368    /// digest; any later appended entries are submitted in order.
369    Ready,
370    /// The primary holds fewer appended entries than the component
371    /// acknowledged (rollback or lost state). The device stays recovering
372    /// until its recovery authority advances the replay epoch.
373    PrimaryBehind,
374    /// The primary's complete-state digest differs from the anchored one,
375    /// including a rollback that kept the receipt-log prefix but lost or
376    /// altered any other durable security record.
377    StateDigestMismatch,
378    /// The component saw a conflicting entry.
379    CheckpointFrozen,
380}
381
382impl DeviceStartupStatus {
383    /// The spelling the shared vectors use.
384    pub fn as_str(self) -> &'static str {
385        match self {
386            DeviceStartupStatus::Ready => "ready",
387            DeviceStartupStatus::PrimaryBehind => "primary_behind",
388            DeviceStartupStatus::StateDigestMismatch => "state_digest_mismatch",
389            DeviceStartupStatus::CheckpointFrozen => "checkpoint_frozen",
390        }
391    }
392}
393
394/// The primary's view of the component (Go `DeviceCheckpointTestOnly`). It
395/// implements [`V2ReceiptCheckpoint`]: every acknowledgement it returns
396/// carries a component signature verified under the pinned key.
397pub struct DeviceCheckpointTestOnly {
398    device: Arc<PrimaryShared>,
399    primary: Arc<Store>,
400    component: Arc<DeviceComponentTestOnly>,
401    pinned: Vec<u8>,
402}
403
404impl fmt::Debug for DeviceCheckpointTestOnly {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        f.debug_struct("DeviceCheckpointTestOnly")
407            .field("component", &self.component)
408            .finish_non_exhaustive()
409    }
410}
411
412impl DeviceCheckpointTestOnly {
413    /// Go `NewDeviceCheckpointTestOnly`: bind a device primary to a
414    /// component whose key the primary pinned at provisioning; from now on
415    /// every durable change of the primary is anchored in the component
416    /// before it takes effect. The primary's store must not self-acknowledge
417    /// (`set_acknowledgement_withheld(true)`). A fresh device then calls
418    /// [`Self::provision`] once; a primary restored from a copy is bound
419    /// again without provisioning, and its first change or startup shows
420    /// whether it matches the anchored state.
421    pub fn new(
422        primary: &DevicePrimaryTestOnly,
423        component: Arc<DeviceComponentTestOnly>,
424        pinned: &[u8],
425    ) -> V2Result<Self> {
426        primary.bind(Arc::clone(&component))?;
427        Ok(DeviceCheckpointTestOnly {
428            device: Arc::clone(&primary.shared),
429            primary: Arc::clone(&primary.store),
430            component,
431            pinned: pinned.to_vec(),
432        })
433    }
434
435    /// Anchor the primary's current complete-state digest as the
436    /// component's initial state.
437    pub fn provision(&self) -> V2Result<()> {
438        let digest = self.device.complete_state_digest(&self.primary)?;
439        self.component.provision_state(&digest)
440    }
441
442    fn to_ack(&self, a: DeviceAcknowledgementTestOnly) -> Result<V2CheckpointAcknowledgement, DeviceErrorTestOnly> {
443        verify_device_acknowledgement_test_only(&self.pinned, &a)
444            .map_err(|e| DeviceErrorTestOnly::Store(V2StoreError::Unavailable(e)))?;
445        Ok(V2CheckpointAcknowledgement {
446            log_id: a.log_id,
447            sequence: a.sequence,
448            entry_hash: a.entry_hash,
449            timestamp: a.timestamp,
450        })
451    }
452
453    /// Go `AcknowledgeV2Receipt`: submit the primary's appended entry with
454    /// the primary's anchored complete-state digest, which already covers
455    /// the append. The security clock is read first, with no lock held,
456    /// because the clock source may take the store lock, which precedes the
457    /// anchor lock. The anchor lock is then held from composing the anchored
458    /// digest through the component commit, so a concurrent anchored change
459    /// cannot advance the component's digest in between.
460    pub fn acknowledge(
461        &self,
462        ctx: &V2Context,
463        log_id: &str,
464        sequence: i64,
465        previous_entry_hash: &[u8],
466        entry_hash: &[u8],
467    ) -> Result<V2CheckpointAcknowledgement, DeviceErrorTestOnly> {
468        if self.primary.appended_entry(sequence).as_deref() != Some(entry_hash) {
469            return Err(DeviceErrorTestOnly::NotAcknowledged);
470        }
471        let now = self.component.clock.authoritative_time_v2(ctx);
472        let ack = {
473            let anchor = self.device.lock_anchor();
474            let state = self
475                .device
476                .compose(&anchor.last_store)
477                .map_err(|e| DeviceErrorTestOnly::Store(V2StoreError::Classified(e)))?;
478            self.component
479                .commit_at(now, log_id, sequence, previous_entry_hash, entry_hash, &state)?
480        };
481        self.to_ack(ack)
482    }
483
484    /// Go `SubmitPending`: submit, in log order, every appended entry of the
485    /// primary that the component has not acknowledged with the same entry
486    /// hash, and return the sequences acknowledged by this call with the
487    /// failure that stopped it, if any. A rolled-back primary therefore
488    /// resubmits its own version of an acknowledged sequence, which the
489    /// component refuses.
490    pub fn submit_pending(&self, ctx: &V2Context) -> (Vec<i64>, Option<DeviceErrorTestOnly>) {
491        let mut acknowledged = Vec::new();
492        let log_id = self.primary.log_id();
493        let mut next = 1;
494        while let Some(entry) = self.primary.appended_entry(next) {
495            let already = matches!(self.component.get(&log_id, next), Ok(existing) if existing.entry_hash == entry);
496            if !already {
497                if let Err(e) = self.resubmit(ctx, next) {
498                    return (acknowledged, Some(e));
499                }
500                acknowledged.push(next);
501            }
502            next += 1;
503        }
504        (acknowledged, None)
505    }
506
507    /// Go `Resubmit`: retry the exact tuple for `sequence` (for example
508    /// after a power loss whose outcome is unknown) and return the
509    /// acknowledgement.
510    pub fn resubmit(&self, ctx: &V2Context, sequence: i64) -> Result<V2CheckpointAcknowledgement, DeviceErrorTestOnly> {
511        let entry = self
512            .primary
513            .appended_entry(sequence)
514            .ok_or(DeviceErrorTestOnly::NotAcknowledged)?;
515        let previous = if sequence > 1 {
516            self.primary
517                .appended_entry(sequence - 1)
518                .ok_or(DeviceErrorTestOnly::NotAcknowledged)?
519        } else {
520            vec![0u8; 48]
521        };
522        self.acknowledge(ctx, &self.primary.log_id(), sequence, &previous, &entry)
523    }
524
525    /// Go `Startup`: compare the primary with the component head before the
526    /// device serves any request: frozen component, then fewer appended
527    /// entries than acknowledged, then the recomputed complete-state digest
528    /// against the anchored one.
529    pub fn startup(&self) -> DeviceStartupStatus {
530        let (head, anchored, frozen) = self.component.head();
531        if frozen {
532            return DeviceStartupStatus::CheckpointFrozen;
533        }
534        if (self.primary.log_length() as i64) < head {
535            return DeviceStartupStatus::PrimaryBehind;
536        }
537        match self.device.complete_state_digest(&self.primary) {
538            Ok(state) if Some(&state) == anchored.as_ref() => DeviceStartupStatus::Ready,
539            _ => DeviceStartupStatus::StateDigestMismatch,
540        }
541    }
542}
543
544impl V2ReceiptCheckpoint for DeviceCheckpointTestOnly {
545    fn acknowledge_v2_receipt(
546        &self,
547        ctx: &V2Context,
548        log_id: &str,
549        sequence: i64,
550        previous_entry_hash: &[u8],
551        entry_hash: &[u8],
552    ) -> Result<V2CheckpointAcknowledgement, V2StoreError> {
553        Ok(self.acknowledge(ctx, log_id, sequence, previous_entry_hash, entry_hash)?)
554    }
555
556    /// Read and verify the component record.
557    fn get_v2_acknowledgement(
558        &self,
559        _ctx: &V2Context,
560        log_id: &str,
561        sequence: i64,
562    ) -> Result<V2CheckpointAcknowledgement, V2StoreError> {
563        let ack = self.component.get(log_id, sequence)?;
564        Ok(self.to_ack(ack)?)
565    }
566}
567
568/// The outbox upload after reconnection (Go `DeviceUplinkTestOnly`). It
569/// uploads signed receipts only from the component-acknowledged prefix, in
570/// log order, once each. Upload is an outbox operation: it never releases a
571/// decision, changes a release record, or makes a withheld result
572/// actionable.
573#[derive(Debug)]
574pub struct DeviceUplinkTestOnly {
575    device: Arc<DeviceCheckpointTestOnly>,
576    state: Mutex<(i64, Vec<Vec<u8>>)>,
577}
578
579impl DeviceUplinkTestOnly {
580    /// An uplink for the device.
581    pub fn new(device: Arc<DeviceCheckpointTestOnly>) -> Self {
582        DeviceUplinkTestOnly {
583            device,
584            state: Mutex::new((0, Vec::new())),
585        }
586    }
587
588    /// Send every acknowledged receipt not yet uploaded and return their
589    /// sequences.
590    pub fn upload(&self, _ctx: &V2Context) -> Vec<i64> {
591        let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
592        let (head, _, _) = self.device.component.head();
593        let mut sent = Vec::new();
594        while state.0 < head {
595            let next = state.0 + 1;
596            let Some(wire) = self.device.primary.appended_wire(next) else {
597                break;
598            };
599            state.1.push(wire);
600            state.0 = next;
601            sent.push(next);
602        }
603        sent
604    }
605
606    /// The receipts uploaded so far, in log order.
607    pub fn collected(&self) -> Vec<Vec<u8>> {
608        self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).1.clone()
609    }
610}