wolf_crypto/mac/poly1305/
mod.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
//! The `Poly1305` Message Authentication Code
//!
//! ```
//! use wolf_crypto::mac::{Poly1305, poly1305::Key};
//!
//! # fn main() -> Result<(), wolf_crypto::Unspecified> {
//! let key = Key::new([0u8; 32]);
//!
//! let tag = Poly1305::new(key.as_ref())
//!     .update(b"hello world")?
//!     .finalize();
//!
//! let o_tag = Poly1305::new(key)
//!     .update(b"Different message")?
//!     .finalize();
//!
//! assert_eq!(
//!     tag, o_tag,
//!     "All of our coefficients are zero!"
//! );
//!
//! let key = Key::new([42u8; 32]);
//!
//! let tag = Poly1305::new(key.as_ref())
//!     .update_ct(b"thankfully this ")
//!     .update_ct(b"is only the case ")
//!     .update_ct(b"with a key of all zeroes.")
//!     .finalize(/* errors are accumulated in constant-time, so we handle them here */)?;
//!
//! let o_tag = Poly1305::new(key.as_ref())
//!     .mac(b"thankfully this is only the case with a key of all zeroes.", ())?;
//!
//! assert_eq!(tag, o_tag);
//!
//! let bad_tag = Poly1305::new(key)
//!     .update(b"This tag will not be the same.")?
//!     .finalize();
//!
//! assert_ne!(bad_tag, tag);
//! # Ok(()) }
//! ```
//!
//! ## Note
//!
//! The first test may be concerning, it is not. `Poly1305` was originally designed to be
//! [paired with `AES`][1], this example only would take place if the cipher it is paired with
//! is fundamentally broken. More explicitly, the cipher would need to be an identity function for
//! the first 32 bytes, meaning not encrypt the first 32 bytes in any way shape or form.
//!
//! The author of `Poly1305` ([Daniel J. Bernstein][2]) also created [`Salsa20` (`Snuffle 2005`)][3],
//! and then [`ChaCha`][4], which `Poly1305` generally complements for authentication.
//!
//! ## Security
//!
//! `Poly1305` is meant to be used with a **one-time key**, key reuse in `Poly1305` can be
//! devastating. When pairing with something like [`ChaCha20Poly1305`] this requirement is handled
//! via the discreteness of the initialization vector (more reason to never reuse initialization
//! vectors).
//!
//! If you are using `Poly1305` directly, each discrete message you authenticate must leverage
//! fresh key material.
//!
//! [1]: https://cr.yp.to/mac/poly1305-20050329.pdf
//! [2]: https://cr.yp.to/djb.html
//! [3]: https://cr.yp.to/snuffle.html
//! [4]: https://cr.yp.to/chacha/chacha-20080128.pdf
//! [`ChaCha20Poly1305`]: crate::aead::ChaCha20Poly1305


use wolf_crypto_sys::{
    Poly1305 as wc_Poly1305,
    wc_Poly1305SetKey, wc_Poly1305Update, wc_Poly1305Final,
    wc_Poly1305_Pad, wc_Poly1305_EncodeSizes,
    wc_Poly1305_MAC
};

mod key;
pub mod state;

pub use key::{GenericKey, Key, KeyRef, KEY_SIZE};
use key::KEY_SIZE_U32;

use core::mem::MaybeUninit;
use core::ptr::addr_of_mut;
use state::{Poly1305State, Init, Ready, Streaming};
use crate::opaque_res::Res;
use crate::{can_cast_u32, to_u32, Unspecified};
use core::marker::PhantomData;
use crate::aead::{Aad, Tag};
use crate::ct;

// INFALLIBILITY COMMENTARY
//
// — poly1305_blocks
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L277
//
// Only can fail under SMALL_STACK /\ W64WRAPPER via OOM. We do not enable either of these
// features, and both must be enabled for this to be fallible.
//
// — poly1305_block
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L483
//
// Returns 0 OR returns the result of poly1305_blocks. Which again is infallible unless the
// aforementioned features are both enabled.
//
// — wc_Poly1305SetKey
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L496
//
// Only can fail if these preconditions are not met:
//
//   key != null /\ KeySz == 32 /\ ctx != null
//
// Which our types guarantee this is satisfied.
//
// — wc_Poly1305Final
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L584
//
// Only can fail if these preconditions are not met:
//
//   ctx != null /\ mac != null
//
// With an implicit, unchecked precondition (observed in the wc_Poly1305_MAC function)
//
//   macSz == 16
//
// Which, again, our types guarantee this precondition is satisfied.
//
// — wc_Poly1305Update
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L794
//
// This depends on the infallibility of poly1305_blocks, which we have already showed
// is infallible.
//
// So, this can only fail if the following preconditions are not met:
//
//  ctx != null /\ (bytes > 0 -> bytes != null)
//
// Which again, our types guarantee this is satisfied.
//
// — wc_Poly1305_Pad (invoked in finalize)
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L913
//
// This depends on the success of wc_Poly1305Update, which we have already shown to be
// infallible.
//
// This is only fallible if the provided ctx is null, which again our types are not
// able to represent.
//
// Regarding the wc_Poly1305Update invocation, this is clearly infallible.
//
// We have this:
//   paddingLen = (-(int)lenToPad) & (WC_POLY1305_PAD_SZ - 1);
//
// Where they are just computing the compliment of lenToPad, masking it against 15, which gives
// us the offset to 16 byte alignment.
// For example, let's say our length to pad is 13 (for ease of reading over a single octet):
//   13 to -13     (00001101 to 11110011)
//   -13 & 15 to 3 (11110011 & 00001111 to 00000011)
//
// For all values, this will never exceed 15 bytes, which is what is the amount of padding living
// on the stack. Again, this usage of wc_Poly1305Update is clearly infallible with our
// configuration.
//
// — wc_Poly1305_EncodeSizes (invoked in finalize)
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L941
//
// Similar to wc_Poly1305_Pad, this depends on the infallibility of wc_Poly1305Update. Which again,
// in this circumstance is infallible. The usage within this function is infallible with our
// configuration of wolfcrypt. The only precondition again is ctx being non-null, which again
// is guaranteed via our types.
//
// — wc_Poly1305_MAC
//
// SRC: https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/poly1305.c#L995
//
// Building on the above commentary, this is infallible as well.
//
// We have the precondition:
//
//   ctx != null /\ input != null /\ tag != null /\ tagSz >= 16
//     /\ (additionalSz != 0 -> additional != null)
//
// Which again, our types ensure that this is satisfied.
//   #1 ctx must not be null as we would never be able to invoke this function otherwise.
//   #2 input must not be null, this is guaranteed via Rust's type system.
//   #3 Our Tag type is never null, and the size of Tag is always 16/
//   #4 Our Aad trait ensures that if the size is non-zero that the ptr method never returns a
//      null pointer.
//
// END COMMENTARY


/// The `Poly1305` Message Authentication Code (MAC)
///
/// # Example
///
/// ```
/// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
///
/// let key: Key = [7u8; 32].into();
///
/// let tag = Poly1305::new(key.as_ref())
///     .update_ct(b"hello world")
///     .update_ct(b", how are you")
///     .finalize()
///     .unwrap();
///
/// let o_tag = Poly1305::new(key.as_ref())
///     .mac(b"hello world, how are you", b"")
///     .unwrap();
///
/// assert_eq!(tag, o_tag);
/// ```
#[repr(transparent)]
pub struct Poly1305<State: Poly1305State = Init> {
    inner: wc_Poly1305,
    _state: PhantomData<State>
}

impl<State: Poly1305State> From<Poly1305<State>> for Unspecified {
    #[inline]
    fn from(value: Poly1305<State>) -> Self {
        drop(value);
        Unspecified
    }
}

opaque_dbg! { Poly1305 }

impl Poly1305<Init> {
    /// Creates a new `Poly1305` instance with the provided key.
    ///
    /// # Arguments
    ///
    /// * `key` - The secret key material used for MAC computation.
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::mac::{Poly1305, poly1305::Key};
    ///
    /// let key: Key = [42u8; 32].into();
    /// let poly = Poly1305::new(key.as_ref());
    /// ```
    pub fn new<K: GenericKey>(key: K) -> Poly1305<Ready> {
        let mut poly1305 = MaybeUninit::<wc_Poly1305>::uninit();

        unsafe {
            // infallible, see commentary at start of file.
            let _res = wc_Poly1305SetKey(
                poly1305.as_mut_ptr(),
                key.ptr(),
                KEY_SIZE_U32
            );

            debug_assert_eq!(_res, 0);

            Poly1305::<Ready> {
                inner: poly1305.assume_init(),
                _state: PhantomData
            }
        }
    }
}

impl<State: Poly1305State> Poly1305<State> {
    /// Transitions the `Poly1305` instance to a new state.
    ///
    /// # Type Parameters
    ///
    /// * `N` - The new state type.
    ///
    /// # Returns
    ///
    /// A `Poly1305` instance in the new state.
    #[inline]
    const fn with_state<N: Poly1305State>(self) -> Poly1305<N> {
        unsafe { core::mem::transmute(self) }
    }

    /// Updates the `Poly1305` instance with additional input without performing checks.
    ///
    /// # Safety
    ///
    /// The length of the input must not be truncated / overflow a `u32`.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the data to include in the MAC computation.
    #[inline]
    unsafe fn update_unchecked(&mut self, input: &[u8]) {
        // infallible, see commentary at beginning of file.
        let _res = wc_Poly1305Update(
            addr_of_mut!(self.inner),
            input.as_ptr(),
            input.len() as u32
        );

        debug_assert_eq!(_res, 0);
    }
}

impl Poly1305<Ready> {
    /// Computes the MAC for the given input and additional data without performing input length checks.
    ///
    /// # Safety
    ///
    /// Both the `input` and `additional` arguments length must be less than `u32::MAX`.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the message to authenticate.
    /// * `additional` - A byte slice representing optional additional authenticated data (AAD).
    ///
    /// # Returns
    ///
    /// The associated authentication tag.
    unsafe fn mac_unchecked<A: Aad>(mut self, input: &[u8], aad: A) -> Tag {
        debug_assert!(can_cast_u32(input.len()));
        debug_assert!(aad.is_valid_size());

        let mut tag = Tag::new_zeroed();

        // Infallible, see final section of commentary at beginning of file.
        let _res = wc_Poly1305_MAC(
            addr_of_mut!(self.inner),
            aad.ptr(),
            aad.size(),
            input.as_ptr(),
            input.len() as u32,
            tag.as_mut_ptr(),
            Tag::SIZE
        );

        assert_eq!(_res, 0);

        debug_assert_eq!(_res, 0);

        tag
    }

    /// Computes the MAC for the given input and additional data.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the message to authenticate.
    /// * `aad` - Any additional authenticated data.
    ///
    /// # Returns
    ///
    /// The associated authentication tag.
    ///
    /// # Errors
    ///
    /// - The length of the `aad` is greater than [`u32::MAX`].
    /// - The length of the `input` is greater than [`u32::MAX`].
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// let key: Key = [42u8; 32].into();
    /// let tag = Poly1305::new(key.as_ref())
    ///     .mac(b"message", b"aad")
    ///     .unwrap();
    /// # assert_ne!(tag, Tag::new_zeroed());
    /// ```
    #[inline]
    pub fn mac<A: Aad>(self, input: &[u8], aad: A) -> Result<Tag, Unspecified> {
        if can_cast_u32(input.len()) && aad.is_valid_size() {
            Ok(unsafe { self.mac_unchecked(input, aad) })
        } else {
            Err(Unspecified)
        }
    }

    /// Updates the `Poly1305` instance with additional input, transitioning it to a streaming
    /// state.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the data to include in the MAC computation.
    ///
    /// # Returns
    ///
    /// A `StreamPoly1305` instance for continued updates.
    ///
    /// # Errors
    ///
    /// If the length of `input` is greater than [`u32::MAX`].
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// # fn main() -> Result<(), wolf_crypto::Unspecified> {
    /// let key: Key = [42u8; 32].into();
    /// let stream = Poly1305::new(key.as_ref())
    ///     .update(b"chunk1")?
    ///     .update(b"chunk2")?;
    /// # Ok(()) }
    /// ```
    #[inline]
    pub fn update(mut self, input: &[u8]) -> Result<StreamPoly1305, Unspecified> {
        if let Some(input_len) = to_u32(input.len()) {
            unsafe { self.update_unchecked(input) };
            Ok(StreamPoly1305::from_parts(self.with_state(), input_len))
        } else {
            Err(Unspecified)
        }
    }

    /// Updates the `Poly1305` instance with additional input in a constant-time manner.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the data to include in the MAC computation.
    ///
    /// # Returns
    ///
    /// A `CtPoly1305` instance containing the updated state.
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// let key: Key = [42u8; 32].into();
    /// let ct_poly = Poly1305::new(key)
    ///     .update_ct(b"sensitive ")
    ///     .update_ct(b"chunks")
    ///     .finalize()
    ///     .unwrap();
    ///
    /// dbg!(ct_poly);
    /// assert_ne!(ct_poly, Tag::new_zeroed());
    /// ```
    pub fn update_ct(mut self, input: &[u8]) -> CtPoly1305 {
        let (adjusted, res) = CtPoly1305::adjust_slice(input);
        unsafe { self.update_unchecked(adjusted) };
        CtPoly1305::from_parts(self.with_state(), res, adjusted.len() as u32)
    }
}

/// Finalizes the `Poly1305` MAC computation.
///
/// # Arguments
///
/// * `res` - The current `Res` state.
/// * `poly` - The `Poly1305` instance.
/// * `accum_len` - The accumulated length of the input data.
///
/// # Returns
///
/// A `Result<Tag, Unspecified>` containing the computed `Tag` on success or an `Unspecified` error
/// on failure.
#[inline]
fn finalize<S: Poly1305State>(mut poly: Poly1305<S>, accum_len: u32) -> Tag {
    // Regarding fallibility for all functions invoked, and debug_asserted to have succeeded,
    // see the commentary at the beginning of the document.
    unsafe {
        let mut tag = Tag::new_zeroed();

        let _res = wc_Poly1305_Pad(
            addr_of_mut!(poly.inner),
            accum_len
        );

        debug_assert_eq!(_res, 0);

        let _res = wc_Poly1305_EncodeSizes(
            addr_of_mut!(poly.inner),
            0u32,
            accum_len
        );

        debug_assert_eq!(_res, 0);

        let _res = wc_Poly1305Final(
            addr_of_mut!(poly.inner),
            tag.as_mut_ptr()
        );

        debug_assert_eq!(_res, 0);

        tag
    }
}

/// Represents an ongoing streaming MAC computation, allowing incremental updates.
///
/// # Example
///
/// ```
/// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
///
/// # fn main() -> Result<(), wolf_crypto::Unspecified> {
/// let key: Key = [42u8; 32].into();
/// let tag = Poly1305::new(key.as_ref())
///     .update(b"chunk1")?
///     .update(b"chunk2")?
///     .update(b"chunk3")?
///     .finalize();
/// # Ok(()) }
/// ```
pub struct StreamPoly1305 {
    poly1305: Poly1305<Streaming>,
    accum_len: u32
}

impl From<StreamPoly1305> for Unspecified {
    #[inline]
    fn from(value: StreamPoly1305) -> Self {
        value.poly1305.into()
    }
}

opaque_dbg! { StreamPoly1305 }

impl StreamPoly1305 {
    /// Creates a new `StreamPoly1305` instance from its parts.
    ///
    /// # Arguments
    ///
    /// * `poly1305` - The `Poly1305` instance in the `Streaming` state.
    /// * `accum_len` - The accumulated length of the input data.
    ///
    /// # Returns
    ///
    /// A new `StreamPoly1305` instance.
    const fn from_parts(poly1305: Poly1305<Streaming>, accum_len: u32) -> Self {
        Self { poly1305, accum_len }
    }

    /// Increments the accumulated length with the provided length.
    ///
    /// # Arguments
    ///
    /// * `len` - The length to add to the accumulator.
    ///
    /// # Returns
    ///
    /// A `Res` indicating the success or failure of the operation.
    #[inline(always)]
    fn incr_accum(&mut self, len: u32) -> Res {
        let (accum_len, res) = ct::add_no_wrap(self.accum_len, len);
        self.accum_len = accum_len;
        res
    }

    /// Updates the streaming MAC computation with additional input.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the additional data to include.
    ///
    /// # Errors
    ///
    /// - The length of the `input` was greater than [`u32::MAX`].
    /// - The total length that has been processed is greater than [`u32::MAX`],
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// # fn main() -> Result<(), wolf_crypto::Unspecified> {
    /// let key: Key = [42u8; 32].into();
    ///
    /// let tag = Poly1305::new(key.as_ref())
    ///     .update(b"chunk1")?
    ///     .update(b"chunk2")?
    ///     .update(b"chunk3")?
    ///     .finalize();
    /// # Ok(()) }
    /// ```
    pub fn update(mut self, input: &[u8]) -> Result<Self, Self> {
        if let Some(input_len) = to_u32(input.len()) {
            into_result!(self.incr_accum(input_len),
                ok => {
                    // We MUST only invoke this AFTER knowing that the incr_accum succeeded.
                    // incr_accum uses the ct_add_no_wrap function, which may sound like it performs
                    // some form of saturating addition, but it does not. If the operation would
                    // overflow, no addition would take place. So, we can return self under the
                    // error case, and the state will not be corrupted.
                    unsafe { self.poly1305.update_unchecked(input) };
                    self
                },
                err => self
            )
        } else {
            Err(self)
        }
    }

    /// Finalizes the streaming MAC computation and returns the resulting `Tag`.
    ///
    /// # Returns
    ///
    /// A `Result<Tag, Unspecified>` containing the computed `Tag` on success or an `Unspecified` error on failure.
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// # fn main() -> Result<(), wolf_crypto::Unspecified> {
    /// let key: Key = [42u8; 32].into();
    ///
    /// let tag = Poly1305::new(key.as_ref())
    ///     .update(b"chunk1")?
    ///     .update(b"chunk2")?
    ///     .update(b"chunk3")?
    ///     .finalize();
    /// # Ok(()) }
    /// ```
    pub fn finalize(self) -> Tag {
        finalize(self.poly1305, self.accum_len)
    }
}

/// Provides a constant-time interface for updating the MAC computation, enhancing resistance
/// against side-channel attacks.
///
/// # Example
///
/// ```
/// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
///
/// let key: Key = [42u8; 32].into();
/// let ct_poly = Poly1305::new(key.as_ref())
///     .update_ct(b"constant time ")
///     .update_ct(b"chunk")
///     .finalize()
///     .unwrap();
/// ```
#[must_use]
pub struct CtPoly1305 {
    poly1305: Poly1305<Streaming>,
    result: Res,
    accum_len: u32
}

opaque_dbg! { CtPoly1305 }

impl CtPoly1305 {
    /// Creates a new `CtPoly1305` instance from its parts.
    ///
    /// # Arguments
    ///
    /// * `poly1305` - The `Poly1305` instance in the `Streaming` state.
    /// * `result` - The current `Res` state.
    /// * `accum_len` - The accumulated length of the input data.
    ///
    /// # Returns
    ///
    /// A new `CtPoly1305` instance.
    const fn from_parts(poly1305: Poly1305<Streaming>, result: Res, accum_len: u32) -> Self {
        Self {
            poly1305,
            result,
            accum_len
        }
    }

    /// Increments the accumulated length with the provided length without wrapping on overflow.
    ///
    /// # Arguments
    ///
    /// * `len` - The length to add to the accumulator.
    ///
    /// # Returns
    ///
    /// `Res` indicating if the operation would have overflowed the internal length.
    #[inline(always)]
    fn incr_accum(&mut self, len: u32) -> Res {
        let (accum_len, res) = ct::add_no_wrap(self.accum_len, len);
        self.accum_len = accum_len;
        res
    }

    /// Creates a mask based on the slice length for constant-time adjustments.
    ///
    /// # Arguments
    ///
    /// * `len` - The length of the slice.
    ///
    /// # Returns
    ///
    /// If the length of the slice is greater than [`u32::MAX`] this will return all zeroes,
    /// otherwise this will return all ones.
    #[inline(always)]
    const fn slice_len_mask(len: usize) -> usize {
        (can_cast_u32(len) as usize).wrapping_neg()
    }

    /// Adjusts the input slice based on the mask to ensure constant-time operations.
    ///
    /// # Arguments
    ///
    /// * `slice` - The input byte slice to adjust.
    ///
    /// # Returns
    ///
    /// A tuple containing the adjusted slice and the resulting `Res` state.
    #[inline(always)]
    fn adjust_slice(slice: &[u8]) -> (&[u8], Res) {
        let mask = Self::slice_len_mask(slice.len());

        // So, of course, this isn't pure constant time. It has variable timing for lengths,
        // though so does poly1305, and practically everything. Only way to avoid this is masking
        // the computation which will never be perfect.
        //
        // Though, it does allow us to not need any early exit, the position of this error across
        // multiple updates is not leaked via timing.
        //
        // So, there is variance in timing under this error yes, but this is given as at some point
        // (finalize) there must be some branch to ensure the operation was successful and that
        // the authentication code genuinely corresponds to the provided messages. With this
        // approach there is a **reduction** in timing leakage, not a complete elimination of it.
        (&slice[..(slice.len() & mask)], Res(mask != 0))
    }

    /// Adds more data to the constant-time streaming MAC computation.
    ///
    /// # Arguments
    ///
    /// * `input` - A byte slice representing the additional data to include.
    ///
    /// # Returns
    ///
    /// The updated `CtPoly1305` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// let key: Key = [42u8; 32].into();
    /// let ct_poly = Poly1305::new(key.as_ref())
    ///     .update_ct(b"chunk1")
    ///     .update_ct(b"chunk2")
    ///     .finalize()
    ///     .unwrap();
    /// ```
    pub fn update_ct(mut self, input: &[u8]) -> Self {
        let (adjusted, mut res) = Self::adjust_slice(input);
        res.ensure(self.incr_accum(adjusted.len() as u32));

        unsafe { self.poly1305.update_unchecked(input) };

        self.result.ensure(res);
        self
    }

    /// Returns `true` if no errors have been encountered to this point.
    #[must_use]
    pub const fn is_ok(&self) -> bool {
        self.result.is_ok()
    }

    /// Returns `true` if an error has been encountered at some point.
    #[must_use]
    pub const fn is_err(&self) -> bool {
        self.result.is_err()
    }

    /// Finalizes the constant-time streaming MAC computation and returns the resulting `Tag`.
    ///
    /// # Returns
    ///
    /// The associated authentication tag representing all updates and the total length of the
    /// updates.
    ///
    /// # Errors
    ///
    /// The `CtPoly1305` instance accumulates errors throughout the updating process without
    /// branching. There are two ways that this will return an error based on prior updates:
    ///
    /// - One of the provided inputs had a length which was greater than [`u32::MAX`].
    /// - The total length, accumulated from all inputs, is greater than [`u32::MAX`].
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// let key: Key = [42u8; 32].into();
    /// let tag = Poly1305::new(key.as_ref())
    ///     .update_ct(b"chunk1")
    ///     .update_ct(b"chunk2")
    ///     .finalize()
    ///     .unwrap();
    /// ```
    pub fn finalize(self) -> Result<Tag, Unspecified> {
        let tag = finalize(self.poly1305, self.accum_len);
        self.result.unit_err(tag)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn smoke() {
        let key: Key = [69; 32].into();
        let tag = Poly1305::new(key.as_ref())
            .update_ct(b"hello world")
            .update_ct(b"good day to you")
            .update_ct(b"mmm yes mm yes indeed mm")
            .update_ct(b"hmm...")
            .finalize()
            .unwrap();

        let o_tag = Poly1305::new(key.as_ref())
            .mac(b"hello worldgood day to yoummm yes mm yes indeed mmhmm...", b"")
            .unwrap();

        assert_eq!(tag, o_tag);
    }
}