at-cryptoauth 0.6.0

Driver for ATECC608 Crypto Authentication secure elements
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
//! Memory and configuration operations

use crate::Block;
use crate::cert::compressed::{
    CertificateDefinition, CompressedCertificate, SerialSource, SubjectSource,
};
use crate::command::{self, Lock, PublicKey, Serial, Word};
use crate::error::{Error, ErrorKind};
use crate::memory::{CertificateRepr, CompressedCertRepr, Size, Slot, SlotAddress, Zone};
use embassy_sync::blocking_mutex::raw::RawMutex;

use super::AtCaClient;

pub struct Memory<'a, M: RawMutex, PHY> {
    pub(crate) atca: &'a AtCaClient<M, PHY>,
}

impl<'a, M: RawMutex, PHY> Memory<'a, M, PHY> {
    pub(crate) const SLOT_CONFIG_INDEX: usize = 20;
    pub(crate) const CHIP_OPTIONS_INDEX: usize = 90;
    pub(crate) const KEY_CONFIG_INDEX: usize = 96;
}

impl<'a, M, PHY> Memory<'a, M, PHY>
where
    PHY: embedded_hal_async::i2c::I2c,
    M: RawMutex,
{
    pub async fn serial_number(&self) -> Result<Serial, Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet =
            command::Read::new(inner.packet_builder()).read(Zone::Config, Size::Block, 0, 0)?;
        inner.execute(packet).await?.as_ref().try_into()
    }

    pub async fn pubkey(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
        let mut pubkey = PublicKey::default();
        let mut offset = 0;

        for (i, ranges) in CertificateRepr::new().enumerate() {
            let mut inner = self.atca.inner.lock().await;
            let packet = command::Read::new(inner.packet_builder()).slot(key_id, i as u8)?;

            let response = inner.execute(packet).await?;
            for range in ranges {
                let dst = offset..offset + range.len();
                pubkey.as_mut()[dst].copy_from_slice(&response.as_ref()[range.clone()]);
                offset += range.len();
            }
        }

        Ok(pubkey)
    }

    /// Derive the public key of a private-key slot via GenKey.
    ///
    /// A private-key slot is secret and cannot be read back with [`Self::pubkey`]
    /// (the device rejects the Read with an execution error); its public key is
    /// recomputed from the stored private key instead.
    pub async fn gen_pubkey(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = command::GenKey::new(inner.packet_builder()).public_key(key_id)?;
        inner.execute(packet).await?.as_ref().try_into()
    }

    pub async fn write_pubkey(&mut self, key_id: Slot, pubkey: &[u8]) -> Result<(), Error> {
        let mut data = Block::default();
        let mut offset = 0;

        for (i, ranges) in CertificateRepr::new().enumerate() {
            let mut inner = self.atca.inner.lock().await;
            data.as_mut().iter_mut().for_each(|value| *value = 0);

            for range in ranges {
                let src = offset..offset + range.len();
                data.as_mut()[range.clone()].copy_from_slice(&pubkey[src]);
                offset += range.len();
            }

            let packet =
                command::Write::new(inner.packet_builder()).slot(key_id, i as u8, &data)?;
            inner.execute(packet).await?;
        }
        Ok(())
    }

    pub async fn write_aes_key(&mut self, key_id: Slot, aes_key: &[u8]) -> Result<(), Error> {
        let mut inner = self.atca.inner.lock().await;
        let mut data = Block::default();
        data.as_mut()[..0x10].copy_from_slice(aes_key);
        let packet = command::Write::new(inner.packet_builder()).slot(key_id, 0u8, &data)?;
        inner.execute(packet).await.map(drop)
    }

    pub async fn is_slot_locked(&mut self, slot: Slot) -> Result<bool, Error> {
        let mut inner = self.atca.inner.lock().await;
        let zone = Zone::Config;
        let size = Size::Word;
        let block = 2;
        let word_offset = 6;
        let packet =
            command::Read::new(inner.packet_builder()).read(zone, size, block, word_offset)?;
        let response = inner.execute(packet).await?;
        let word = Word::try_from(response.as_ref())?;
        let slot_locked_bytes = word.as_ref()[..2]
            .try_into()
            .map(u16::from_le_bytes)
            .unwrap_or_else(|_| unreachable!());
        Ok(slot_locked_bytes & (0x01u16 << slot as u32) == 0x00)
    }

    pub async fn is_locked(&mut self, zone: Zone) -> Result<bool, Error> {
        let mut inner = self.atca.inner.lock().await;
        let size = Size::Word;
        let block = 2;
        let word_offset = 5;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            size,
            block,
            word_offset,
        )?;
        let response = inner.execute(packet).await?;
        let word = Word::try_from(response.as_ref())?;
        match zone {
            Zone::Config => Ok(word.as_ref()[3] != 0x55),
            Zone::Data => Ok(word.as_ref()[2] != 0x55),
            Zone::Otp => Err(ErrorKind::BadParam.into()),
        }
    }

    pub async fn lock_slot(&mut self, key_id: Slot) -> Result<(), Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = Lock::new(inner.packet_builder()).slot(key_id)?;
        inner.execute(packet).await.map(drop)
    }

    pub async fn lock(&mut self, zone: Zone) -> Result<(), Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = Lock::new(inner.packet_builder()).zone(zone, None)?;
        inner.execute(packet).await.map(drop)
    }

    pub async fn lock_crc(&mut self, zone: Zone, crc: u16) -> Result<(), Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = Lock::new(inner.packet_builder()).zone(zone, Some(crc))?;
        inner.execute(packet).await.map(drop)
    }

    pub async fn chip_options(&mut self) -> Result<u16, Error> {
        let (block, offset, pos) = Zone::locate_index(Self::CHIP_OPTIONS_INDEX);
        let range = pos as usize..pos as usize + 2;
        let mut inner = self.atca.inner.lock().await;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            Size::Word,
            block,
            offset,
        )?;
        inner.execute(packet).await.map(|resp| {
            resp.as_ref()[range]
                .try_into()
                .map(u16::from_le_bytes)
                .unwrap_or_else(|_| unreachable!())
        })
    }

    pub async fn permission(&mut self, slot: Slot) -> Result<u16, Error> {
        let index = Self::SLOT_CONFIG_INDEX + (slot as usize * 2);
        let (block, offset, pos) = Zone::locate_index(index);
        let range = pos as usize..pos as usize + 2;
        let mut inner = self.atca.inner.lock().await;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            Size::Word,
            block,
            offset,
        )?;
        inner.execute(packet).await.map(|resp| {
            resp.as_ref()[range]
                .try_into()
                .map(u16::from_le_bytes)
                .unwrap_or_else(|_| unreachable!())
        })
    }

    pub async fn key_type(&mut self, slot: Slot) -> Result<u16, Error> {
        let index = Self::KEY_CONFIG_INDEX + (slot as usize * 2);
        let (block, offset, pos) = Zone::locate_index(index);
        let range = pos as usize..pos as usize + 2;
        let mut inner = self.atca.inner.lock().await;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            Size::Word,
            block,
            offset,
        )?;
        inner.execute(packet).await.map(|resp| {
            resp.as_ref()[range]
                .try_into()
                .map(u16::from_le_bytes)
                .unwrap_or_else(|_| unreachable!())
        })
    }

    /// # Safety
    ///
    /// Caller must ensure the config zone parameters (size, block, offset) are valid
    /// for the target device and do not cause out-of-bounds reads.
    pub async unsafe fn read_config(
        &mut self,
        size: Size,
        block: u8,
        offset: u8,
    ) -> Result<heapless::Vec<u8, { Size::Block.len() }>, Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet =
            command::Read::new(inner.packet_builder()).read(Zone::Config, size, block, offset)?;
        inner.execute(packet).await.and_then(|d| {
            heapless::Vec::from_slice(d.as_ref()).map_err(|_| ErrorKind::SmallBuffer.into())
        })
    }

    pub async fn write_config(
        &mut self,
        size: Size,
        block: u8,
        offset: u8,
        data: &[u8],
    ) -> Result<(), Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = command::Write::new(inner.packet_builder()).write(
            Zone::Config,
            size,
            block,
            offset,
            data,
        )?;
        inner.execute(packet).await.map(drop)
    }

    pub async fn read_compressed_cert(
        &mut self,
        slot: Slot,
    ) -> Result<crate::cert::compressed::CompressedCertificate, Error> {
        if !slot.is_certificate() {
            return Err(ErrorKind::BadParam.into());
        }

        let mut cert_data = [0u8; crate::cert::compressed::CompressedCertificate::SIZE];
        let mut offset = 0;

        for (i, ranges) in CompressedCertRepr::new().enumerate() {
            let mut inner = self.atca.inner.lock().await;
            let packet = command::Read::new(inner.packet_builder()).slot(slot, i as u8)?;

            let response = inner.execute(packet).await?;
            for range in ranges {
                let dst = offset..offset + range.len();
                cert_data[dst].copy_from_slice(&response.as_ref()[range.clone()]);
                offset += range.len();
            }
        }

        Ok(crate::cert::compressed::CompressedCertificate::new(
            cert_data,
        ))
    }

    pub async fn write_compressed_cert(
        &mut self,
        slot: Slot,
        cert: &crate::cert::compressed::CompressedCertificate,
    ) -> Result<(), Error> {
        if !slot.is_certificate() {
            return Err(ErrorKind::BadParam.into());
        }

        let mut data = Block::default();
        let mut offset = 0;

        for (i, ranges) in CompressedCertRepr::new().enumerate() {
            let mut inner = self.atca.inner.lock().await;
            data.as_mut().iter_mut().for_each(|value| *value = 0);

            for range in ranges {
                let src = offset..offset + range.len();
                data.as_mut()[range.clone()].copy_from_slice(&cert.as_ref()[src]);
                offset += range.len();
            }

            let packet = command::Write::new(inner.packet_builder()).slot(slot, i as u8, &data)?;
            inner.execute(packet).await?;
        }
        Ok(())
    }

    /// Read a single 32-byte block from the Data08 slot.
    pub async fn read_data08_block(&mut self, block: u8) -> Result<Block, Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = command::Read::new(inner.packet_builder()).slot(Slot::Data08, block)?;
        let response = inner.execute(packet).await?;
        Block::try_from(response.as_ref())
    }

    /// Write a single 32-byte block to the Data08 slot.
    pub async fn write_data08_block(&mut self, block: u8, data: &Block) -> Result<(), Error> {
        let mut inner = self.atca.inner.lock().await;
        let packet = command::Write::new(inner.packet_builder()).slot(Slot::Data08, block, data)?;
        inner.execute(packet).await.map(drop)
    }

    /// Read a block from a SlotAddress (dispatches between cert slots and Data08 blocks).
    async fn read_addressed(&mut self, addr: &SlotAddress) -> Result<Block, Error> {
        match addr {
            SlotAddress::Data08(block) => self.read_data08_block(*block).await,
            _ => Err(ErrorKind::BadParam.into()),
        }
    }

    /// Write a block to a SlotAddress (dispatches between cert slots and Data08 blocks).
    async fn write_addressed(&mut self, addr: &SlotAddress, data: &Block) -> Result<(), Error> {
        match addr {
            SlotAddress::Data08(block) => self.write_data08_block(*block, data).await,
            _ => Err(ErrorKind::BadParam.into()),
        }
    }

    pub async fn read_certificate(
        &mut self,
        def: &CertificateDefinition<'_>,
        output: &mut [u8],
    ) -> Result<usize, Error> {
        let compressed = self.read_compressed_cert(def.compressed_slot).await?;
        // A private-key slot is secret: its public key must be derived via
        // GenKey, not read back. Public-key / cert slots are read directly.
        let public_key = if def.public_key_slot.is_private_key() {
            self.gen_pubkey(def.public_key_slot).await?
        } else {
            self.pubkey(def.public_key_slot).await?
        };

        let mut serial_buf = [0u8; 32];
        let serial: &[u8] = if let SerialSource::Stored(addr) = &def.serial_source {
            // Read serial directly from device storage
            let block = self.read_addressed(addr).await?;
            let count = def.serial_number.count as usize;
            serial_buf[..count].copy_from_slice(&block.as_ref()[..count]);
            &serial_buf[..count]
        } else {
            let device_serial = self.serial_number().await?;
            let mut gen_buf = [0u8; 16];
            let len = {
                let s = def.serial_source.generate(
                    &device_serial,
                    compressed.signer_id(),
                    &mut gen_buf,
                )?;
                s.len()
            };
            serial_buf[..len].copy_from_slice(&gen_buf[..len]);
            &serial_buf[..len]
        };

        // Resolve the subject from the definition (mirrors serial resolution).
        let mut subject_buf = [0u8; 64];
        let subject: Option<&[u8]> = match def.subject_source {
            SubjectSource::Template => None,
            SubjectSource::Provided(bytes) => Some(bytes),
            SubjectSource::FromSerial(derive) => {
                let device_serial = self.serial_number().await?;
                let n = derive(&device_serial, &mut subject_buf).ok_or(ErrorKind::BadParam)?;
                Some(&subject_buf[..n])
            }
        };

        def.reconstruct(&compressed, &public_key, serial, subject, output)
    }

    /// Compress a DER certificate and write it to the ATECC.
    ///
    /// If the serial source is `Stored`, writes the serial number to the
    /// addressed Data08 block first, then the compressed cert to the cert slot.
    ///
    /// That order matters: the two writes are separate ATECC transactions, and
    /// the cert slot is what decides whether a certificate is present at all.
    /// [`read_certificate`](Self::read_certificate) fails on a zeroed cert slot
    /// (its encoded date has no valid month or day) but silently splices in
    /// whatever the serial block holds. Writing the cert slot last makes it the
    /// commit point, so an interrupted write leaves the slot unreadable and the
    /// caller retries. The reverse order leaves a certificate that reconstructs
    /// cleanly against a stale serial, which no read can detect.
    pub async fn write_certificate(
        &mut self,
        def: &CertificateDefinition<'_>,
        der_cert: &[u8],
    ) -> Result<(), Error> {
        let compressed = def.compress(der_cert)?;

        // If serial is stored externally, write it to the Data08 block
        if let SerialSource::Stored(addr) = &def.serial_source {
            let serial = def.extract_serial(der_cert);
            let mut block = Block::default();
            let count = serial.len().min(32);
            block.as_mut()[..count].copy_from_slice(&serial[..count]);
            self.write_addressed(addr, &block).await?;
        }

        self.write_compressed_cert(def.compressed_slot, &compressed)
            .await?;

        Ok(())
    }

    /// Erase a certificate from the ATECC (zero the cert slot and stored serial).
    ///
    /// Zeroes the cert slot first — the mirror of
    /// [`write_certificate`](Self::write_certificate)'s order, and correct for
    /// the same reason: it invalidates the commit point up front, so a half-done
    /// erase still reads as "no certificate" rather than as a live one.
    pub async fn erase_certificate(
        &mut self,
        def: &CertificateDefinition<'_>,
    ) -> Result<(), Error> {
        let zero_cert = CompressedCertificate::zeroed();
        self.write_compressed_cert(def.compressed_slot, &zero_cert)
            .await?;

        if let SerialSource::Stored(addr) = &def.serial_source {
            let zero_block = Block::default();
            self.write_addressed(addr, &zero_block).await?;
        }

        Ok(())
    }
}

impl<'a, M, PHY> Memory<'a, M, PHY>
where
    PHY: embedded_hal::i2c::I2c,
    M: RawMutex,
{
    pub fn serial_number_blocking(&mut self) -> Result<Serial, Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet =
            command::Read::new(inner.packet_builder()).read(Zone::Config, Size::Block, 0, 0)?;
        inner.execute_blocking(packet)?.as_ref().try_into()
    }

    pub fn pubkey_blocking(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
        let mut pubkey = PublicKey::default();
        let mut offset = 0;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;

        for (i, ranges) in CertificateRepr::new().enumerate() {
            let packet = command::Read::new(inner.packet_builder()).slot(key_id, i as u8)?;

            let response = inner.execute_blocking(packet)?;
            for range in ranges {
                let dst = offset..offset + range.len();
                pubkey.as_mut()[dst].copy_from_slice(&response.as_ref()[range.clone()]);
                offset += range.len();
            }
        }

        Ok(pubkey)
    }

    /// Blocking counterpart to [`Self::gen_pubkey`].
    pub fn gen_pubkey_blocking(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::GenKey::new(inner.packet_builder()).public_key(key_id)?;
        inner.execute_blocking(packet)?.as_ref().try_into()
    }

    pub fn write_pubkey_blocking(&mut self, key_id: Slot, pubkey: &[u8]) -> Result<(), Error> {
        let mut data = Block::default();
        let mut offset = 0;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;

        for (i, ranges) in CertificateRepr::new().enumerate() {
            data.as_mut().iter_mut().for_each(|value| *value = 0);

            for range in ranges {
                let src = offset..offset + range.len();
                data.as_mut()[range.clone()].copy_from_slice(&pubkey[src]);
                offset += range.len();
            }

            let packet =
                command::Write::new(inner.packet_builder()).slot(key_id, i as u8, &data)?;
            inner.execute_blocking(packet)?;
        }
        Ok(())
    }

    pub fn write_aes_key_blocking(&mut self, key_id: Slot, aes_key: &[u8]) -> Result<(), Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let mut data = Block::default();
        data.as_mut()[..0x10].copy_from_slice(aes_key);
        let packet = command::Write::new(inner.packet_builder()).slot(key_id, 0u8, &data)?;
        inner.execute_blocking(packet).map(drop)
    }

    pub fn is_slot_locked_blocking(&mut self, slot: Slot) -> Result<bool, Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let zone = Zone::Config;
        let size = Size::Word;
        let block = 2;
        let word_offset = 6;
        let packet =
            command::Read::new(inner.packet_builder()).read(zone, size, block, word_offset)?;
        let response = inner.execute_blocking(packet)?;
        let word = Word::try_from(response.as_ref())?;
        let slot_locked_bytes = word.as_ref()[..2]
            .try_into()
            .map(u16::from_le_bytes)
            .unwrap_or_else(|_| unreachable!());
        Ok(slot_locked_bytes & (0x01u16 << slot as u32) == 0x00)
    }

    pub fn is_locked_blocking(&mut self, zone: Zone) -> Result<bool, Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let size = Size::Word;
        let block = 2;
        let word_offset = 5;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            size,
            block,
            word_offset,
        )?;
        let response = inner.execute_blocking(packet)?;
        let word = Word::try_from(response.as_ref())?;
        match zone {
            Zone::Config => Ok(word.as_ref()[3] != 0x55),
            Zone::Data => Ok(word.as_ref()[2] != 0x55),
            Zone::Otp => Err(ErrorKind::BadParam.into()),
        }
    }

    pub fn lock_slot_blocking(&mut self, key_id: Slot) -> Result<(), Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = Lock::new(inner.packet_builder()).slot(key_id)?;
        inner.execute_blocking(packet).map(drop)
    }

    pub fn lock_blocking(&mut self, zone: Zone) -> Result<(), Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = Lock::new(inner.packet_builder()).zone(zone, None)?;
        inner.execute_blocking(packet).map(drop)
    }

    pub fn lock_crc_blocking(&mut self, zone: Zone, crc: u16) -> Result<(), Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = Lock::new(inner.packet_builder()).zone(zone, Some(crc))?;
        inner.execute_blocking(packet).map(drop)
    }

    pub fn chip_options_blocking(&mut self) -> Result<u16, Error> {
        let (block, offset, pos) = Zone::locate_index(Self::CHIP_OPTIONS_INDEX);
        let range = pos as usize..pos as usize + 2;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            Size::Word,
            block,
            offset,
        )?;
        inner.execute_blocking(packet).map(|resp| {
            resp.as_ref()[range]
                .try_into()
                .map(u16::from_le_bytes)
                .unwrap_or_else(|_| unreachable!())
        })
    }

    pub fn permission_blocking(&mut self, slot: Slot) -> Result<u16, Error> {
        let index = Self::SLOT_CONFIG_INDEX + (slot as usize * 2);
        let (block, offset, pos) = Zone::locate_index(index);
        let range = pos as usize..pos as usize + 2;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            Size::Word,
            block,
            offset,
        )?;
        inner.execute_blocking(packet).map(|resp| {
            resp.as_ref()[range]
                .try_into()
                .map(u16::from_le_bytes)
                .unwrap_or_else(|_| unreachable!())
        })
    }

    pub fn key_type_blocking(&mut self, slot: Slot) -> Result<u16, Error> {
        let index = Self::KEY_CONFIG_INDEX + (slot as usize * 2);
        let (block, offset, pos) = Zone::locate_index(index);
        let range = pos as usize..pos as usize + 2;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::Read::new(inner.packet_builder()).read(
            Zone::Config,
            Size::Word,
            block,
            offset,
        )?;
        inner.execute_blocking(packet).map(|resp| {
            resp.as_ref()[range]
                .try_into()
                .map(u16::from_le_bytes)
                .unwrap_or_else(|_| unreachable!())
        })
    }

    pub fn write_config_blocking(
        &mut self,
        size: Size,
        block: u8,
        offset: u8,
        data: &[u8],
    ) -> Result<(), Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::Write::new(inner.packet_builder()).write(
            Zone::Config,
            size,
            block,
            offset,
            data,
        )?;
        inner.execute_blocking(packet).map(drop)
    }

    pub fn read_compressed_cert_blocking(
        &mut self,
        slot: Slot,
    ) -> Result<crate::cert::compressed::CompressedCertificate, Error> {
        if !slot.is_certificate() {
            return Err(ErrorKind::BadParam.into());
        }

        let mut cert_data = [0u8; crate::cert::compressed::CompressedCertificate::SIZE];
        let mut offset = 0;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;

        for (i, ranges) in CompressedCertRepr::new().enumerate() {
            let packet = command::Read::new(inner.packet_builder()).slot(slot, i as u8)?;

            let response = inner.execute_blocking(packet)?;
            for range in ranges {
                let dst = offset..offset + range.len();
                cert_data[dst].copy_from_slice(&response.as_ref()[range.clone()]);
                offset += range.len();
            }
        }

        Ok(crate::cert::compressed::CompressedCertificate::new(
            cert_data,
        ))
    }

    pub fn write_compressed_cert_blocking(
        &mut self,
        slot: Slot,
        cert: &crate::cert::compressed::CompressedCertificate,
    ) -> Result<(), Error> {
        if !slot.is_certificate() {
            return Err(ErrorKind::BadParam.into());
        }

        let mut data = Block::default();
        let mut offset = 0;
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;

        for (i, ranges) in CompressedCertRepr::new().enumerate() {
            data.as_mut().iter_mut().for_each(|value| *value = 0);

            for range in ranges {
                let src = offset..offset + range.len();
                data.as_mut()[range.clone()].copy_from_slice(&cert.as_ref()[src]);
                offset += range.len();
            }

            let packet = command::Write::new(inner.packet_builder()).slot(slot, i as u8, &data)?;
            inner.execute_blocking(packet)?;
        }
        Ok(())
    }

    /// Read a single 32-byte block from the Data08 slot (blocking).
    pub fn read_data08_block_blocking(&mut self, block: u8) -> Result<Block, Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::Read::new(inner.packet_builder()).slot(Slot::Data08, block)?;
        let response = inner.execute_blocking(packet)?;
        Block::try_from(response.as_ref())
    }

    /// Write a single 32-byte block to the Data08 slot (blocking).
    pub fn write_data08_block_blocking(&mut self, block: u8, data: &Block) -> Result<(), Error> {
        let mut inner = self
            .atca
            .inner
            .try_lock()
            .map_err(|_| ErrorKind::MutexLocked)?;
        let packet = command::Write::new(inner.packet_builder()).slot(Slot::Data08, block, data)?;
        inner.execute_blocking(packet).map(drop)
    }

    fn read_addressed_blocking(&mut self, addr: &SlotAddress) -> Result<Block, Error> {
        match addr {
            SlotAddress::Data08(block) => self.read_data08_block_blocking(*block),
            _ => Err(ErrorKind::BadParam.into()),
        }
    }

    fn write_addressed_blocking(&mut self, addr: &SlotAddress, data: &Block) -> Result<(), Error> {
        match addr {
            SlotAddress::Data08(block) => self.write_data08_block_blocking(*block, data),
            _ => Err(ErrorKind::BadParam.into()),
        }
    }

    pub fn read_certificate_blocking(
        &mut self,
        def: &CertificateDefinition<'_>,
        output: &mut [u8],
    ) -> Result<usize, Error> {
        let compressed = self.read_compressed_cert_blocking(def.compressed_slot)?;
        // A private-key slot is secret: its public key must be derived via
        // GenKey, not read back. Public-key / cert slots are read directly.
        let public_key = if def.public_key_slot.is_private_key() {
            self.gen_pubkey_blocking(def.public_key_slot)?
        } else {
            self.pubkey_blocking(def.public_key_slot)?
        };

        let mut serial_buf = [0u8; 32];
        let serial: &[u8] = if let SerialSource::Stored(addr) = &def.serial_source {
            let block = self.read_addressed_blocking(addr)?;
            let count = def.serial_number.count as usize;
            serial_buf[..count].copy_from_slice(&block.as_ref()[..count]);
            &serial_buf[..count]
        } else {
            let device_serial = self.serial_number_blocking()?;
            let mut gen_buf = [0u8; 16];
            let len = {
                let s = def.serial_source.generate(
                    &device_serial,
                    compressed.signer_id(),
                    &mut gen_buf,
                )?;
                s.len()
            };
            serial_buf[..len].copy_from_slice(&gen_buf[..len]);
            &serial_buf[..len]
        };

        let mut subject_buf = [0u8; 64];
        let subject: Option<&[u8]> = match def.subject_source {
            SubjectSource::Template => None,
            SubjectSource::Provided(bytes) => Some(bytes),
            SubjectSource::FromSerial(derive) => {
                let device_serial = self.serial_number_blocking()?;
                let n = derive(&device_serial, &mut subject_buf).ok_or(ErrorKind::BadParam)?;
                Some(&subject_buf[..n])
            }
        };

        def.reconstruct(&compressed, &public_key, serial, subject, output)
    }

    /// Blocking [`write_certificate`](Self::write_certificate); same write order.
    pub fn write_certificate_blocking(
        &mut self,
        def: &CertificateDefinition<'_>,
        der_cert: &[u8],
    ) -> Result<(), Error> {
        let compressed = def.compress(der_cert)?;

        if let SerialSource::Stored(addr) = &def.serial_source {
            let serial = def.extract_serial(der_cert);
            let mut block = Block::default();
            let count = serial.len().min(32);
            block.as_mut()[..count].copy_from_slice(&serial[..count]);
            self.write_addressed_blocking(addr, &block)?;
        }

        self.write_compressed_cert_blocking(def.compressed_slot, &compressed)?;

        Ok(())
    }

    pub fn erase_certificate_blocking(
        &mut self,
        def: &CertificateDefinition<'_>,
    ) -> Result<(), Error> {
        let zero_cert = CompressedCertificate::zeroed();
        self.write_compressed_cert_blocking(def.compressed_slot, &zero_cert)?;

        if let SerialSource::Stored(addr) = &def.serial_source {
            let zero_block = Block::default();
            self.write_addressed_blocking(addr, &zero_block)?;
        }

        Ok(())
    }
}