tlsn_core/
transcript.rs

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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Transcript types.
//!
//! All application data communicated over a TLS connection is referred to as a
//! [`Transcript`]. A transcript is essentially just two vectors of bytes, each
//! corresponding to a [`Direction`].
//!
//! TLS operates over a bidirectional byte stream, and thus there are no
//! application layer semantics present in the transcript. For example, HTTPS is
//! an application layer protocol that runs *over TLS* so there is no concept of
//! "requests" or "responses" in the transcript itself. These semantics must be
//! recovered by parsing the application data and relating it to the bytes
//! in the transcript.
//!
//! ## Commitments
//!
//! During the attestation process a Prover can generate multiple commitments to
//! various parts of the transcript. These commitments are inserted into the
//! attestation body and can be used by the Verifier to verify transcript proofs
//! later.
//!
//! To configure the transcript commitments, use the
//! [`TranscriptCommitConfigBuilder`].
//!
//! ## Selective Disclosure
//!
//! Using a [`TranscriptProof`] a Prover can selectively disclose parts of a
//! transcript to a Verifier in the form of a [`PartialTranscript`]. A Verifier
//! always learns the length of the transcript, but sensitive data can be
//! withheld.
//!
//! To create a proof, use the [`TranscriptProofBuilder`] which is returned by
//! [`Secrets::transcript_proof_builder`](crate::Secrets::transcript_proof_builder).

mod commit;
#[doc(hidden)]
pub mod encoding;
pub(crate) mod hash;
mod proof;

use std::{fmt, ops::Range};

use serde::{Deserialize, Serialize};
use utils::range::{Difference, IndexRanges, RangeSet, ToRangeSet, Union};

use crate::connection::TranscriptLength;

pub use commit::{
    TranscriptCommitConfig, TranscriptCommitConfigBuilder, TranscriptCommitConfigBuilderError,
    TranscriptCommitmentKind,
};
pub use proof::{
    TranscriptProof, TranscriptProofBuilder, TranscriptProofBuilderError, TranscriptProofError,
};

/// Sent data transcript ID.
pub static TX_TRANSCRIPT_ID: &str = "tx";
/// Received data transcript ID.
pub static RX_TRANSCRIPT_ID: &str = "rx";

/// A transcript contains all the data communicated over a TLS connection.
#[derive(Clone, Serialize, Deserialize)]
pub struct Transcript {
    /// Data sent from the Prover to the Server.
    sent: Vec<u8>,
    /// Data received by the Prover from the Server.
    received: Vec<u8>,
}

opaque_debug::implement!(Transcript);

impl Transcript {
    /// Creates a new transcript.
    pub fn new(sent: impl Into<Vec<u8>>, received: impl Into<Vec<u8>>) -> Self {
        Self {
            sent: sent.into(),
            received: received.into(),
        }
    }

    /// Returns a reference to the sent data.
    pub fn sent(&self) -> &[u8] {
        &self.sent
    }

    /// Returns a reference to the received data.
    pub fn received(&self) -> &[u8] {
        &self.received
    }

    /// Returns the length of the sent and received data, respectively.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> (usize, usize) {
        (self.sent.len(), self.received.len())
    }

    /// Returns the length of the transcript in the given direction.
    pub(crate) fn len_of_direction(&self, direction: Direction) -> usize {
        match direction {
            Direction::Sent => self.sent.len(),
            Direction::Received => self.received.len(),
        }
    }

    /// Returns the transcript length.
    pub fn length(&self) -> TranscriptLength {
        TranscriptLength {
            sent: self.sent.len() as u32,
            received: self.received.len() as u32,
        }
    }

    /// Returns the subsequence of the transcript with the provided index,
    /// returning `None` if the index is out of bounds.
    pub fn get(&self, direction: Direction, idx: &Idx) -> Option<Subsequence> {
        let data = match direction {
            Direction::Sent => &self.sent,
            Direction::Received => &self.received,
        };

        if idx.end() > data.len() {
            return None;
        }

        Some(
            Subsequence::new(idx.clone(), data.index_ranges(&idx.0))
                .expect("data is same length as index"),
        )
    }

    /// Returns a partial transcript containing the provided indices.
    ///
    /// # Panics
    ///
    /// Panics if the indices are out of bounds.
    ///
    /// # Arguments
    ///
    /// * `sent_idx` - The indices of the sent data to include.
    /// * `recv_idx` - The indices of the received data to include.
    pub fn to_partial(&self, sent_idx: Idx, recv_idx: Idx) -> PartialTranscript {
        let mut sent = vec![0; self.sent.len()];
        let mut received = vec![0; self.received.len()];

        for range in sent_idx.iter_ranges() {
            sent[range.clone()].copy_from_slice(&self.sent[range]);
        }

        for range in recv_idx.iter_ranges() {
            received[range.clone()].copy_from_slice(&self.received[range]);
        }

        PartialTranscript {
            sent,
            received,
            sent_authed: sent_idx,
            received_authed: recv_idx,
        }
    }
}

/// A partial transcript.
///
/// A partial transcript is a transcript which may not have all the data
/// authenticated.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "validation::PartialTranscriptUnchecked")]
pub struct PartialTranscript {
    /// Data sent from the Prover to the Server.
    sent: Vec<u8>,
    /// Data received by the Prover from the Server.
    received: Vec<u8>,
    /// Index of `sent` which have been authenticated.
    sent_authed: Idx,
    /// Index of `received` which have been authenticated.
    received_authed: Idx,
}

impl PartialTranscript {
    /// Creates a new partial transcript initalized to all 0s.
    ///
    /// # Arguments
    ///
    /// * `sent_len` - The length of the sent data.
    /// * `received_len` - The length of the received data.
    pub fn new(sent_len: usize, received_len: usize) -> Self {
        Self {
            sent: vec![0; sent_len],
            received: vec![0; received_len],
            sent_authed: Idx::default(),
            received_authed: Idx::default(),
        }
    }

    /// Returns the length of the sent transcript.
    pub fn len_sent(&self) -> usize {
        self.sent.len()
    }

    /// Returns the length of the received transcript.
    pub fn len_received(&self) -> usize {
        self.received.len()
    }

    /// Returns whether the transcript is complete.
    pub fn is_complete(&self) -> bool {
        self.sent_authed.len() == self.sent.len()
            && self.received_authed.len() == self.received.len()
    }

    /// Returns whether the index is in bounds of the transcript.
    pub fn contains(&self, direction: Direction, idx: &Idx) -> bool {
        match direction {
            Direction::Sent => idx.end() <= self.sent.len(),
            Direction::Received => idx.end() <= self.received.len(),
        }
    }

    /// Returns a reference to the sent data.
    ///
    /// # Warning
    ///
    /// Not all of the data in the transcript may have been authenticated. See
    /// [sent_authed](PartialTranscript::sent_authed) for a set of ranges which
    /// have been.
    pub fn sent_unsafe(&self) -> &[u8] {
        &self.sent
    }

    /// Returns a reference to the received data.
    ///
    /// # Warning
    ///
    /// Not all of the data in the transcript may have been authenticated. See
    /// [received_authed](PartialTranscript::received_authed) for a set of
    /// ranges which have been.
    pub fn received_unsafe(&self) -> &[u8] {
        &self.received
    }

    /// Returns the index of sent data which have been authenticated.
    pub fn sent_authed(&self) -> &Idx {
        &self.sent_authed
    }

    /// Returns the index of received data which have been authenticated.
    pub fn received_authed(&self) -> &Idx {
        &self.received_authed
    }

    /// Returns the index of sent data which haven't been authenticated.
    pub fn sent_unauthed(&self) -> Idx {
        Idx(RangeSet::from(0..self.sent.len()).difference(&self.sent_authed.0))
    }

    /// Returns the index of received data which haven't been authenticated.
    pub fn received_unauthed(&self) -> Idx {
        Idx(RangeSet::from(0..self.received.len()).difference(&self.received_authed.0))
    }

    /// Returns an iterator over the authenticated data in the transcript.
    pub fn iter(&self, direction: Direction) -> impl Iterator<Item = u8> + '_ {
        let (data, authed) = match direction {
            Direction::Sent => (&self.sent, &self.sent_authed),
            Direction::Received => (&self.received, &self.received_authed),
        };

        authed.0.iter().map(|i| data[i])
    }

    /// Unions the authenticated data of this transcript with another.
    ///
    /// # Panics
    ///
    /// Panics if the other transcript is not the same length.
    pub fn union_transcript(&mut self, other: &PartialTranscript) {
        assert_eq!(
            self.sent.len(),
            other.sent.len(),
            "sent data are not the same length"
        );
        assert_eq!(
            self.received.len(),
            other.received.len(),
            "received data are not the same length"
        );

        for range in other
            .sent_authed
            .0
            .difference(&self.sent_authed.0)
            .iter_ranges()
        {
            self.sent[range.clone()].copy_from_slice(&other.sent[range]);
        }

        for range in other
            .received_authed
            .0
            .difference(&self.received_authed.0)
            .iter_ranges()
        {
            self.received[range.clone()].copy_from_slice(&other.received[range]);
        }

        self.sent_authed = self.sent_authed.union(&other.sent_authed);
        self.received_authed = self.received_authed.union(&other.received_authed);
    }

    /// Unions an authenticated subsequence into this transcript.
    ///
    /// # Panics
    ///
    /// Panics if the subsequence is outside the bounds of the transcript.
    pub fn union_subsequence(&mut self, direction: Direction, seq: &Subsequence) {
        match direction {
            Direction::Sent => {
                seq.copy_to(&mut self.sent);
                self.sent_authed = self.sent_authed.union(&seq.idx);
            }
            Direction::Received => {
                seq.copy_to(&mut self.received);
                self.received_authed = self.received_authed.union(&seq.idx);
            }
        }
    }

    /// Sets all bytes in the transcript which haven't been authenticated.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to set the unauthenticated bytes to
    pub fn set_unauthed(&mut self, value: u8) {
        for range in self.sent_unauthed().iter_ranges() {
            self.sent[range].fill(value);
        }
        for range in self.received_unauthed().iter_ranges() {
            self.received[range].fill(value);
        }
    }

    /// Sets all bytes in the transcript which haven't been authenticated within
    /// the given range.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to set the unauthenticated bytes to
    /// * `range` - The range of bytes to set
    pub fn set_unauthed_range(&mut self, value: u8, direction: Direction, range: Range<usize>) {
        match direction {
            Direction::Sent => {
                for range in range.difference(&self.sent_authed.0).iter_ranges() {
                    self.sent[range].fill(value);
                }
            }
            Direction::Received => {
                for range in range.difference(&self.received_authed.0).iter_ranges() {
                    self.received[range].fill(value);
                }
            }
        }
    }
}

/// The direction of data communicated over a TLS connection.
///
/// This is used to differentiate between data sent from the Prover to the TLS
/// peer, and data received by the Prover from the TLS peer (client or server).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Direction {
    /// Sent from the Prover to the TLS peer.
    Sent = 0x00,
    /// Received by the prover from the TLS peer.
    Received = 0x01,
}

impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Direction::Sent => write!(f, "sent"),
            Direction::Received => write!(f, "received"),
        }
    }
}

/// Transcript index.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Idx(RangeSet<usize>);

impl Idx {
    /// Creates a new index builder.
    pub fn builder() -> IdxBuilder {
        IdxBuilder::default()
    }

    /// Creates an empty index.
    pub fn empty() -> Self {
        Self(RangeSet::default())
    }

    /// Creates a new transcript index.
    pub fn new(ranges: impl Into<RangeSet<usize>>) -> Self {
        Self(ranges.into())
    }

    /// Returns the start of the index.
    pub fn start(&self) -> usize {
        self.0.min().unwrap_or_default()
    }

    /// Returns the end of the index, non-inclusive.
    pub fn end(&self) -> usize {
        self.0.end().unwrap_or_default()
    }

    /// Returns an iterator over the values in the index.
    pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
        self.0.iter()
    }

    /// Returns an iterator over the ranges of the index.
    pub fn iter_ranges(&self) -> impl Iterator<Item = Range<usize>> + '_ {
        self.0.iter_ranges()
    }

    /// Returns the number of values in the index.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the index is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of disjoint ranges in the index.
    pub fn count(&self) -> usize {
        self.0.len_ranges()
    }

    /// Returns the union of this index with another.
    pub fn union(&self, other: &Idx) -> Idx {
        Idx(self.0.union(&other.0))
    }
}

/// Builder for [`Idx`].
#[derive(Debug, Default)]
pub struct IdxBuilder(RangeSet<usize>);

impl IdxBuilder {
    /// Unions ranges.
    pub fn union(self, ranges: &dyn ToRangeSet<usize>) -> Self {
        IdxBuilder(self.0.union(&ranges.to_range_set()))
    }

    /// Builds the index.
    pub fn build(self) -> Idx {
        Idx(self.0)
    }
}

/// Transcript subsequence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "validation::SubsequenceUnchecked")]
pub struct Subsequence {
    /// Index of the subsequence.
    idx: Idx,
    /// Data of the subsequence.
    data: Vec<u8>,
}

impl Subsequence {
    /// Creates a new subsequence.
    pub fn new(idx: Idx, data: Vec<u8>) -> Result<Self, InvalidSubsequence> {
        if idx.len() != data.len() {
            return Err(InvalidSubsequence(
                "index length does not match data length",
            ));
        }

        Ok(Self { idx, data })
    }

    /// Returns the index of the subsequence.
    pub fn index(&self) -> &Idx {
        &self.idx
    }

    /// Returns the data of the subsequence.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Returns the length of the subsequence.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns the inner parts of the subsequence.
    pub fn into_parts(self) -> (Idx, Vec<u8>) {
        (self.idx, self.data)
    }

    /// Copies the subsequence data into the given destination.
    ///
    /// # Panics
    ///
    /// Panics if the subsequence ranges are out of bounds.
    pub(crate) fn copy_to(&self, dest: &mut [u8]) {
        let mut offset = 0;
        for range in self.idx.iter_ranges() {
            dest[range.clone()].copy_from_slice(&self.data[offset..offset + range.len()]);
            offset += range.len();
        }
    }
}

/// Invalid subsequence error.
#[derive(Debug, thiserror::Error)]
#[error("invalid subsequence: {0}")]
pub struct InvalidSubsequence(&'static str);

/// Returns the value ID for each byte in the provided range set.
#[doc(hidden)]
pub fn get_value_ids(direction: Direction, idx: &Idx) -> impl Iterator<Item = String> + '_ {
    let id = match direction {
        Direction::Sent => TX_TRANSCRIPT_ID,
        Direction::Received => RX_TRANSCRIPT_ID,
    };

    idx.iter().map(move |idx| format!("{}/{}", id, idx))
}

mod validation {
    use super::*;

    #[derive(Debug, Deserialize)]
    pub(super) struct SubsequenceUnchecked {
        idx: Idx,
        data: Vec<u8>,
    }

    impl TryFrom<SubsequenceUnchecked> for Subsequence {
        type Error = InvalidSubsequence;

        fn try_from(unchecked: SubsequenceUnchecked) -> Result<Self, Self::Error> {
            Self::new(unchecked.idx, unchecked.data)
        }
    }

    /// Invalid partial transcript error.
    #[derive(Debug, thiserror::Error)]
    #[error("invalid partial transcript: {0}")]
    pub struct InvalidPartialTranscript(&'static str);

    #[derive(Debug, Deserialize)]
    pub(super) struct PartialTranscriptUnchecked {
        sent: Vec<u8>,
        received: Vec<u8>,
        sent_authed: Idx,
        received_authed: Idx,
    }

    impl TryFrom<PartialTranscriptUnchecked> for PartialTranscript {
        type Error = InvalidPartialTranscript;

        fn try_from(unchecked: PartialTranscriptUnchecked) -> Result<Self, Self::Error> {
            if unchecked.sent_authed.end() > unchecked.sent.len()
                || unchecked.received_authed.end() > unchecked.received.len()
            {
                return Err(InvalidPartialTranscript(
                    "authenticated ranges are not in bounds of the data",
                ));
            }

            // Rewrite the data to ensure that unauthenticated data is zeroed out.
            let mut sent = vec![0; unchecked.sent.len()];
            let mut received = vec![0; unchecked.received.len()];

            for range in unchecked.sent_authed.iter_ranges() {
                sent[range.clone()].copy_from_slice(&unchecked.sent[range]);
            }

            for range in unchecked.received_authed.iter_ranges() {
                received[range.clone()].copy_from_slice(&unchecked.received[range]);
            }

            Ok(Self {
                sent,
                received,
                sent_authed: unchecked.sent_authed,
                received_authed: unchecked.received_authed,
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::{fixture, rstest};

    use super::*;

    #[fixture]
    fn transcript() -> Transcript {
        Transcript::new(
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
        )
    }

    #[rstest]
    fn test_transcript_get_subsequence(transcript: Transcript) {
        let subseq = transcript
            .get(Direction::Received, &Idx(RangeSet::from([0..4, 7..10])))
            .unwrap();
        assert_eq!(subseq.data, vec![0, 1, 2, 3, 7, 8, 9]);

        let subseq = transcript
            .get(Direction::Sent, &Idx(RangeSet::from([0..4, 9..12])))
            .unwrap();
        assert_eq!(subseq.data, vec![0, 1, 2, 3, 9, 10, 11]);

        let subseq = transcript.get(
            Direction::Received,
            &Idx(RangeSet::from([0..4, 7..10, 11..13])),
        );
        assert_eq!(subseq, None);

        let subseq = transcript.get(Direction::Sent, &Idx(RangeSet::from([0..4, 7..10, 11..13])));
        assert_eq!(subseq, None);
    }

    #[rstest]
    fn test_transcript_to_partial_success(transcript: Transcript) {
        let partial = transcript.to_partial(Idx::new(0..2), Idx::new(3..7));
        assert_eq!(partial.sent_unsafe(), [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
        assert_eq!(
            partial.received_unsafe(),
            [0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0]
        );
    }

    #[rstest]
    #[should_panic]
    fn test_transcript_to_partial_failure(transcript: Transcript) {
        let _ = transcript.to_partial(Idx::new(0..14), Idx::new(3..7));
    }

    #[rstest]
    fn test_partial_transcript_contains(transcript: Transcript) {
        let partial = transcript.to_partial(Idx::new(0..2), Idx::new(3..7));
        assert!(partial.contains(Direction::Sent, &Idx::new([0..5, 7..10])));
        assert!(!partial.contains(Direction::Received, &Idx::new([4..6, 7..13])))
    }

    #[rstest]
    fn test_partial_transcript_unauthed(transcript: Transcript) {
        let partial = transcript.to_partial(Idx::new(0..2), Idx::new(3..7));
        assert_eq!(partial.sent_unauthed(), Idx::new(2..12));
        assert_eq!(partial.received_unauthed(), Idx::new([0..3, 7..12]));
    }

    #[rstest]
    fn test_partial_transcript_union_success(transcript: Transcript) {
        // Non overlapping ranges.
        let mut simple_partial = transcript.to_partial(Idx::new(0..2), Idx::new(3..7));

        let other_simple_partial = transcript.to_partial(Idx::new(3..5), Idx::new(1..2));

        simple_partial.union_transcript(&other_simple_partial);

        assert_eq!(
            simple_partial.sent_unsafe(),
            [0, 1, 0, 3, 4, 0, 0, 0, 0, 0, 0, 0]
        );
        assert_eq!(
            simple_partial.received_unsafe(),
            [0, 1, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0]
        );
        assert_eq!(simple_partial.sent_authed(), &Idx::new([0..2, 3..5]));
        assert_eq!(simple_partial.received_authed(), &Idx::new([1..2, 3..7]));

        // Overwrite with another partial transcript.

        let another_simple_partial = transcript.to_partial(Idx::new(1..4), Idx::new(6..9));

        simple_partial.union_transcript(&another_simple_partial);

        assert_eq!(
            simple_partial.sent_unsafe(),
            [0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0]
        );
        assert_eq!(
            simple_partial.received_unsafe(),
            [0, 1, 0, 3, 4, 5, 6, 7, 8, 0, 0, 0]
        );
        assert_eq!(simple_partial.sent_authed(), &Idx::new(0..5));
        assert_eq!(simple_partial.received_authed(), &Idx::new([1..2, 3..9]));

        // Overlapping ranges.
        let mut overlap_partial = transcript.to_partial(Idx::new(4..6), Idx::new(3..7));

        let other_overlap_partial = transcript.to_partial(Idx::new(3..5), Idx::new(5..9));

        overlap_partial.union_transcript(&other_overlap_partial);

        assert_eq!(
            overlap_partial.sent_unsafe(),
            [0, 0, 0, 3, 4, 5, 0, 0, 0, 0, 0, 0]
        );
        assert_eq!(
            overlap_partial.received_unsafe(),
            [0, 0, 0, 3, 4, 5, 6, 7, 8, 0, 0, 0]
        );
        assert_eq!(overlap_partial.sent_authed(), &Idx::new([3..5, 4..6]));
        assert_eq!(overlap_partial.received_authed(), &Idx::new([3..7, 5..9]));

        // Equal ranges.
        let mut equal_partial = transcript.to_partial(Idx::new(4..6), Idx::new(3..7));

        let other_equal_partial = transcript.to_partial(Idx::new(4..6), Idx::new(3..7));

        equal_partial.union_transcript(&other_equal_partial);

        assert_eq!(
            equal_partial.sent_unsafe(),
            [0, 0, 0, 0, 4, 5, 0, 0, 0, 0, 0, 0]
        );
        assert_eq!(
            equal_partial.received_unsafe(),
            [0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0]
        );
        assert_eq!(equal_partial.sent_authed(), &Idx::new(4..6));
        assert_eq!(equal_partial.received_authed(), &Idx::new(3..7));

        // Subset ranges.
        let mut subset_partial = transcript.to_partial(Idx::new(4..10), Idx::new(3..11));

        let other_subset_partial = transcript.to_partial(Idx::new(6..9), Idx::new(5..6));

        subset_partial.union_transcript(&other_subset_partial);

        assert_eq!(
            subset_partial.sent_unsafe(),
            [0, 0, 0, 0, 4, 5, 6, 7, 8, 9, 0, 0]
        );
        assert_eq!(
            subset_partial.received_unsafe(),
            [0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10, 0]
        );
        assert_eq!(subset_partial.sent_authed(), &Idx::new(4..10));
        assert_eq!(subset_partial.received_authed(), &Idx::new(3..11));
    }

    #[rstest]
    #[should_panic]
    fn test_partial_transcript_union_failure(transcript: Transcript) {
        let mut partial = transcript.to_partial(Idx::new(4..10), Idx::new(3..11));

        let other_transcript = Transcript::new(
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        );

        let other_partial = other_transcript.to_partial(Idx::new(6..9), Idx::new(5..6));

        partial.union_transcript(&other_partial);
    }

    #[rstest]
    fn test_partial_transcript_union_subseq_success(transcript: Transcript) {
        let mut partial = transcript.to_partial(Idx::new(4..10), Idx::new(3..11));
        let sent_seq = Subsequence::new(Idx::new([0..3, 5..7]), [0, 1, 2, 5, 6].into()).unwrap();
        let recv_seq = Subsequence::new(Idx::new([0..4, 5..7]), [0, 1, 2, 3, 5, 6].into()).unwrap();

        partial.union_subsequence(Direction::Sent, &sent_seq);
        partial.union_subsequence(Direction::Received, &recv_seq);

        assert_eq!(partial.sent_unsafe(), [0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 0, 0]);
        assert_eq!(
            partial.received_unsafe(),
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0]
        );
        assert_eq!(partial.sent_authed(), &Idx::new([0..3, 4..10]));
        assert_eq!(partial.received_authed(), &Idx::new(0..11));

        // Overwrite with another subseq.
        let other_sent_seq = Subsequence::new(Idx::new(0..3), [3, 2, 1].into()).unwrap();

        partial.union_subsequence(Direction::Sent, &other_sent_seq);
        assert_eq!(partial.sent_unsafe(), [3, 2, 1, 0, 4, 5, 6, 7, 8, 9, 0, 0]);
        assert_eq!(partial.sent_authed(), &Idx::new([0..3, 4..10]));
    }

    #[rstest]
    #[should_panic]
    fn test_partial_transcript_union_subseq_failure(transcript: Transcript) {
        let mut partial = transcript.to_partial(Idx::new(4..10), Idx::new(3..11));

        let sent_seq = Subsequence::new(Idx::new([0..3, 13..15]), [0, 1, 2, 5, 6].into()).unwrap();

        partial.union_subsequence(Direction::Sent, &sent_seq);
    }

    #[rstest]
    fn test_partial_transcript_set_unauthed_range(transcript: Transcript) {
        let mut partial = transcript.to_partial(Idx::new(4..10), Idx::new(3..7));

        partial.set_unauthed_range(7, Direction::Sent, 2..5);
        partial.set_unauthed_range(5, Direction::Sent, 0..2);
        partial.set_unauthed_range(3, Direction::Received, 4..6);
        partial.set_unauthed_range(1, Direction::Received, 3..7);

        assert_eq!(partial.sent_unsafe(), [5, 5, 7, 7, 4, 5, 6, 7, 8, 9, 0, 0]);
        assert_eq!(
            partial.received_unsafe(),
            [0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 0]
        );
    }

    #[rstest]
    #[should_panic]
    fn test_subsequence_new_invalid_len() {
        let _ = Subsequence::new(Idx::new([0..3, 5..8]), [0, 1, 2, 5, 6].into()).unwrap();
    }

    #[rstest]
    #[should_panic]
    fn test_subsequence_copy_to_invalid_len() {
        let seq = Subsequence::new(Idx::new([0..3, 5..7]), [0, 1, 2, 5, 6].into()).unwrap();

        let mut data: [u8; 3] = [0, 1, 2];
        seq.copy_to(&mut data);
    }
}