katzenpost_thin_client 0.0.17

This rust crate provides an async thin client library for Katzenpost, a post quantum decryption mixnet.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
// SPDX-FileCopyrightText: Copyright (C) 2026 David Stainton
// SPDX-License-Identifier: AGPL-3.0-only

//! Typed channel handles for simplified pigeonhole operations.
//!
//! A `WriteChannel` carries the write capability and tracks the next
//! message box index for sending. A `ReadChannel` carries the read
//! capability and tracks the next message box index for receiving.
//! Capabilities themselves are immutable; only `next_index` advances.

use std::sync::Arc;

use rand::RngCore;

use crate::core::ThinClient;
use crate::pigeonhole::{KeypairResult, TombstoneRangeResult};
use super::db::Database;
use super::error::{PigeonholeDbError, Result};
use super::models::{
    ReadChannel as ReadChannelModel, ReceivedMessage, WriteChannel as WriteChannelModel,
};

/// High-level pigeonhole client with database persistence.
pub struct PigeonholeClient {
    client: Arc<ThinClient>,
    db: Database,
}

impl PigeonholeClient {
    pub fn new(client: Arc<ThinClient>, db: Database) -> Self {
        Self { client, db }
    }

    pub fn new_in_memory(client: Arc<ThinClient>) -> Result<Self> {
        let db = Database::open_in_memory()?;
        Ok(Self { client, db })
    }

    pub fn db(&self) -> &Database {
        &self.db
    }

    pub fn thin_client(&self) -> &Arc<ThinClient> {
        &self.client
    }

    // ========================================================================
    // Write Channel Constructors
    // ========================================================================

    /// Load an owned write channel from previously-issued capability material.
    ///
    /// `next_index` is the message box index to use for the next write —
    /// either `first_message_index` from `new_keypair` for a fresh channel,
    /// or a saved cursor from a prior session for resume.
    pub fn load_write_channel(
        &self,
        name: &str,
        write_cap: &[u8],
        next_index: &[u8],
    ) -> Result<WriteChannel> {
        let model = self.db.create_write_channel(name, write_cap, next_index)?;
        Ok(WriteChannel { model, client: self.client.clone(), db: self.db.clone() })
    }

    /// Get an existing write channel by name.
    pub fn get_write_channel(&self, name: &str) -> Result<WriteChannel> {
        let model = self.db.get_write_channel(name)?;
        Ok(WriteChannel { model, client: self.client.clone(), db: self.db.clone() })
    }

    /// List all stored write channels.
    pub fn list_write_channels(&self) -> Result<Vec<WriteChannelModel>> {
        self.db.list_write_channels()
    }

    /// Delete a write channel and all its pending messages.
    pub fn delete_write_channel(&self, name: &str) -> Result<()> {
        self.db.delete_write_channel(name)
    }

    // ========================================================================
    // Read Channel Constructors
    // ========================================================================

    /// Load a read channel from previously-issued capability material.
    ///
    /// `next_index` is the message box index to use for the next read —
    /// either `first_message_index` from `new_keypair` for a fresh channel,
    /// or a saved cursor from a prior session for resume.
    pub fn load_read_channel(
        &self,
        name: &str,
        read_cap: &[u8],
        next_index: &[u8],
    ) -> Result<ReadChannel> {
        let model = self.db.create_read_channel(name, read_cap, next_index)?;
        Ok(ReadChannel { model, client: self.client.clone(), db: self.db.clone() })
    }

    /// Get an existing read channel by name.
    pub fn get_read_channel(&self, name: &str) -> Result<ReadChannel> {
        let model = self.db.get_read_channel(name)?;
        Ok(ReadChannel { model, client: self.client.clone(), db: self.db.clone() })
    }

    /// List all stored read channels.
    pub fn list_read_channels(&self) -> Result<Vec<ReadChannelModel>> {
        self.db.list_read_channels()
    }

    /// Delete a read channel and all its received messages.
    pub fn delete_read_channel(&self, name: &str) -> Result<()> {
        self.db.delete_read_channel(name)
    }

    /// Create a `CopyStreamBuilder` rooted at this client's thin client,
    /// without first loading or creating any persisted channel. Useful
    /// when the caller already has the destination cap and start index
    /// in hand.
    pub async fn copy_stream_builder(&self) -> Result<CopyStreamBuilder> {
        CopyStreamBuilder::new(self.client.clone()).await
    }
}

// ============================================================================
// WriteChannel
// ============================================================================

/// Handle for sending on a pigeonhole channel.
pub struct WriteChannel {
    model: WriteChannelModel,
    client: Arc<ThinClient>,
    db: Database,
}

impl WriteChannel {
    pub fn name(&self) -> &str {
        &self.model.name
    }

    pub fn write_cap(&self) -> &[u8] {
        &self.model.write_cap
    }

    /// The message box index that will be used for the next write.
    pub fn next_index(&self) -> &[u8] {
        &self.model.next_index
    }

    /// Refresh the in-memory model from the database.
    pub fn refresh(&mut self) -> Result<()> {
        self.model = self.db.get_write_channel_by_id(self.model.id)?;
        Ok(())
    }

    // ------------------------------------------------------------------------
    // Low-Level Box Operations (caller-supplied index, no state advancement)
    // ------------------------------------------------------------------------

    /// Write a single box at a specific index. Does NOT advance `next_index`.
    pub async fn write_box(&self, plaintext: &[u8], box_index: &[u8]) -> Result<Vec<u8>> {
        let result = self
            .client
            .encrypt_write(plaintext, &self.model.write_cap, box_index)
            .await?;

        self.client
            .start_resending_encrypted_message(
                None,
                Some(&self.model.write_cap),
                None,
                Some(0),
                &result.envelope_descriptor,
                &result.message_ciphertext,
                &result.envelope_hash,
            )
            .await?;

        Ok(result.next_message_box_index)
    }

    /// Write a single box, returning `BoxAlreadyExists` rather than treating
    /// re-writes as idempotent successes.
    pub async fn write_box_return_box_exists(
        &self,
        plaintext: &[u8],
        box_index: &[u8],
    ) -> Result<Vec<u8>> {
        let result = self
            .client
            .encrypt_write(plaintext, &self.model.write_cap, box_index)
            .await?;

        self.client
            .start_resending_encrypted_message_return_box_exists(
                None,
                Some(&self.model.write_cap),
                None,
                Some(0),
                &result.envelope_descriptor,
                &result.message_ciphertext,
                &result.envelope_hash,
            )
            .await?;

        Ok(result.next_message_box_index)
    }

    // ------------------------------------------------------------------------
    // High-Level Send (advances state in the database)
    // ------------------------------------------------------------------------

    /// Send a message at the channel's `next_index`, advancing state on success.
    pub async fn send(&mut self, plaintext: &[u8]) -> Result<()> {
        let encrypt_result = self
            .client
            .encrypt_write(plaintext, &self.model.write_cap, &self.model.next_index)
            .await?;

        let pending = self.db.create_pending_message(
            self.model.id,
            plaintext,
            &encrypt_result.message_ciphertext,
            &encrypt_result.envelope_descriptor,
            &encrypt_result.envelope_hash,
            &self.model.next_index,
        )?;

        self.db.update_pending_message_status(pending.id, "sending")?;

        let result = self
            .client
            .start_resending_encrypted_message(
                None,
                Some(&self.model.write_cap),
                None,
                Some(0),
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await;

        match result {
            Ok(_) => {
                let next = encrypt_result.next_message_box_index;
                self.db.update_write_next_index(self.model.id, &next)?;
                self.db.delete_pending_message(pending.id)?;
                self.model.next_index = next;
                Ok(())
            }
            Err(e) => {
                self.db.update_pending_message_status(pending.id, "failed")?;
                Err(e.into())
            }
        }
    }

    /// Like `send`, but returns `BoxAlreadyExists` rather than treating
    /// re-writes as idempotent successes.
    pub async fn send_return_box_exists(&mut self, plaintext: &[u8]) -> Result<()> {
        let encrypt_result = self
            .client
            .encrypt_write(plaintext, &self.model.write_cap, &self.model.next_index)
            .await?;

        let pending = self.db.create_pending_message(
            self.model.id,
            plaintext,
            &encrypt_result.message_ciphertext,
            &encrypt_result.envelope_descriptor,
            &encrypt_result.envelope_hash,
            &self.model.next_index,
        )?;

        self.db.update_pending_message_status(pending.id, "sending")?;

        let result = self
            .client
            .start_resending_encrypted_message_return_box_exists(
                None,
                Some(&self.model.write_cap),
                None,
                Some(0),
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await;

        match result {
            Ok(_) => {
                let next = encrypt_result.next_message_box_index;
                self.db.update_write_next_index(self.model.id, &next)?;
                self.db.delete_pending_message(pending.id)?;
                self.model.next_index = next;
                Ok(())
            }
            Err(e) => {
                self.db.update_pending_message_status(pending.id, "failed")?;
                Err(e.into())
            }
        }
    }

    // ------------------------------------------------------------------------
    // Tombstone Operations
    // ------------------------------------------------------------------------

    /// Tombstone the box at `next_index`, advancing state on success.
    pub async fn tombstone_current(&mut self) -> Result<()> {
        let encrypt_result = self
            .client
            .encrypt_write(&[], &self.model.write_cap, &self.model.next_index)
            .await?;

        self.client
            .start_resending_encrypted_message(
                None,
                Some(&self.model.write_cap),
                None,
                None,
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await?;

        let next = encrypt_result.next_message_box_index;
        self.db.update_write_next_index(self.model.id, &next)?;
        self.model.next_index = next;
        Ok(())
    }

    /// Tombstone up to `count` boxes starting from the channel's `next_index`,
    /// advancing state past the tombstoned range.
    pub async fn tombstone_range(&mut self, count: u32) -> Result<u32> {
        let result: TombstoneRangeResult = self
            .client
            .tombstone_range(&self.model.write_cap, &self.model.next_index, count)
            .await;

        let mut sent = 0u32;
        for envelope in &result.envelopes {
            let mut hash = [0u8; 32];
            hash.copy_from_slice(&envelope.envelope_hash);

            match self
                .client
                .start_resending_encrypted_message(
                    None,
                    Some(&self.model.write_cap),
                    None,
                    None,
                    &envelope.envelope_descriptor,
                    &envelope.message_ciphertext,
                    &hash,
                )
                .await
            {
                Ok(_) => sent += 1,
                Err(e) => {
                    if sent > 0 {
                        self.db
                            .update_write_next_index(self.model.id, &envelope.box_index)?;
                        self.model.next_index = envelope.box_index.clone();
                    }
                    return Err(e.into());
                }
            }
        }

        if sent > 0 {
            self.db.update_write_next_index(self.model.id, &result.next)?;
            self.model.next_index = result.next;
        }
        Ok(sent)
    }

    /// Tombstone a specific box without affecting the channel's `next_index`.
    pub async fn tombstone_at(&self, box_index: &[u8]) -> Result<()> {
        let encrypt_result = self
            .client
            .encrypt_write(&[], &self.model.write_cap, box_index)
            .await?;

        self.client
            .start_resending_encrypted_message(
                None,
                Some(&self.model.write_cap),
                None,
                None,
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await?;

        Ok(())
    }

    /// Tombstone up to `count` boxes from `start_index` without affecting
    /// the channel's `next_index`.
    pub async fn tombstone_from(&self, start_index: &[u8], count: u32) -> Result<u32> {
        let result: TombstoneRangeResult = self
            .client
            .tombstone_range(&self.model.write_cap, start_index, count)
            .await;

        let mut sent = 0u32;
        for envelope in &result.envelopes {
            let mut hash = [0u8; 32];
            hash.copy_from_slice(&envelope.envelope_hash);

            match self
                .client
                .start_resending_encrypted_message(
                    None,
                    Some(&self.model.write_cap),
                    None,
                    None,
                    &envelope.envelope_descriptor,
                    &envelope.message_ciphertext,
                    &hash,
                )
                .await
            {
                Ok(_) => sent += 1,
                Err(e) => return Err(e.into()),
            }
        }
        Ok(sent)
    }

    // ------------------------------------------------------------------------
    // Copy Stream Operations
    // ------------------------------------------------------------------------

    /// Create a `CopyStreamBuilder` rooted at this channel's thin client.
    pub async fn copy_stream_builder(&self) -> Result<CopyStreamBuilder> {
        CopyStreamBuilder::new(self.client.clone()).await
    }

    /// Execute a Copy command using this channel's write capability as the source.
    pub async fn execute_copy(
        &self,
        courier_identity_hash: Option<&[u8]>,
        courier_queue_id: Option<&[u8]>,
    ) -> Result<()> {
        self.client
            .start_resending_copy_command(&self.model.write_cap, courier_identity_hash, courier_queue_id)
            .await?;
        Ok(())
    }

    /// Cancel a Copy command in progress by write-cap hash.
    pub async fn cancel_copy(&self, write_cap_hash: &[u8; 32]) -> Result<()> {
        self.client.cancel_resending_copy_command(write_cap_hash).await?;
        Ok(())
    }
}

// ============================================================================
// ReadChannel
// ============================================================================

/// Handle for receiving on a pigeonhole channel.
pub struct ReadChannel {
    model: ReadChannelModel,
    client: Arc<ThinClient>,
    db: Database,
}

impl ReadChannel {
    pub fn name(&self) -> &str {
        &self.model.name
    }

    pub fn read_cap(&self) -> &[u8] {
        &self.model.read_cap
    }

    /// The message box index that will be used for the next read.
    pub fn next_index(&self) -> &[u8] {
        &self.model.next_index
    }

    /// Refresh the in-memory model from the database.
    pub fn refresh(&mut self) -> Result<()> {
        self.model = self.db.get_read_channel_by_id(self.model.id)?;
        Ok(())
    }

    // ------------------------------------------------------------------------
    // Low-Level Box Operations (caller-supplied index, no state advancement)
    // ------------------------------------------------------------------------

    /// Read a single box at a specific index. Does NOT advance `next_index`.
    pub async fn read_box(&self, box_index: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
        let encrypt_result = self
            .client
            .encrypt_read(&self.model.read_cap, box_index)
            .await?;

        let result = self
            .client
            .start_resending_encrypted_message(
                Some(&self.model.read_cap),
                None,
                Some(box_index),
                Some(0),
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await?;

        Ok((result.plaintext, encrypt_result.next_message_box_index))
    }

    /// Like `read_box`, but returns `BoxIDNotFound` immediately rather than
    /// retrying through replication lag.
    pub async fn read_box_no_retry(&self, box_index: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
        let encrypt_result = self
            .client
            .encrypt_read(&self.model.read_cap, box_index)
            .await?;

        let result = self
            .client
            .start_resending_encrypted_message_no_retry(
                Some(&self.model.read_cap),
                None,
                Some(box_index),
                Some(0),
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await?;

        Ok((result.plaintext, encrypt_result.next_message_box_index))
    }

    // ------------------------------------------------------------------------
    // High-Level Receive (advances state in the database)
    // ------------------------------------------------------------------------

    /// Receive the next message from the channel's `next_index`, advancing state on success.
    pub async fn receive(&mut self) -> Result<Vec<u8>> {
        let encrypt_result = self
            .client
            .encrypt_read(&self.model.read_cap, &self.model.next_index)
            .await?;

        let current_index = self.model.next_index.clone();
        let result = self
            .client
            .start_resending_encrypted_message(
                Some(&self.model.read_cap),
                None,
                Some(&current_index),
                Some(0),
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await?;

        self.db
            .create_received_message(self.model.id, &result.plaintext, &current_index)?;

        let next = encrypt_result.next_message_box_index;
        self.db.update_read_next_index(self.model.id, &next)?;
        self.model.next_index = next;

        Ok(result.plaintext)
    }

    /// Like `receive`, but returns `BoxIDNotFound` immediately rather than
    /// retrying through replication lag.
    pub async fn receive_no_retry(&mut self) -> Result<Vec<u8>> {
        let encrypt_result = self
            .client
            .encrypt_read(&self.model.read_cap, &self.model.next_index)
            .await?;

        let current_index = self.model.next_index.clone();
        let result = self
            .client
            .start_resending_encrypted_message_no_retry(
                Some(&self.model.read_cap),
                None,
                Some(&current_index),
                Some(0),
                &encrypt_result.envelope_descriptor,
                &encrypt_result.message_ciphertext,
                &encrypt_result.envelope_hash,
            )
            .await?;

        self.db
            .create_received_message(self.model.id, &result.plaintext, &current_index)?;

        let next = encrypt_result.next_message_box_index;
        self.db.update_read_next_index(self.model.id, &next)?;
        self.model.next_index = next;

        Ok(result.plaintext)
    }

    pub fn get_unread_messages(&self) -> Result<Vec<ReceivedMessage>> {
        self.db.get_unread_messages(self.model.id)
    }

    pub fn get_all_messages(&self) -> Result<Vec<ReceivedMessage>> {
        self.db.get_all_messages(self.model.id)
    }

    pub fn mark_message_read(&self, message_id: i64) -> Result<()> {
        self.db.mark_message_read(message_id)
    }
}

// ============================================================================
// CopyStreamBuilder
// ============================================================================

/// Builder for streaming arbitrarily large payloads through a temporary
/// pigeonhole channel into one or more destination channels via the courier
/// Copy command.
pub struct CopyStreamBuilder {
    client: Arc<ThinClient>,
    temp_write_cap: Vec<u8>,
    temp_index: Vec<u8>,
    total_boxes: usize,
    buffer: Vec<u8>,
}

impl CopyStreamBuilder {
    async fn new(client: Arc<ThinClient>) -> Result<Self> {
        let mut seed = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut seed);
        let KeypairResult { write_cap: temp_write_cap, read_cap: _, first_message_index: temp_first_index } =
            client.new_keypair(&seed).await?;

        Ok(Self {
            client,
            temp_write_cap,
            temp_index: temp_first_index,
            total_boxes: 0,
            buffer: Vec::new(),
        })
    }

    pub async fn add_payload(
        &mut self,
        payload: &[u8],
        dest_write_cap: &[u8],
        dest_start_index: &[u8],
        is_last: bool,
    ) -> Result<usize> {
        let is_start = self.total_boxes == 0;
        let result = self
            .client
            .create_courier_envelopes_from_payload(payload, dest_write_cap, dest_start_index, is_start, is_last)
            .await?;

        let chunk_count = result.envelopes.len();

        for chunk in result.envelopes {
            let encrypt_result = self
                .client
                .encrypt_write(&chunk, &self.temp_write_cap, &self.temp_index)
                .await?;

            self.client
                .start_resending_encrypted_message(
                    None,
                    Some(&self.temp_write_cap),
                    None,
                    Some(0),
                    &encrypt_result.envelope_descriptor,
                    &encrypt_result.message_ciphertext,
                    &encrypt_result.envelope_hash,
                )
                .await?;

            self.temp_index = encrypt_result.next_message_box_index;
        }

        self.total_boxes += chunk_count;
        Ok(chunk_count)
    }

    pub async fn add_multi_payload(
        &mut self,
        destinations: Vec<(&[u8], &[u8], &[u8])>,
        is_last: bool,
    ) -> Result<usize> {
        if destinations.is_empty() {
            return Ok(0);
        }

        let is_start = self.total_boxes == 0;
        let buf = if self.buffer.is_empty() { None } else { Some(self.buffer.clone()) };
        let result = self
            .client
            .create_courier_envelopes_from_multi_payload(destinations, is_start, is_last, buf)
            .await?;

        let chunk_count = result.envelopes.len();
        self.buffer = result.buffer;

        for chunk in result.envelopes {
            let encrypt_result = self
                .client
                .encrypt_write(&chunk, &self.temp_write_cap, &self.temp_index)
                .await?;

            self.client
                .start_resending_encrypted_message(
                    None,
                    Some(&self.temp_write_cap),
                    None,
                    Some(0),
                    &encrypt_result.envelope_descriptor,
                    &encrypt_result.message_ciphertext,
                    &encrypt_result.envelope_hash,
                )
                .await?;

            self.temp_index = encrypt_result.next_message_box_index;
        }

        self.total_boxes += chunk_count;
        Ok(chunk_count)
    }

    pub async fn finish(self) -> Result<usize> {
        self.client
            .start_resending_copy_command(&self.temp_write_cap, None, None)
            .await?;
        Ok(self.total_boxes)
    }

    pub async fn finish_with_courier(
        self,
        courier_identity_hash: &[u8],
        courier_queue_id: &[u8],
    ) -> Result<usize> {
        self.client
            .start_resending_copy_command(
                &self.temp_write_cap,
                Some(courier_identity_hash),
                Some(courier_queue_id),
            )
            .await?;
        Ok(self.total_boxes)
    }

    pub fn temp_write_cap(&self) -> &[u8] {
        &self.temp_write_cap
    }

    pub fn buffer(&self) -> &[u8] {
        &self.buffer
    }
}

// `PigeonholeDbError` is referenced indirectly through `Result`; suppress unused warning.
#[allow(dead_code)]
fn _ensure_error_in_scope(_e: PigeonholeDbError) {}