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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
//! 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())
//!     .aead_padding()
//!     .update(b"hello world")?
//!     .finalize();
//!
//! let o_tag = Poly1305::new(key)
//!     .mac(b"Different message", ()).unwrap();
//!
//! assert_eq!(
//!     tag, o_tag,
//!     "All of our coefficients are zero!"
//! );
//!
//! let key = Key::new([42u8; 32]);
//!
//! let tag = Poly1305::new(key.as_ref())
//!     .aead_padding_ct()
//!     .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())
///     .aead_padding_ct()
///     .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 {
        Self
    }
}

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. This uses the TLS AEAD padding
    /// scheme. If this is undesirable, consider calling `update` followed by `finalize` manually.
    ///
    /// # 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)
        }
    }

    /// Transitions the `Poly1305` instance into the streaming state with the TLS AEAD padding
    /// scheme.
    ///
    /// # Returns
    ///
    /// A [`StreamPoly1305Aead`] instance for continued updates.
    ///
    /// # 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())
    ///     .aead_padding()
    ///     .update(b"chunk1")?
    ///     .update(b"chunk2")?;
    /// # Ok(()) }
    /// ```
    pub const fn aead_padding(self) -> StreamPoly1305Aead {
        StreamPoly1305Aead::from_parts(self.with_state(), 0)
    }

    /// Transitions the `Poly1305` instance into the streaming state.
    ///
    /// # Returns
    ///
    /// A [`StreamPoly1305`] instance for continued updates.
    ///
    /// # 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()).normal()
    ///     .update(b"chunk1")?
    ///     .update(b"chunk2")?;
    /// # Ok(()) }
    /// ```
    pub const fn normal(self) -> StreamPoly1305 {
        StreamPoly1305::from_parts(self.with_state(), 0)
    }

    /// Transitions the `Poly1305` instance into the streaming state with the TLS AEAD padding
    /// scheme.
    ///
    /// The distinction between this and the standard [`aead_padding`] is that this accumulates
    /// errors up until the point of finalization in constant time.
    ///
    /// # Returns
    ///
    /// A [`CtPoly1305Aead`] instance for continued updates.
    ///
    /// # 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())
    ///     .aead_padding_ct()
    ///     .update_ct(b"chunk1")
    ///     .update_ct(b"chunk2");
    /// # Ok(()) }
    /// ```
    ///
    /// [`aead_padding`]: Self::aead_padding
    pub const fn aead_padding_ct(self) -> CtPoly1305Aead {
        CtPoly1305Aead::from_parts(self.with_state(), Res::OK, 0)
    }

    /// Transitions the `Poly1305` instance into the streaming state.
    ///
    /// The distinction between this and the standard [`normal`] is that this accumulates
    /// errors up until the point of finalization in constant time.
    ///
    /// # Returns
    ///
    /// A [`CtPoly1305`] instance for continued updates.
    ///
    /// # 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()).normal_ct()
    ///     .update_ct(b"chunk1")
    ///     .update_ct(b"chunk2");
    /// # Ok(()) }
    /// ```
    ///
    /// [`normal`]: Self::normal
    pub const fn normal_ct(self) -> CtPoly1305 {
        CtPoly1305::from_parts(self.with_state(), Res::OK, 0)
    }

    /// 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> {
        to_u32(input.len()).map_or(
            Err(Unspecified), 
            |len| unsafe {
                self.update_unchecked(input);
                Ok(StreamPoly1305::from_parts(self.with_state(), len))
            }
        )
    }

    /// 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 tag = Poly1305::new(key.as_ref())
    ///     .update_ct(b"sensitive ")
    ///     .update_ct(b"chunks")
    ///     .finalize()
    ///     .unwrap();
    ///
    /// let o_tag = Poly1305::new(key.as_ref())
    ///     .update_ct(b"sensitive chunks")
    ///     .finalize().unwrap();
    ///
    /// assert_eq!(tag, o_tag);
    /// ```
    pub fn update_ct(mut self, input: &[u8]) -> CtPoly1305 {
        let (adjusted, res) = adjust_slice(input);
        unsafe { self.update_unchecked(adjusted) };
        // adjusted length will always be below u32::MAX
        CtPoly1305::from_parts(self.with_state(), res, adjusted.len() as u32)
    }
}

/// Finalizes the `Poly1305` MAC computation using the TLS AEAD padding scheme.
///
/// # Arguments
///
/// * `poly` - The `Poly1305` instance.
/// * `accum_len` - The accumulated length of the input data.
///
/// # Returns
///
/// The associated authentication [`Tag`].
#[inline]
fn finalize_aead<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 _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);

        finalize_no_pad(poly)
    }
}

/// Finalizes the `Poly1305` MAC computation with padding.
///
/// # Arguments
///
/// * `poly` - The `Poly1305` instance.
/// * `to_pad` - Either the length of the input, or the accumulated output of [`update_to_pad`].
///
/// # Returns
///
/// The associated authentication [`Tag`].
#[inline]
fn finalize<S: Poly1305State>(mut poly: Poly1305<S>, to_pad: u32) -> Tag {
    unsafe {
        let _res = wc_Poly1305_Pad(
            addr_of_mut!(poly.inner),
            to_pad
        );

        debug_assert_eq!(_res, 0);

        finalize_no_pad(poly)
    }
}

/// Finalizes the `Poly1305` MAC computation without padding.
///
/// # Arguments
///
/// * `poly` - The `Poly1305` instance.
///
/// # Returns
///
/// The associated authentication [`Tag`].
#[inline]
fn finalize_no_pad<S: Poly1305State>(mut poly: Poly1305<S>) -> Tag {
    unsafe {
        let mut tag = Tag::new_zeroed();

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

        debug_assert_eq!(_res, 0);

        tag
    }
}

#[inline(always)]
#[must_use]
const fn update_to_pad(to_pad: u8, new_len: u32) -> u8 {
    // this is the same as (num + num) & 15, where num is a number of any possible size, not bound
    // to a concrete type like u32.

    // With wolfcrypt's padding algorithm this will always result in the same output as providing
    // the total length. See kani verification at the bottom of the file.
    to_pad.wrapping_add((new_len & 15) as u8) & 15
}

/// Represents an ongoing streaming MAC computation, allowing incremental updates.
///
/// This uses the TLS AEAD padding scheme.
///
/// # 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())
///     .aead_padding()
///     .update(b"chunk1")?
///     .update(b"chunk2")?
///     .update(b"chunk3")?
///     .finalize();
/// # Ok(()) }
/// ```
pub struct StreamPoly1305Aead {
    poly1305: Poly1305<Streaming>,
    accum_len: u32
}

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

opaque_dbg! { StreamPoly1305Aead }

impl StreamPoly1305Aead {
    /// 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())
    ///     .aead_padding()
    ///     .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
    ///
    /// The associated authentication [`Tag`].
    ///
    /// # 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())
    ///     .aead_padding()
    ///     .update(b"chunk1")?
    ///     .update(b"chunk2")?
    ///     .update(b"chunk3")?
    ///     .finalize();
    /// # Ok(()) }
    /// ```
    pub fn finalize(self) -> Tag {
        finalize_aead(self.poly1305, self.accum_len)
    }
}

/// 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>,
    to_pad: u8
}

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>, len: u32) -> Self {
        Self { poly1305, to_pad: update_to_pad(0, len) }
    }

    /// 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`].
    ///
    /// # 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(len) = to_u32(input.len()) {
            self.to_pad = update_to_pad(self.to_pad, len);
            unsafe { self.poly1305.update_unchecked(input) };
            Ok(self)
        } else {
            Err(self)
        }
    }

    /// Finalizes the streaming MAC computation and returns the resulting `Tag`.
    ///
    /// # Returns
    ///
    /// The associated authentication [`Tag`].
    ///
    /// # 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(()) }
    /// ```
    #[inline]
    pub fn finalize(self) -> Tag {
        finalize(self.poly1305, self.to_pad as u32)
    }

    /// Finalizes the constant-time streaming MAC computation and returns the resulting `Tag`.
    ///
    /// # Note
    ///
    /// It is far more common in practice to use to pad the [`finalize`] method. This is only here
    /// `XSalsa20Poly1305`.
    ///
    /// # Returns
    ///
    /// The associated authentication [`Tag`] representing all updates and the total length of the
    /// updates.
    ///
    /// # Example
    ///
    /// ```
    /// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
    ///
    /// let key: Key = [42u8; 32].into();
    /// let tag = Poly1305::new(key.as_ref())
    ///     .update(b"chunk1").unwrap()
    ///     .update(b"chunk2").unwrap()
    ///     .finalize_no_padding();
    /// ```
    ///
    /// [`finalize`]: Self::finalize
    #[inline]
    pub fn finalize_no_padding(self) -> Tag {
        finalize_no_pad(self.poly1305)
    }
}

/// Provides a constant-time interface for updating the MAC computation, enhancing resistance
/// against side-channel attacks.
///
/// This uses the recent TLS AEAD padding scheme on finalization, if this is not desired see
/// [`CtPoly1305`].
///
/// # Example
///
/// ```
/// use wolf_crypto::{mac::{Poly1305, poly1305::Key}, aead::Tag};
///
/// let key: Key = [42u8; 32].into();
/// let ct_poly = Poly1305::new(key.as_ref())
///     .aead_padding_ct()
///     .update_ct(b"constant time ")
///     .update_ct(b"chunk")
///     .finalize()
///     .unwrap();
/// ```
#[must_use]
pub struct CtPoly1305Aead {
    poly1305: Poly1305<Streaming>,
    result: Res,
    accum_len: u32
}

opaque_dbg! { CtPoly1305Aead }

/// 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)]
#[must_use]
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 = 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))
}

impl CtPoly1305Aead {
    /// 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
    }

    /// 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())
    ///     .aead_padding_ct()
    ///     .update_ct(b"chunk1")
    ///     .update_ct(b"chunk2")
    ///     .finalize()
    ///     .unwrap();
    /// ```
    pub fn update_ct(mut self, input: &[u8]) -> Self {
        let (adjusted, mut res) = adjust_slice(input);
        res.ensure(self.incr_accum(adjusted.len() as u32));

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

        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())
    ///     .aead_padding_ct()
    ///     .update_ct(b"chunk1")
    ///     .update_ct(b"chunk2")
    ///     .finalize()
    ///     .unwrap();
    /// ```
    pub fn finalize(self) -> Result<Tag, Unspecified> {
        let tag = finalize_aead(self.poly1305, self.accum_len);
        self.result.unit_err(tag)
    }
}

/// 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,
    to_pad: u8
}

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.
    /// * `len` - The length of the input data. Used to compute the amount needed for padding
    ///   overtime.
    ///
    /// # Returns
    ///
    /// A new `CtPoly1305` instance.
    const fn from_parts(poly1305: Poly1305<Streaming>, result: Res, len: u32) -> Self {
        Self {
            poly1305,
            result,
            to_pad: update_to_pad(0, len)
        }
    }

    /// 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, res) = adjust_slice(input);

        // adjusted length will always be less than u32::MAX
        self.to_pad = update_to_pad(self.to_pad, adjusted.len() as u32);

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

        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. The only error which could occur:
    ///
    /// One of the provided inputs had a length which was 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.to_pad as u32);
        self.result.unit_err(tag)
    }

    /// Finalizes the constant-time streaming MAC computation and returns the resulting `Tag`.
    ///
    /// # Note
    ///
    /// It is far more common in practice to use to pad the [`finalize`] method. This is only here
    /// `XSalsa20Poly1305`.
    ///
    /// # 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. The only error which could occur:
    ///
    /// One of the provided inputs had a length which was 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_no_padding()
    ///     .unwrap();
    /// ```
    ///
    /// [`finalize`]: Self::finalize
    pub fn finalize_no_padding(self) -> Result<Tag, Unspecified> {
        let tag = finalize_no_pad(self.poly1305);
        self.result.unit_err(tag)
    }
}

#[cfg(test)]
use poly1305::universal_hash::generic_array::{GenericArray, ArrayLength};

#[cfg(test)]
const fn rc_to_blocks<T, N: ArrayLength<T>>(data: &[T]) -> (&[GenericArray<T, N>], &[T]) {
    let nb = data.len() / N::USIZE;
    let (left, right) = data.split_at(nb * N::USIZE);
    let p = left.as_ptr().cast::<GenericArray<T, N>>();
    // SAFETY: we guarantee that `blocks` does not point outside `data`
    // and `p` is valid for reads
    #[allow(unsafe_code)]
    let blocks = unsafe { core::slice::from_raw_parts(p, nb) };
    (blocks, right)
}

#[cfg(test)]
use poly1305::{Poly1305 as rc_Poly1305, universal_hash::{KeyInit, UniversalHash}};

#[cfg(test)]
fn construct_polys(key: [u8; 32]) -> (rc_Poly1305, Poly1305<Ready>) {
    let rc_key = poly1305::Key::from_slice(key.as_slice());
    (rc_Poly1305::new(rc_key), Poly1305::new(KeyRef::new(&key)))
}

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

    #[test]
    fn smoke() {
        let key: Key = [42u8; 32].into();
        let tag = Poly1305::new(key.as_ref())
            .aead_padding_ct()
            .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);
    }

    #[test]
    fn rust_crypto_aligned() {
        let key = [42u8; 32];
        let (mut rc, wc) = construct_polys(key);
        let data = b"hello world we operate equivalen";

        let (blocks, _rem) = rc_to_blocks(data);

        rc.update(blocks);
        let rc_out = rc.finalize();

        let wc_out = wc.update(data).unwrap().finalize();

        assert_eq!(wc_out, rc_out.as_slice());
    }

    #[test]
    fn rust_crypto_unaligned() {
        let key = [42u8; 32];
        let (mut rc, wc) = construct_polys(key);
        let data = b"hello world we operate equivalently";

        rc.update_padded(data);
        let rc_tag = rc.finalize();
        let tag = wc.update(data).unwrap().finalize();

        assert_eq!(tag, rc_tag.as_slice());
    }
}

#[cfg(kani)]
const fn wc_to_pad(len_to_pad: u32) -> u32 {
    ((-(len_to_pad as isize)) & 15) as u32
}

#[cfg(kani)]
const fn wc_to_pad_64(len_to_pad: u64) -> u32 {
    ((-(len_to_pad as i128)) & 15) as u32
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;
    use crate::aes::test_utils::{BoundList, AnyList};

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(5_000))]

        #[test]
        fn wc_poly_is_eq_to_rc_poly(
            key in any::<[u8; 32]>(),
            data in any::<BoundList<1024>>()
        ) {
            let (mut rc, wc) = construct_polys(key);

            rc.update_padded(data.as_slice());

            let tag = wc.update(data.as_slice()).unwrap().finalize();
            let rc_tag = rc.finalize();

            prop_assert_eq!(tag, rc_tag.as_slice());
        }

        #[test]
        fn wc_poly_multi_updates_is_eq_to_rc_poly_oneshot(
            key in any::<[u8; 32]>(),
            data in any::<AnyList<32, BoundList<256>>>()
        ) {
            let (mut rc, wc) = construct_polys(key);

            let mut wc = wc.normal();

            for input in data.as_slice() {
                wc = wc.update(input.as_slice()).unwrap();
            }

            let joined = data.join();
            rc.update_padded(joined.as_slice());

            let tag = wc.finalize();
            let rc_tag = rc.finalize();

            prop_assert_eq!(tag, rc_tag.as_slice());
        }

        #[test]
        fn multi_updates_is_eq_to_oneshot_tls_aead_scheme(
            key in any::<Key>(),
            data in any::<AnyList<32, BoundList<256>>>()
        ) {
            let mut updates = Poly1305::new(key.as_ref()).aead_padding();

            for input in data.as_slice() {
                updates = updates.update(input.as_slice()).unwrap();
            }

            let tag = updates.finalize();

            let joined = data.join();
            let m_tag = Poly1305::new(key).mac(joined.as_slice(), ()).unwrap();

            prop_assert_eq!(tag, m_tag);
        }

        #[test]
        fn multi_updates_ct_is_eq_to_normal(
            key in any::<Key>(),
            data in any::<AnyList<32, BoundList<256>>>()
        ) {
            let mut poly = Poly1305::new(key.as_ref()).normal();
            let mut poly_ct = Poly1305::new(key.as_ref()).normal_ct();

            for input in data.as_slice() {
                poly = poly.update(input.as_slice()).unwrap();
                poly_ct = poly_ct.update_ct(input.as_slice());
            }

            let tag = poly.finalize();
            let tag_ct = poly_ct.finalize().unwrap();

            prop_assert_eq!(tag, tag_ct);
        }

        #[test]
        fn multi_updates_is_eq_oneshot(
            key in any::<Key>(),
            data in any::<AnyList<32, BoundList<256>>>()
        ) {
            let mut poly = Poly1305::new(key.as_ref()).normal();

            for input in data.as_slice() {
                poly = poly.update(input.as_slice()).unwrap();
            }

            let tag = poly.finalize();

            let joined = data.join();
            let o_tag = Poly1305::new(key)
                .update(joined.as_slice()).unwrap()
                .finalize();

            prop_assert_eq!(tag, o_tag);
        }

        #[test]
        fn multi_updates_ct_is_eq_oneshot(
            key in any::<Key>(),
            data in any::<AnyList<32, BoundList<256>>>()
        ) {
            let mut poly = Poly1305::new(key.as_ref()).normal_ct();

            for input in data.as_slice() {
                poly = poly.update_ct(input.as_slice());
            }

            let tag = poly.finalize().unwrap();

            let joined = data.join();
            let o_tag = Poly1305::new(key)
                .update(joined.as_slice()).unwrap()
                .finalize();

            prop_assert_eq!(tag, o_tag);
        }
    }
}

#[cfg(kani)]
mod proofs {
    use kani::proof;
    use super::*;

    #[proof]
    fn univ_update_to_pad_is_no_wrap_mask() {
        let existing: u32 = kani::any();
        let to_add: u32 = kani::any();

        let utp = update_to_pad((existing & 15) as u8, to_add) as u64;
        let genuine = ((existing as u64) + (to_add as u64)) & 15;

        kani::assert(
            utp == genuine,
            "The wrapping addition must always be equivalent to non-wrapping output"
        );
    }

    #[proof]
    fn univ_update_to_pad_holds_for_wc_pad_algo() {
        let start: u32 = kani::any();
        let end: u32 = kani::any();

        let utp = update_to_pad((start & 15) as u8, end);

        kani::assert(
            wc_to_pad(utp as u32) == wc_to_pad_64((start as u64) + (end as u64)),
            "update_to_pad must be equivalent to the total length in the eyes of the wolfcrypt \
            padding algorithm."
        );
    }

    #[proof]
    fn univ_mask_is_no_mask_to_wc_pad_algo() {
        let some_num: u64 = kani::any();

        kani::assert(
            wc_to_pad_64(some_num & 15) == wc_to_pad_64(some_num),
            "wolfcrypt's to pad must result in the same output for the input mask 15 and raw input"
        )
    }
}