trouble-host 0.7.0

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

use core::num::NonZeroU128;

use aes::cipher::{BlockEncrypt, KeyInit};
use aes::Aes128;
use bt_hci::param::BdAddr;
use cmac::digest;
use p256::ecdh;
use rand_core::{CryptoRng, RngCore};

use crate::Address;

/// LE Secure Connections Long Term Key.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[must_use]
#[repr(transparent)]
pub struct LongTermKey(pub u128);

impl LongTermKey {
    /// Creates a Long Term Key from a `u128` value.
    #[inline(always)]
    pub const fn new(k: u128) -> Self {
        Self(k)
    }
    /// Creates a Long Term Key from a `[u8; 16]` value in little endian.
    #[inline(always)]
    pub const fn from_le_bytes(k: [u8; 16]) -> Self {
        Self(u128::from_le_bytes(k))
    }
    /// Creates a Long Term Key from a `[u8; 16]` value in little endian.
    #[inline(always)]
    pub const fn to_le_bytes(self) -> [u8; 16] {
        self.0.to_le_bytes()
    }

    /// Derives a Long Term Key from a 128-bit Encryption Root (ER) and 16-bit
    /// Diversifier (DIV) ([Vol 3] Part H, Section B.2.2).
    ///
    ///   LTK = d1(ER, DIV, 0)
    #[inline]
    pub fn from_encryption_root(er: u128, div: u16) -> Self {
        Self(d1(er, div, 0))
    }
}

impl From<&LongTermKey> for u128 {
    #[inline(always)]
    fn from(k: &LongTermKey) -> Self {
        k.0
    }
}

impl core::fmt::Display for LongTermKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:016x}", self.0)
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for LongTermKey {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "{:016x}", self.0)
    }
}

/// Identity Resolving Key.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[must_use]
#[repr(transparent)]
pub struct IdentityResolvingKey(pub NonZeroU128);

impl IdentityResolvingKey {
    /// Creates an Identity Resolving Key from a `u128` value.
    #[inline(always)]
    pub const fn new(k: u128) -> Option<Self> {
        match NonZeroU128::new(k) {
            Some(k) => Some(Self(k)),
            None => None,
        }
    }

    /// Creates an Identity Resolving Key from a `[u8; 16]` value in little endian.
    #[inline(always)]
    pub const fn from_le_bytes(k: [u8; 16]) -> Option<Self> {
        Self::new(u128::from_le_bytes(k))
    }

    /// Derives an Identity Resolving Key from a 128-bit Identity Root (IR)
    /// ([Vol 3] Part H, Section B.2.3).
    ///
    ///   IRK = d1(IR, 1, 0)
    #[inline]
    pub fn from_identity_root(ir: u128) -> Option<Self> {
        Self::new(d1(ir, 1, 0))
    }

    /// Returns the Identity Resolving Key as `[u8; 16]` value in little endian.
    #[inline(always)]
    pub const fn to_le_bytes(self) -> [u8; 16] {
        self.0.get().to_le_bytes()
    }

    /// Generates a resolvable private address using this key.
    ///
    /// The generated address follows the format described in
    /// Bluetooth Core Specification [Vol 3] Part C, Section 10.8.2.
    pub fn generate_resolvable_address<T: RngCore + CryptoRng>(&self, rng: &mut T) -> [u8; 6] {
        // Generate prand (24 bits with top 2 bits set to 0b01 to indicate resolvable private address)
        let mut prand = [0u8; 3];
        rng.fill_bytes(&mut prand);

        // Set the top 2 bits to 0b01 to indicate resolvable private address
        prand[2] &= 0b00111111; // Clear top 2 bits
        prand[2] |= 0b01000000; // Set 2nd bit from top

        // Calculate hash using ah function
        let hash = self.ah(prand);

        // Construct the address: prand || hash
        let mut address = [0u8; 6];
        address[3..6].copy_from_slice(&prand);
        address[0..3].copy_from_slice(&hash);

        address
    }

    /// Resolves a resolvable private address.
    ///
    /// Returns true if the address was generated using this IRK.
    pub fn resolve_address(&self, address: &BdAddr) -> bool {
        // Extract prand (top 24 bits) and hash (bottom 24 bits)
        let mut prand = [0u8; 3];
        prand.copy_from_slice(&address.raw()[3..6]);

        // Verify the address type bits (top 2 bits should be 0b01)
        if (prand[2] & 0b11000000) != 0b01000000 {
            return false; // Not a resolvable private address
        }

        prand.reverse();

        // Calculate local hash
        let mut local_hash = self.ah(prand);
        local_hash.reverse();

        // Compare with the hash in the address
        let mut address_hash = [0u8; 3];
        address_hash.copy_from_slice(&address.raw()[0..3]);
        local_hash == address_hash
    }

    /// Random address hash function `ah` as defined in
    /// Bluetooth Core Specification [Vol 3] Part H, Section 2.2.2.
    /// https://www.bluetooth.com/wp-content/uploads/Files/Specification/HTML/Core-54/out/en/host/security-manager-specification.html#UUID-03b4d5c9-160c-658a-7aa5-d0b2230d38f1
    fn ah(&self, r: [u8; 3]) -> [u8; 3] {
        let mut r_prime = [0u8; 16];
        r_prime[13..].copy_from_slice(&r);

        let cipher = Aes128::new_from_slice(&self.0.get().to_be_bytes()).unwrap();
        cipher.encrypt_block((&mut r_prime).into());
        // Extract least significant 24 bits (3 bytes) as the result
        r_prime[13..16].try_into().unwrap()
    }
}

impl From<&IdentityResolvingKey> for u128 {
    #[inline(always)]
    fn from(k: &IdentityResolvingKey) -> Self {
        k.0.get()
    }
}

impl core::fmt::Display for IdentityResolvingKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:016x}", self.0)
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for IdentityResolvingKey {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "{:016x}", self.0)
    }
}

/// RFC-4493 AES-CMAC ([Vol 3] Part H, Section 2.2.5).
#[derive(Debug)]
#[repr(transparent)]
pub struct AesCmac(cmac::Cmac<aes::Aes128>);

impl AesCmac {
    /// Creates new AES-CMAC state using key `k`.
    #[inline(always)]
    #[must_use]
    pub(super) fn new(k: &Key) -> Self {
        Self(digest::KeyInit::new(&k.0))
    }

    /// Creates new AES-CMAC state using an all-zero key for GAP database hash
    /// calculation ([Vol 3] Part G, Section 7.3.1).
    #[inline(always)]
    #[must_use]
    pub fn db_hash() -> Self {
        Self::new(&Key::new(0))
    }

    /// Updates CMAC state.
    #[inline(always)]
    pub fn update(&mut self, b: impl AsRef<[u8]>) -> &mut Self {
        digest::Update::update(&mut self.0, b.as_ref());
        self
    }

    /// Computes the final MAC value.
    #[inline(always)]
    #[must_use]
    pub fn finalize(self) -> u128 {
        u128::from_be_bytes(*digest::FixedOutput::finalize_fixed(self.0).as_ref())
    }

    /// Computes the final MAC value for use as a future key and resets the
    /// state.
    #[inline(always)]
    pub(super) fn finalize_key(&mut self) -> Key {
        // Best effort to avoid leaving copies
        let mut k = Key::new(0);
        digest::FixedOutputReset::finalize_into_reset(&mut self.0, &mut k.0);
        k
    }
}

/// LE Secure Connections check value generated by [`MacKey::f6`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
#[repr(transparent)]
pub struct Check(pub u128);

#[derive(Clone, Copy)]
#[repr(transparent)]
pub(super) struct Key(aes::cipher::Key<aes::Aes128>);

impl Key {
    /// Creates a key from a `u128` value.
    #[inline(always)]
    pub fn new(k: u128) -> Self {
        Self(k.to_be_bytes().into())
    }
}

impl From<&Key> for u128 {
    #[inline(always)]
    fn from(k: &Key) -> Self {
        Self::from_be_bytes(k.0.into())
    }
}

/// Concatenated `AuthReq`, OOB data flag, and IO capability parameters used by
/// [`MacKey::f6`] function ([Vol 3] Part H, Section 2.2.8).
#[repr(transparent)]
#[derive(Clone, Copy, Debug)]
pub struct IoCap(pub(crate) [u8; 3]);

impl IoCap {
    /// Creates new `IoCap` parameter.
    #[inline(always)]
    pub fn new(auth_req: u8, oob_data: bool, io_cap: u8) -> Self {
        Self([auth_req, u8::from(oob_data), io_cap])
    }
}

/// 128-bit key used to compute LE Secure Connections check value
/// ([Vol 3] Part H, Section 2.2.8).
#[derive(Clone, Copy)]
#[must_use]
#[repr(transparent)]
pub struct MacKey(Key);

impl core::fmt::Debug for MacKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("MacKey").field(&"***").finish()
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for MacKey {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "MacKey(***)");
    }
}

impl MacKey {
    /// Generates LE Secure Connections check value
    /// ([Vol 3] Part H, Section 2.2.8).
    #[inline]
    pub fn f6(&self, n1: Nonce, n2: Nonce, r: u128, io_cap: IoCap, a1: Address, a2: Address) -> Check {
        let mut m = AesCmac::new(&self.0);
        m.update(n1.0.to_be_bytes())
            .update(n2.0.to_be_bytes())
            .update(r.to_be_bytes())
            .update(io_cap.0)
            .update(a1.to_bytes())
            .update(a2.to_bytes());
        Check(m.finalize())
    }
}

/// 128-bit random nonce value ([Vol 3] Part H, Section 2.3.5.6).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(transparent)]
pub struct Nonce(pub u128);

impl Nonce {
    /// Generates a new non-zero random nonce value from the OS CSPRNG.
    ///
    /// # Panics
    ///
    /// Panics if the OS CSPRNG is broken.
    #[allow(clippy::new_without_default)]
    #[inline]
    pub fn new<T: RngCore>(rng: &mut T) -> Self {
        let mut b = [0; core::mem::size_of::<u128>()];
        rng.fill_bytes(b.as_mut_slice());
        let n = u128::from_ne_bytes(b);
        assert_ne!(n, 0);
        Self(n)
    }

    /// Generates LE Secure Connections confirm value
    /// ([Vol 3] Part H, Section 2.2.6).
    #[inline]
    pub fn f4(&self, u: &PublicKeyX, v: &PublicKeyX, z: u8) -> Confirm {
        let mut m = AesCmac::new(&Key::new(self.0));
        m.update(u.as_be_bytes()).update(v.as_be_bytes()).update([z]);
        Confirm(m.finalize())
    }

    /// Generates LE Secure Connections numeric comparison value
    /// ([Vol 3] Part H, Section 2.2.9).
    #[inline]
    pub fn g2(&self, pkax: &PublicKeyX, pkbx: &PublicKeyX, nb: &Self) -> NumCompare {
        let mut m = AesCmac::new(&Key::new(self.0));
        m.update(pkax.as_be_bytes())
            .update(pkbx.as_be_bytes())
            .update(nb.0.to_be_bytes());
        #[allow(clippy::cast_possible_truncation)]
        NumCompare(m.finalize() as u32 % 1_000_000)
    }
}

/// LE Secure Connections confirm value generated by [`Nonce::f4`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[must_use]
#[repr(transparent)]
pub struct Confirm(pub u128);

/// 6-digit LE Secure Connections numeric comparison value generated by
/// [`Nonce::g2`].
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[must_use]
#[repr(transparent)]
pub struct NumCompare(pub u32);

/// P-256 elliptic curve secret key.
#[derive(Clone)]
#[must_use]
#[repr(transparent)]
pub struct SecretKey(p256::NonZeroScalar);

impl core::fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("SecretKey").field(&"***").finish()
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for SecretKey {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "SecretKey(***)");
    }
}

impl SecretKey {
    /// Generates a new random secret key.
    #[allow(clippy::new_without_default)]
    #[inline(always)]
    pub fn new<T: RngCore + CryptoRng>(rng: &mut T) -> Self {
        Self(p256::NonZeroScalar::random(rng))
    }

    /// Computes the associated public key.
    pub fn public_key(&self) -> PublicKey {
        use p256::elliptic_curve::sec1::Coordinates::Uncompressed;
        use p256::elliptic_curve::sec1::ToEncodedPoint;
        let p = p256::PublicKey::from_secret_scalar(&self.0).to_encoded_point(false);
        match p.coordinates() {
            Uncompressed { x, y } => PublicKey {
                x: PublicKeyX(Coord(*x.as_ref())),
                y: Coord(*y.as_ref()),
            },
            _ => unreachable!("invalid secret key"),
        }
    }

    /// Computes a shared secret from the local secret key and remote public
    /// key. Returns [`None`] if the public key is either invalid or derived
    /// from the same secret key ([Vol 3] Part H, Section 2.3.5.6.1).
    #[must_use]
    pub fn dh_key(&self, pk: PublicKey) -> Option<DHKey> {
        use p256::elliptic_curve::sec1::FromEncodedPoint;
        if pk.is_debug() {
            return None; // TODO: Compile-time option for debug-only mode
        }

        let (x, y) = (&pk.x.0 .0.into(), &pk.y.0.into());
        let rep = p256::EncodedPoint::from_affine_coordinates(x, y, false);
        let lpk = p256::PublicKey::from_secret_scalar(&self.0);
        // Constant-time ops not required:
        // https://github.com/RustCrypto/traits/issues/1227
        let rpk = Option::from(p256::PublicKey::from_encoded_point(&rep)).unwrap_or(lpk);
        (rpk != lpk).then(|| DHKey(ecdh::diffie_hellman(&self.0, rpk.as_affine())))
    }
}

/// P-256 elliptic curve public key ([Vol 3] Part H, Section 3.5.6).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[must_use]
pub struct PublicKey {
    pub x: PublicKeyX,
    pub y: Coord,
}

impl PublicKey {
    pub fn from_bytes(bytes: &[u8]) -> Self {
        let mut x = [0u8; 32];
        let mut y = [0u8; 32];

        x.copy_from_slice(&bytes[..32]);
        y.copy_from_slice(&bytes[32..]);

        x.reverse();
        y.reverse();

        Self {
            x: PublicKeyX(Coord(x)),
            y: Coord(y),
        }
    }

    /// Returns the public key X coordinate.
    #[inline(always)]
    pub const fn x(&self) -> &PublicKeyX {
        &self.x
    }

    /// Returns whether `self` is the debug public key
    /// ([Vol 3] Part H, Section 2.3.5.6.1).
    #[allow(clippy::unreadable_literal)]
    #[allow(clippy::unusual_byte_groupings)]
    fn is_debug(&self) -> bool {
        let (x, y) = (&self.x.0 .0, &self.y.0);
        x[..16] == u128::to_be_bytes(0x20b003d2_f297be2c_5e2c83a7_e9f9a5b9)
            && x[16..] == u128::to_be_bytes(0xeff49111_acf4fddb_cc030148_0e359de6)
            && y[..16] == u128::to_be_bytes(0xdc809c49_652aeb6d_63329abf_5a52155c)
            && y[16..] == u128::to_be_bytes(0x766345c2_8fed3024_741c8ed0_1589d28b)
    }
}

/// 256-bit elliptic curve coordinate in big-endian byte order.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(transparent)]
pub struct Coord([u8; 256 / u8::BITS as usize]);

impl Coord {
    /// Returns the coordinate in big-endian byte order.
    #[inline(always)]
    pub(super) const fn as_be_bytes(&self) -> &[u8; core::mem::size_of::<Self>()] {
        &self.0
    }
}

/// P-256 elliptic curve public key affine X coordinate.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[must_use]
#[repr(transparent)]
pub struct PublicKeyX(Coord);

impl PublicKeyX {
    /// Creates the coordinate from a big-endian encoded byte array.
    #[cfg(test)]
    #[inline]
    pub(super) const fn from_be_bytes(x: [u8; core::mem::size_of::<Self>()]) -> Self {
        Self(Coord(x))
    }

    /// Returns the coordinate in big-endian byte order.
    #[inline(always)]
    pub(super) const fn as_be_bytes(&self) -> &[u8; core::mem::size_of::<Self>()] {
        &self.0 .0
    }
}

/// P-256 elliptic curve shared secret ([Vol 3] Part H, Section 2.3.5.6.1).
#[must_use]
#[repr(transparent)]
pub struct DHKey(ecdh::SharedSecret);

impl Clone for DHKey {
    fn clone(&self) -> Self {
        Self(ecdh::SharedSecret::from(*self.0.raw_secret_bytes()))
    }
}

impl core::fmt::Debug for DHKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("DHKey").field(&"***").finish()
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for DHKey {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "DHKey(***)");
    }
}

impl DHKey {
    /// Generates LE Secure Connections `MacKey` and `LTK`
    /// ([Vol 3] Part H, Section 2.2.7).
    #[inline]
    pub fn f5(&self, n1: Nonce, n2: Nonce, a1: Address, a2: Address) -> (MacKey, LongTermKey) {
        let n1 = n1.0.to_be_bytes();
        let n2 = n2.0.to_be_bytes();
        let half = |m: &mut AesCmac, counter: u8| {
            m.update([counter])
                .update(b"btle")
                .update(n1)
                .update(n2)
                .update(a1.to_bytes())
                .update(a2.to_bytes())
                .update(256_u16.to_be_bytes())
                .finalize_key()
        };
        let mut m = AesCmac::new(&Key::new(0x6C88_8391_AAF5_A538_6037_0BDB_5A60_83BE));
        m.update(self.0.raw_secret_bytes());
        let mut m = AesCmac::new(&m.finalize_key());
        (MacKey(half(&mut m, 0)), LongTermKey(u128::from(&half(&mut m, 1))))
    }
}

#[cfg(feature = "legacy-pairing")]
#[allow(clippy::too_many_arguments)]
/// Confirm value generation function `c1` for LE Legacy Pairing
/// ([Vol 3] Part H, Section 2.2.3).
///
/// Uses two rounds of AES-128 with XOR combining:
///   c1(k, r, preq, pres, iat, ia, rat, ra) = e(k, e(k, r XOR p1) XOR p2)
/// where:
///   p1 = pres || preq || rat || iat
///   p2 = padding || ia || ra
///
/// - `preq`/`pres`: 7 bytes each in wire order (command code at index 0)
/// - `iat`/`rat`: address type (0=public, 1=random)
/// - `ia`/`ra`: 6-byte address in MSO order (reversed from BdAddr raw)
pub(super) fn c1(
    k: u128,
    r: u128,
    preq: &[u8; 7],
    pres: &[u8; 7],
    iat: u8,
    ia: &[u8; 6],
    rat: u8,
    ra: &[u8; 6],
) -> u128 {
    // p1 = pres || preq || rat || iat (MSO to LSO, 16 bytes)
    // preq/pres are treated as LE integers in the concatenation, so the wire-order
    // bytes must be reversed to place the most significant byte at the MSO position.
    let mut pres_rev = *pres;
    pres_rev.reverse();
    let mut preq_rev = *preq;
    preq_rev.reverse();

    let mut p1 = [0u8; 16];
    p1[0..7].copy_from_slice(&pres_rev);
    p1[7..14].copy_from_slice(&preq_rev);
    p1[14] = rat;
    p1[15] = iat;

    // p2 = padding(4) || ia(6) || ra(6) (MSO to LSO)
    let mut p2 = [0u8; 16];
    p2[4..10].copy_from_slice(ia);
    p2[10..16].copy_from_slice(ra);

    let cipher = Aes128::new_from_slice(&k.to_be_bytes()).unwrap();

    // e(k, r XOR p1)
    let r_bytes = r.to_be_bytes();
    let mut block = [0u8; 16];
    for i in 0..16 {
        block[i] = r_bytes[i] ^ p1[i];
    }
    cipher.encrypt_block((&mut block).into());

    // e(k, result XOR p2)
    for i in 0..16 {
        block[i] ^= p2[i];
    }
    cipher.encrypt_block((&mut block).into());

    u128::from_be_bytes(block)
}

#[cfg(feature = "legacy-pairing")]
/// Short Term Key (STK) generation function `s1` for LE Legacy Pairing
/// ([Vol 3] Part H, Section 2.2.4).
///
///   s1(k, r1, r2) = e(k, r1' || r2')
/// where r1' and r2' are the least significant 64 bits of r1 and r2.
pub(super) fn s1(k: u128, r1: u128, r2: u128) -> u128 {
    let r1_bytes = r1.to_be_bytes();
    let r2_bytes = r2.to_be_bytes();

    // r1' = r1[63:0] = least significant 8 bytes (bytes [8..16] in big-endian)
    // r2' = r2[63:0] = least significant 8 bytes
    let mut r_prime = [0u8; 16];
    r_prime[0..8].copy_from_slice(&r1_bytes[8..16]);
    r_prime[8..16].copy_from_slice(&r2_bytes[8..16]);

    let cipher = Aes128::new_from_slice(&k.to_be_bytes()).unwrap();
    cipher.encrypt_block((&mut r_prime).into());

    u128::from_be_bytes(r_prime)
}

/// Diversifying function `d1` ([Vol 3] Part H, Section B.2.1).
///
///   d1(k, d, r) = e(k, d')
/// where d' = padding(96) || r || d, with the least significant octet of `d`
/// becoming the least significant octet of `d'`.
pub(super) fn d1(k: u128, d: u16, r: u16) -> u128 {
    let mut d_prime = [0u8; 16];
    d_prime[12..14].copy_from_slice(&r.to_be_bytes());
    d_prime[14..16].copy_from_slice(&d.to_be_bytes());

    let cipher = Aes128::new_from_slice(&k.to_be_bytes()).unwrap();
    cipher.encrypt_block((&mut d_prime).into());

    u128::from_be_bytes(d_prime)
}

/// Combines `hi` and `lo` values into a big-endian byte array.
#[allow(clippy::redundant_pub_crate)]
#[cfg(test)]
pub(super) fn u256<T: From<[u8; 32]>>(hi: u128, lo: u128) -> T {
    let mut b = [0; 32];
    b[..16].copy_from_slice(&hi.to_be_bytes());
    b[16..].copy_from_slice(&lo.to_be_bytes());
    T::from(b)
}

#[allow(clippy::unreadable_literal)]
#[allow(clippy::unusual_byte_groupings)]
#[cfg(test)]
mod tests {
    use p256::elliptic_curve::rand_core::OsRng;

    use super::*;
    extern crate std;
    use bt_hci::param::{AddrKind, BdAddr};

    #[test]
    fn sizes() {
        assert_eq!(core::mem::size_of::<Coord>(), 32);
        assert_eq!(core::mem::size_of::<PublicKey>(), 64);
        assert_eq!(core::mem::size_of::<SecretKey>(), 32);
        assert_eq!(core::mem::size_of::<DHKey>(), 32);
    }

    /// Debug mode key ([Vol 3] Part H, Section 2.3.5.6.1).
    #[test]
    fn debug_key() {
        let sk = secret_key(
            0x3f49f6d4_a3c55f38_74c9b3e3_d2103f50,
            0x4aff607b_eb40b799_5899b8a6_cd3c1abd,
        );
        let pk = PublicKey {
            x: PublicKeyX(Coord(u256(
                0x20b003d2_f297be2c_5e2c83a7_e9f9a5b9,
                0xeff49111_acf4fddb_cc030148_0e359de6,
            ))),
            y: Coord(u256(
                0xdc809c49_652aeb6d_63329abf_5a52155c,
                0x766345c2_8fed3024_741c8ed0_1589d28b,
            )),
        };
        assert_eq!(sk.public_key(), pk);
        assert!(pk.is_debug());
    }

    /// P-256 data set 1 ([Vol 2] Part G, Section 7.1.2.1).
    #[test]
    fn p256_1() {
        let (ska, skb) = (
            secret_key(
                0x3f49f6d4_a3c55f38_74c9b3e3_d2103f50,
                0x4aff607b_eb40b799_5899b8a6_cd3c1abd,
            ),
            secret_key(
                0x55188b3d_32f6bb9a_900afcfb_eed4e72a,
                0x59cb9ac2_f19d7cfb_6b4fdd49_f47fc5fd,
            ),
        );
        let (pka, pkb) = (
            PublicKey {
                x: PublicKeyX(Coord(u256(
                    0x20b003d2_f297be2c_5e2c83a7_e9f9a5b9,
                    0xeff49111_acf4fddb_cc030148_0e359de6,
                ))),
                y: Coord(u256(
                    0xdc809c49_652aeb6d_63329abf_5a52155c,
                    0x766345c2_8fed3024_741c8ed0_1589d28b,
                )),
            },
            PublicKey {
                x: PublicKeyX(Coord(u256(
                    0x1ea1f0f0_1faf1d96_09592284_f19e4c00,
                    0x47b58afd_8615a69f_559077b2_2faaa190,
                ))),
                y: Coord(u256(
                    0x4c55f33e_429dad37_7356703a_9ab85160,
                    0x472d1130_e28e3676_5f89aff9_15b1214a,
                )),
            },
        );
        let dh_key = shared_secret(
            0xec0234a3_57c8ad05_341010a6_0a397d9b,
            0x99796b13_b4f866f1_868d34f3_73bfa698,
        );
        assert_eq!(ska.public_key(), pka);
        assert_eq!(skb.public_key(), pkb);
        assert_eq!(
            ska.dh_key(pkb).unwrap().0.raw_secret_bytes(),
            dh_key.0.raw_secret_bytes()
        );

        assert!(!pkb.is_debug());
        assert!(skb.dh_key(pkb).is_none());
    }

    /// P-256 data set 2 ([Vol 2] Part G, Section 7.1.2.2).
    #[test]
    fn p256_2() {
        let (ska, skb) = (
            secret_key(
                0x06a51669_3c9aa31a_6084545d_0c5db641,
                0xb48572b9_7203ddff_b7ac73f7_d0457663,
            ),
            secret_key(
                0x529aa067_0d72cd64_97502ed4_73502b03,
                0x7e8803b5_c60829a5_a3caa219_505530ba,
            ),
        );
        let (pka, pkb) = (
            PublicKey {
                x: PublicKeyX(Coord(u256(
                    0x2c31a47b_5779809e_f44cb5ea_af5c3e43,
                    0xd5f8faad_4a8794cb_987e9b03_745c78dd,
                ))),
                y: Coord(u256(
                    0x91951218_3898dfbe_cd52e240_8e43871f,
                    0xd0211091_17bd3ed4_eaf84377_43715d4f,
                )),
            },
            PublicKey {
                x: PublicKeyX(Coord(u256(
                    0xf465e43f_f23d3f1b_9dc7dfc0_4da87581,
                    0x84dbc966_204796ec_cf0d6cf5_e16500cc,
                ))),
                y: Coord(u256(
                    0x0201d048_bcbbd899_eeefc424_164e33c2,
                    0x01c2b010_ca6b4d43_a8a155ca_d8ecb279,
                )),
            },
        );
        let dh_key = shared_secret(
            0xab85843a_2f6d883f_62e5684b_38e30733,
            0x5fe6e194_5ecd1960_4105c6f2_3221eb69,
        );
        assert_eq!(ska.public_key(), pka);
        assert_eq!(skb.public_key(), pkb);
        assert_eq!(
            ska.dh_key(pkb).unwrap().0.raw_secret_bytes(),
            dh_key.0.raw_secret_bytes()
        );
    }

    /// Key generation function ([Vol 3] Part H, Section D.3).
    #[test]
    fn dh_key_f5() {
        let w = shared_secret(
            0xec0234a3_57c8ad05_341010a6_0a397d9b,
            0x99796b13_b4f866f1_868d34f3_73bfa698,
        );
        let n1 = Nonce(0xd5cb8454_d177733e_ffffb2ec_712baeab);
        let n2 = Nonce(0xa6e8e7cc_25a75f6e_216583f7_ff3dc4cf);
        let a1 = Address::new(AddrKind::PUBLIC, BdAddr::new([0xce, 0xbf, 0x37, 0x37, 0x12, 0x56]));
        let a2 = Address::new(AddrKind::PUBLIC, BdAddr::new([0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7]));
        let (mk, ltk) = w.f5(n1, n2, a1, a2);
        assert_eq!(ltk.0, 0x69867911_69d7cd23_980522b5_94750a38);
        assert_eq!(u128::from(&mk.0), 0x2965f176_a1084a02_fd3f6a20_ce636e20);
    }

    #[inline]
    fn secret_key(hi: u128, lo: u128) -> SecretKey {
        SecretKey(p256::NonZeroScalar::from_repr(u256(hi, lo)).unwrap())
    }

    #[inline]
    fn shared_secret(hi: u128, lo: u128) -> DHKey {
        DHKey(ecdh::SharedSecret::from(u256::<p256::FieldBytes>(hi, lo)))
    }

    #[test]
    fn testtest() {
        let skb = SecretKey::new(&mut OsRng::default());
        let _pkb = skb.public_key();

        let ska = SecretKey::new(&mut OsRng::default());
        let pka = ska.public_key();

        let _dh_key = skb.dh_key(pka).unwrap();
    }

    #[test]
    fn testtest2() {
        let bytes = [
            0x1eu8, 0x3b, 0x26, 0x40, 0x0e, 0xba, 0x72, 0x51, 0x81, 0xf9, 0x3d, 0x16, 0xb3, 0xc4, 0x11, 0x55, 0x3f,
            0xa8, 0x88, 0x47, 0x08, 0x1c, 0x4a, 0x42, 0x88, 0xbb, 0x68, 0x1d, 0x93, 0xe5, 0xab, 0xb3, 0x72, 0xfa, 0x93,
            0xb4, 0xa0, 0xfe, 0x3f, 0x83, 0x9c, 0x85, 0x5b, 0x5f, 0xb6, 0x30, 0x09, 0x85, 0x47, 0xfd, 0xa8, 0xfa, 0x11,
            0x71, 0xe4, 0x95, 0x17, 0x71, 0x98, 0x82, 0x8f, 0xf8, 0x79, 0x94,
        ];

        let skb = SecretKey::new(&mut OsRng::default());
        let _pkb = skb.public_key();

        let pka = PublicKey::from_bytes(&bytes);

        let _dh_key = skb.dh_key(pka).unwrap();
    }

    #[test]
    fn nonce() {
        // No fair dice rolls for us!
        assert_ne!(Nonce::new(&mut OsRng::default()), Nonce::new(&mut OsRng::default()));
    }

    /// Confirm value generation function ([Vol 3] Part H, Section D.2).
    #[test]
    fn nonce_f4() {
        let u = PublicKeyX::from_be_bytes(u256(
            0x20b003d2_f297be2c_5e2c83a7_e9f9a5b9,
            0xeff49111_acf4fddb_cc030148_0e359de6,
        ));
        let v = PublicKeyX::from_be_bytes(u256(
            0x55188b3d_32f6bb9a_900afcfb_eed4e72a,
            0x59cb9ac2_f19d7cfb_6b4fdd49_f47fc5fd,
        ));
        let x = Nonce(0xd5cb8454_d177733e_ffffb2ec_712baeab);
        assert_eq!(x.f4(&u, &v, 0).0, 0xf2c916f1_07a9bd1c_f1eda1be_a974872d);
    }

    /// Numeric comparison generation function ([Vol 3] Part H, Section D.5).
    #[allow(clippy::unreadable_literal)]
    #[test]
    fn nonce_g2() {
        let u = PublicKeyX::from_be_bytes(u256(
            0x20b003d2_f297be2c_5e2c83a7_e9f9a5b9,
            0xeff49111_acf4fddb_cc030148_0e359de6,
        ));
        let v = PublicKeyX::from_be_bytes(u256(
            0x55188b3d_32f6bb9a_900afcfb_eed4e72a,
            0x59cb9ac2_f19d7cfb_6b4fdd49_f47fc5fd,
        ));
        let x = Nonce(0xd5cb8454_d177733e_ffffb2ec_712baeab);
        let y = Nonce(0xa6e8e7cc_25a75f6e_216583f7_ff3dc4cf);
        assert_eq!(x.g2(&u, &v, &y), NumCompare(0x2f9ed5ba % 1_000_000));
    }

    /// Check value generation function ([Vol 3] Part H, Section D.4).
    #[test]
    fn mac_key_f6() {
        let k = MacKey(Key::new(0x2965f176_a1084a02_fd3f6a20_ce636e20));
        let n1 = Nonce(0xd5cb8454_d177733e_ffffb2ec_712baeab);
        let n2 = Nonce(0xa6e8e7cc_25a75f6e_216583f7_ff3dc4cf);
        let r = 0x12a3343b_b453bb54_08da42d2_0c2d0fc8;
        let io_cap = IoCap([0x01, 0x01, 0x02]);
        let a1 = Address::new(AddrKind::PUBLIC, BdAddr::new([0xce, 0xbf, 0x37, 0x37, 0x12, 0x56]));
        let a2 = Address::new(AddrKind::PUBLIC, BdAddr::new([0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7]));
        let c = k.f6(n1, n2, r, io_cap, a1, a2);
        assert_eq!(c.0, 0xe3c47398_9cd0e8c5_d26c0b09_da958f61);
    }

    #[test]
    fn nonce_f4_test() {
        let ra = [
            0x11u8, 0x3a, 0x7a, 0x69, 0x11, 0xcd, 0x44, 0x15, 0x52, 0xf7, 0x47, 0xe8, 0x26, 0x67, 0x72, 0xca,
        ];

        let rb = [
            0xa5u8, 0x9e, 0x9a, 0x32, 0xc0, 0x97, 0x1c, 0xf7, 0x72, 0x1c, 0x29, 0xa7, 0x8c, 0x1e, 0xfd, 0x18,
        ];

        let pkb = [
            0xd, 0x80, 0x33, 0x93, 0xad, 0x1f, 0x7e, 0x9a, 0x30, 0xc9, 0x6e, 0x1, 0x78, 0xf3, 0x43, 0x14, 0xa0, 0x57,
            0xae, 0xa5, 0xa8, 0xee, 0x75, 0x51, 0x3f, 0xaa, 0xb1, 0x80, 0x75, 0xc7, 0x14, 0x50, 0x73, 0x9a, 0x98, 0x95,
            0x36, 0x2e, 0xe6, 0x81, 0x5f, 0xbf, 0x16, 0xa2, 0x8c, 0xf6, 0x9d, 0xdc, 0x1f, 0xb8, 0x84, 0x8c, 0x7d, 0x37,
            0x36, 0xe4, 0x36, 0x3c, 0xb3, 0xe8, 0xfe, 0x4a, 0x73, 0xc6,
        ];

        let pka = [
            0x97, 0x20, 0x0f, 0xfe, 0xf0, 0xec, 0xdd, 0x11, 0xda, 0xa8, 0xa8, 0x07, 0x3e, 0xd7, 0xc6, 0xf2, 0x68, 0x5d,
            0xc2, 0x58, 0x71, 0x1e, 0x34, 0x4f, 0xa1, 0xc4, 0x44, 0xa9, 0x7c, 0x71, 0xee, 0x54, 0x0d, 0xad, 0xb7, 0x69,
            0x89, 0x9d, 0x4f, 0x83, 0x37, 0xcd, 0x43, 0xd3, 0x9f, 0x05, 0x13, 0x99, 0x6f, 0xbc, 0x1a, 0x89, 0xed, 0xb4,
            0x7f, 0x80, 0x98, 0xcf, 0xad, 0x7c, 0x4c, 0x57, 0xbf, 0xe1,
        ];

        let mut pkb_x = [0u8; 32];
        pkb_x.copy_from_slice(&pkb[..32]);
        pkb_x.reverse();
        let mut pka_x = [0u8; 32];
        pka_x.copy_from_slice(&pka[..32]);
        pka_x.reverse();

        let pkbx = PublicKeyX::from_be_bytes(pkb_x);
        let pkax = PublicKeyX::from_be_bytes(pka_x);
        extern crate std;

        let x = Nonce(u128::from_le_bytes(ra));
        let y = Nonce(u128::from_le_bytes(rb));

        assert_eq!(x.g2(&pkax, &pkbx, &y).0, 991180);
    }

    #[test]
    pub fn irk_test() {
        let irk = IdentityResolvingKey::new(0xec0234a3_57c8ad05_341010a6_0a397d9b).unwrap();
        let prand = [0x70, 0x81, 0x94];

        let hash = irk.ah(prand);
        assert_eq!(hash, [0x0d, 0xfb, 0xaa]);
    }

    #[test]
    pub fn rpa_test() {
        let irk = IdentityResolvingKey::new(0x8b3958c158ed64467bd27bc90d3cf54d).unwrap();
        let address = BdAddr::new([0x92, 0xF2, 0x8F, 0x84, 0x72, 0x4F]);
        let re = irk.resolve_address(&address);
        assert_eq!(re, true);
    }

    /// LE Legacy Pairing c1 test vector ([Vol 3] Part H, Appendix D.1).
    /// preq/pres in wire order (command code at index 0).
    #[cfg(feature = "legacy-pairing")]
    #[allow(clippy::unreadable_literal)]
    #[test]
    fn legacy_c1() {
        let k: u128 = 0;
        let r: u128 = 0x5783D52156AD6F0E6388274EC6702EE0;
        // Wire order: [Code, IO, OOB, Auth, MaxKey, InitDist, RespDist]
        let preq: [u8; 7] = [0x01, 0x01, 0x00, 0x00, 0x10, 0x07, 0x07];
        let pres: [u8; 7] = [0x02, 0x03, 0x00, 0x00, 0x08, 0x00, 0x05];
        let iat: u8 = 0x01;
        let rat: u8 = 0x00;
        let ia: [u8; 6] = [0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6];
        let ra: [u8; 6] = [0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6];

        let result = c1(k, r, &preq, &pres, iat, &ia, rat, &ra);
        assert_eq!(result, 0x1E1E3FEF878988EAD2A74DC5BEF13B86);
    }

    /// LE Legacy Pairing s1 test vector ([Vol 3] Part H, Appendix D.2).
    #[cfg(feature = "legacy-pairing")]
    #[allow(clippy::unreadable_literal)]
    #[test]
    fn legacy_s1() {
        let k: u128 = 0;
        let r1: u128 = 0x000F0E0D0C0B0A091122334455667788;
        let r2: u128 = 0x010203040506070899AABBCCDDEEFF00;

        let result = s1(k, r1, r2);
        assert_eq!(result, 0x9a1fe1f0e8b0f49b5b4216ae796da062);
    }

    /// Diversifying function d1 ([Vol 3] Part H, Section B.2.1).
    /// Spec example: d=0x1234, r=0xABCD => d' = 0x000000000000000000000000ABCD1234.
    #[allow(clippy::unreadable_literal)]
    #[test]
    fn diversify_d1() {
        let k: u128 = 0x000102030405060708090a0b0c0d0e0f;
        let d: u16 = 0x1234;
        let r: u16 = 0xABCD;
        assert_eq!(d1(k, d, r), 0xb66854fa3dd35aadf83a6c59e22b52fd);
    }
}