Skip to main content

at_cryptoauth/client/
memory.rs

1//! Memory and configuration operations
2
3use crate::Block;
4use crate::cert::compressed::{
5    CertificateDefinition, CompressedCertificate, SerialSource, SubjectSource,
6};
7use crate::command::{self, Lock, PublicKey, Serial, Word};
8use crate::error::{Error, ErrorKind};
9use crate::memory::{CertificateRepr, CompressedCertRepr, Size, Slot, SlotAddress, Zone};
10use embassy_sync::blocking_mutex::raw::RawMutex;
11
12use super::AtCaClient;
13
14pub struct Memory<'a, M: RawMutex, PHY> {
15    pub(crate) atca: &'a AtCaClient<M, PHY>,
16}
17
18impl<'a, M: RawMutex, PHY> Memory<'a, M, PHY> {
19    pub(crate) const SLOT_CONFIG_INDEX: usize = 20;
20    pub(crate) const CHIP_OPTIONS_INDEX: usize = 90;
21    pub(crate) const KEY_CONFIG_INDEX: usize = 96;
22}
23
24impl<'a, M, PHY> Memory<'a, M, PHY>
25where
26    PHY: embedded_hal_async::i2c::I2c,
27    M: RawMutex,
28{
29    pub async fn serial_number(&self) -> Result<Serial, Error> {
30        let mut inner = self.atca.inner.lock().await;
31        let packet =
32            command::Read::new(inner.packet_builder()).read(Zone::Config, Size::Block, 0, 0)?;
33        inner.execute(packet).await?.as_ref().try_into()
34    }
35
36    pub async fn pubkey(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
37        let mut pubkey = PublicKey::default();
38        let mut offset = 0;
39
40        for (i, ranges) in CertificateRepr::new().enumerate() {
41            let mut inner = self.atca.inner.lock().await;
42            let packet = command::Read::new(inner.packet_builder()).slot(key_id, i as u8)?;
43
44            let response = inner.execute(packet).await?;
45            for range in ranges {
46                let dst = offset..offset + range.len();
47                pubkey.as_mut()[dst].copy_from_slice(&response.as_ref()[range.clone()]);
48                offset += range.len();
49            }
50        }
51
52        Ok(pubkey)
53    }
54
55    /// Derive the public key of a private-key slot via GenKey.
56    ///
57    /// A private-key slot is secret and cannot be read back with [`Self::pubkey`]
58    /// (the device rejects the Read with an execution error); its public key is
59    /// recomputed from the stored private key instead.
60    pub async fn gen_pubkey(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
61        let mut inner = self.atca.inner.lock().await;
62        let packet = command::GenKey::new(inner.packet_builder()).public_key(key_id)?;
63        inner.execute(packet).await?.as_ref().try_into()
64    }
65
66    pub async fn write_pubkey(&mut self, key_id: Slot, pubkey: &[u8]) -> Result<(), Error> {
67        let mut data = Block::default();
68        let mut offset = 0;
69
70        for (i, ranges) in CertificateRepr::new().enumerate() {
71            let mut inner = self.atca.inner.lock().await;
72            data.as_mut().iter_mut().for_each(|value| *value = 0);
73
74            for range in ranges {
75                let src = offset..offset + range.len();
76                data.as_mut()[range.clone()].copy_from_slice(&pubkey[src]);
77                offset += range.len();
78            }
79
80            let packet =
81                command::Write::new(inner.packet_builder()).slot(key_id, i as u8, &data)?;
82            inner.execute(packet).await?;
83        }
84        Ok(())
85    }
86
87    pub async fn write_aes_key(&mut self, key_id: Slot, aes_key: &[u8]) -> Result<(), Error> {
88        let mut inner = self.atca.inner.lock().await;
89        let mut data = Block::default();
90        data.as_mut()[..0x10].copy_from_slice(aes_key);
91        let packet = command::Write::new(inner.packet_builder()).slot(key_id, 0u8, &data)?;
92        inner.execute(packet).await.map(drop)
93    }
94
95    pub async fn is_slot_locked(&mut self, slot: Slot) -> Result<bool, Error> {
96        let mut inner = self.atca.inner.lock().await;
97        let zone = Zone::Config;
98        let size = Size::Word;
99        let block = 2;
100        let word_offset = 6;
101        let packet =
102            command::Read::new(inner.packet_builder()).read(zone, size, block, word_offset)?;
103        let response = inner.execute(packet).await?;
104        let word = Word::try_from(response.as_ref())?;
105        let slot_locked_bytes = word.as_ref()[..2]
106            .try_into()
107            .map(u16::from_le_bytes)
108            .unwrap_or_else(|_| unreachable!());
109        Ok(slot_locked_bytes & (0x01u16 << slot as u32) == 0x00)
110    }
111
112    pub async fn is_locked(&mut self, zone: Zone) -> Result<bool, Error> {
113        let mut inner = self.atca.inner.lock().await;
114        let size = Size::Word;
115        let block = 2;
116        let word_offset = 5;
117        let packet = command::Read::new(inner.packet_builder()).read(
118            Zone::Config,
119            size,
120            block,
121            word_offset,
122        )?;
123        let response = inner.execute(packet).await?;
124        let word = Word::try_from(response.as_ref())?;
125        match zone {
126            Zone::Config => Ok(word.as_ref()[3] != 0x55),
127            Zone::Data => Ok(word.as_ref()[2] != 0x55),
128            Zone::Otp => Err(ErrorKind::BadParam.into()),
129        }
130    }
131
132    pub async fn lock_slot(&mut self, key_id: Slot) -> Result<(), Error> {
133        let mut inner = self.atca.inner.lock().await;
134        let packet = Lock::new(inner.packet_builder()).slot(key_id)?;
135        inner.execute(packet).await.map(drop)
136    }
137
138    pub async fn lock(&mut self, zone: Zone) -> Result<(), Error> {
139        let mut inner = self.atca.inner.lock().await;
140        let packet = Lock::new(inner.packet_builder()).zone(zone, None)?;
141        inner.execute(packet).await.map(drop)
142    }
143
144    pub async fn lock_crc(&mut self, zone: Zone, crc: u16) -> Result<(), Error> {
145        let mut inner = self.atca.inner.lock().await;
146        let packet = Lock::new(inner.packet_builder()).zone(zone, Some(crc))?;
147        inner.execute(packet).await.map(drop)
148    }
149
150    pub async fn chip_options(&mut self) -> Result<u16, Error> {
151        let (block, offset, pos) = Zone::locate_index(Self::CHIP_OPTIONS_INDEX);
152        let range = pos as usize..pos as usize + 2;
153        let mut inner = self.atca.inner.lock().await;
154        let packet = command::Read::new(inner.packet_builder()).read(
155            Zone::Config,
156            Size::Word,
157            block,
158            offset,
159        )?;
160        inner.execute(packet).await.map(|resp| {
161            resp.as_ref()[range]
162                .try_into()
163                .map(u16::from_le_bytes)
164                .unwrap_or_else(|_| unreachable!())
165        })
166    }
167
168    pub async fn permission(&mut self, slot: Slot) -> Result<u16, Error> {
169        let index = Self::SLOT_CONFIG_INDEX + (slot as usize * 2);
170        let (block, offset, pos) = Zone::locate_index(index);
171        let range = pos as usize..pos as usize + 2;
172        let mut inner = self.atca.inner.lock().await;
173        let packet = command::Read::new(inner.packet_builder()).read(
174            Zone::Config,
175            Size::Word,
176            block,
177            offset,
178        )?;
179        inner.execute(packet).await.map(|resp| {
180            resp.as_ref()[range]
181                .try_into()
182                .map(u16::from_le_bytes)
183                .unwrap_or_else(|_| unreachable!())
184        })
185    }
186
187    pub async fn key_type(&mut self, slot: Slot) -> Result<u16, Error> {
188        let index = Self::KEY_CONFIG_INDEX + (slot as usize * 2);
189        let (block, offset, pos) = Zone::locate_index(index);
190        let range = pos as usize..pos as usize + 2;
191        let mut inner = self.atca.inner.lock().await;
192        let packet = command::Read::new(inner.packet_builder()).read(
193            Zone::Config,
194            Size::Word,
195            block,
196            offset,
197        )?;
198        inner.execute(packet).await.map(|resp| {
199            resp.as_ref()[range]
200                .try_into()
201                .map(u16::from_le_bytes)
202                .unwrap_or_else(|_| unreachable!())
203        })
204    }
205
206    /// # Safety
207    ///
208    /// Caller must ensure the config zone parameters (size, block, offset) are valid
209    /// for the target device and do not cause out-of-bounds reads.
210    pub async unsafe fn read_config(
211        &mut self,
212        size: Size,
213        block: u8,
214        offset: u8,
215    ) -> Result<heapless::Vec<u8, { Size::Block.len() }>, Error> {
216        let mut inner = self.atca.inner.lock().await;
217        let packet =
218            command::Read::new(inner.packet_builder()).read(Zone::Config, size, block, offset)?;
219        inner.execute(packet).await.and_then(|d| {
220            heapless::Vec::from_slice(d.as_ref()).map_err(|_| ErrorKind::SmallBuffer.into())
221        })
222    }
223
224    pub async fn write_config(
225        &mut self,
226        size: Size,
227        block: u8,
228        offset: u8,
229        data: &[u8],
230    ) -> Result<(), Error> {
231        let mut inner = self.atca.inner.lock().await;
232        let packet = command::Write::new(inner.packet_builder()).write(
233            Zone::Config,
234            size,
235            block,
236            offset,
237            data,
238        )?;
239        inner.execute(packet).await.map(drop)
240    }
241
242    pub async fn read_compressed_cert(
243        &mut self,
244        slot: Slot,
245    ) -> Result<crate::cert::compressed::CompressedCertificate, Error> {
246        if !slot.is_certificate() {
247            return Err(ErrorKind::BadParam.into());
248        }
249
250        let mut cert_data = [0u8; crate::cert::compressed::CompressedCertificate::SIZE];
251        let mut offset = 0;
252
253        for (i, ranges) in CompressedCertRepr::new().enumerate() {
254            let mut inner = self.atca.inner.lock().await;
255            let packet = command::Read::new(inner.packet_builder()).slot(slot, i as u8)?;
256
257            let response = inner.execute(packet).await?;
258            for range in ranges {
259                let dst = offset..offset + range.len();
260                cert_data[dst].copy_from_slice(&response.as_ref()[range.clone()]);
261                offset += range.len();
262            }
263        }
264
265        Ok(crate::cert::compressed::CompressedCertificate::new(
266            cert_data,
267        ))
268    }
269
270    pub async fn write_compressed_cert(
271        &mut self,
272        slot: Slot,
273        cert: &crate::cert::compressed::CompressedCertificate,
274    ) -> Result<(), Error> {
275        if !slot.is_certificate() {
276            return Err(ErrorKind::BadParam.into());
277        }
278
279        let mut data = Block::default();
280        let mut offset = 0;
281
282        for (i, ranges) in CompressedCertRepr::new().enumerate() {
283            let mut inner = self.atca.inner.lock().await;
284            data.as_mut().iter_mut().for_each(|value| *value = 0);
285
286            for range in ranges {
287                let src = offset..offset + range.len();
288                data.as_mut()[range.clone()].copy_from_slice(&cert.as_ref()[src]);
289                offset += range.len();
290            }
291
292            let packet = command::Write::new(inner.packet_builder()).slot(slot, i as u8, &data)?;
293            inner.execute(packet).await?;
294        }
295        Ok(())
296    }
297
298    /// Read a single 32-byte block from the Data08 slot.
299    pub async fn read_data08_block(&mut self, block: u8) -> Result<Block, Error> {
300        let mut inner = self.atca.inner.lock().await;
301        let packet = command::Read::new(inner.packet_builder()).slot(Slot::Data08, block)?;
302        let response = inner.execute(packet).await?;
303        Block::try_from(response.as_ref())
304    }
305
306    /// Write a single 32-byte block to the Data08 slot.
307    pub async fn write_data08_block(&mut self, block: u8, data: &Block) -> Result<(), Error> {
308        let mut inner = self.atca.inner.lock().await;
309        let packet = command::Write::new(inner.packet_builder()).slot(Slot::Data08, block, data)?;
310        inner.execute(packet).await.map(drop)
311    }
312
313    /// Read a block from a SlotAddress (dispatches between cert slots and Data08 blocks).
314    async fn read_addressed(&mut self, addr: &SlotAddress) -> Result<Block, Error> {
315        match addr {
316            SlotAddress::Data08(block) => self.read_data08_block(*block).await,
317            _ => Err(ErrorKind::BadParam.into()),
318        }
319    }
320
321    /// Write a block to a SlotAddress (dispatches between cert slots and Data08 blocks).
322    async fn write_addressed(&mut self, addr: &SlotAddress, data: &Block) -> Result<(), Error> {
323        match addr {
324            SlotAddress::Data08(block) => self.write_data08_block(*block, data).await,
325            _ => Err(ErrorKind::BadParam.into()),
326        }
327    }
328
329    pub async fn read_certificate(
330        &mut self,
331        def: &CertificateDefinition<'_>,
332        output: &mut [u8],
333    ) -> Result<usize, Error> {
334        let compressed = self.read_compressed_cert(def.compressed_slot).await?;
335        // A private-key slot is secret: its public key must be derived via
336        // GenKey, not read back. Public-key / cert slots are read directly.
337        let public_key = if def.public_key_slot.is_private_key() {
338            self.gen_pubkey(def.public_key_slot).await?
339        } else {
340            self.pubkey(def.public_key_slot).await?
341        };
342
343        let mut serial_buf = [0u8; 32];
344        let serial: &[u8] = if let SerialSource::Stored(addr) = &def.serial_source {
345            // Read serial directly from device storage
346            let block = self.read_addressed(addr).await?;
347            let count = def.serial_number.count as usize;
348            serial_buf[..count].copy_from_slice(&block.as_ref()[..count]);
349            &serial_buf[..count]
350        } else {
351            let device_serial = self.serial_number().await?;
352            let mut gen_buf = [0u8; 16];
353            let len = {
354                let s = def.serial_source.generate(
355                    &device_serial,
356                    compressed.signer_id(),
357                    &mut gen_buf,
358                )?;
359                s.len()
360            };
361            serial_buf[..len].copy_from_slice(&gen_buf[..len]);
362            &serial_buf[..len]
363        };
364
365        // Resolve the subject from the definition (mirrors serial resolution).
366        let mut subject_buf = [0u8; 64];
367        let subject: Option<&[u8]> = match def.subject_source {
368            SubjectSource::Template => None,
369            SubjectSource::Provided(bytes) => Some(bytes),
370            SubjectSource::FromSerial(derive) => {
371                let device_serial = self.serial_number().await?;
372                let n = derive(&device_serial, &mut subject_buf).ok_or(ErrorKind::BadParam)?;
373                Some(&subject_buf[..n])
374            }
375        };
376
377        def.reconstruct(&compressed, &public_key, serial, subject, output)
378    }
379
380    /// Compress a DER certificate and write it to the ATECC.
381    ///
382    /// If the serial source is `Stored`, writes the serial number to the
383    /// addressed Data08 block first, then the compressed cert to the cert slot.
384    ///
385    /// That order matters: the two writes are separate ATECC transactions, and
386    /// the cert slot is what decides whether a certificate is present at all.
387    /// [`read_certificate`](Self::read_certificate) fails on a zeroed cert slot
388    /// (its encoded date has no valid month or day) but silently splices in
389    /// whatever the serial block holds. Writing the cert slot last makes it the
390    /// commit point, so an interrupted write leaves the slot unreadable and the
391    /// caller retries. The reverse order leaves a certificate that reconstructs
392    /// cleanly against a stale serial, which no read can detect.
393    pub async fn write_certificate(
394        &mut self,
395        def: &CertificateDefinition<'_>,
396        der_cert: &[u8],
397    ) -> Result<(), Error> {
398        let compressed = def.compress(der_cert)?;
399
400        // If serial is stored externally, write it to the Data08 block
401        if let SerialSource::Stored(addr) = &def.serial_source {
402            let serial = def.extract_serial(der_cert);
403            let mut block = Block::default();
404            let count = serial.len().min(32);
405            block.as_mut()[..count].copy_from_slice(&serial[..count]);
406            self.write_addressed(addr, &block).await?;
407        }
408
409        self.write_compressed_cert(def.compressed_slot, &compressed)
410            .await?;
411
412        Ok(())
413    }
414
415    /// Erase a certificate from the ATECC (zero the cert slot and stored serial).
416    ///
417    /// Zeroes the cert slot first — the mirror of
418    /// [`write_certificate`](Self::write_certificate)'s order, and correct for
419    /// the same reason: it invalidates the commit point up front, so a half-done
420    /// erase still reads as "no certificate" rather than as a live one.
421    pub async fn erase_certificate(
422        &mut self,
423        def: &CertificateDefinition<'_>,
424    ) -> Result<(), Error> {
425        let zero_cert = CompressedCertificate::zeroed();
426        self.write_compressed_cert(def.compressed_slot, &zero_cert)
427            .await?;
428
429        if let SerialSource::Stored(addr) = &def.serial_source {
430            let zero_block = Block::default();
431            self.write_addressed(addr, &zero_block).await?;
432        }
433
434        Ok(())
435    }
436}
437
438impl<'a, M, PHY> Memory<'a, M, PHY>
439where
440    PHY: embedded_hal::i2c::I2c,
441    M: RawMutex,
442{
443    pub fn serial_number_blocking(&mut self) -> Result<Serial, Error> {
444        let mut inner = self
445            .atca
446            .inner
447            .try_lock()
448            .map_err(|_| ErrorKind::MutexLocked)?;
449        let packet =
450            command::Read::new(inner.packet_builder()).read(Zone::Config, Size::Block, 0, 0)?;
451        inner.execute_blocking(packet)?.as_ref().try_into()
452    }
453
454    pub fn pubkey_blocking(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
455        let mut pubkey = PublicKey::default();
456        let mut offset = 0;
457        let mut inner = self
458            .atca
459            .inner
460            .try_lock()
461            .map_err(|_| ErrorKind::MutexLocked)?;
462
463        for (i, ranges) in CertificateRepr::new().enumerate() {
464            let packet = command::Read::new(inner.packet_builder()).slot(key_id, i as u8)?;
465
466            let response = inner.execute_blocking(packet)?;
467            for range in ranges {
468                let dst = offset..offset + range.len();
469                pubkey.as_mut()[dst].copy_from_slice(&response.as_ref()[range.clone()]);
470                offset += range.len();
471            }
472        }
473
474        Ok(pubkey)
475    }
476
477    /// Blocking counterpart to [`Self::gen_pubkey`].
478    pub fn gen_pubkey_blocking(&mut self, key_id: Slot) -> Result<PublicKey, Error> {
479        let mut inner = self
480            .atca
481            .inner
482            .try_lock()
483            .map_err(|_| ErrorKind::MutexLocked)?;
484        let packet = command::GenKey::new(inner.packet_builder()).public_key(key_id)?;
485        inner.execute_blocking(packet)?.as_ref().try_into()
486    }
487
488    pub fn write_pubkey_blocking(&mut self, key_id: Slot, pubkey: &[u8]) -> Result<(), Error> {
489        let mut data = Block::default();
490        let mut offset = 0;
491        let mut inner = self
492            .atca
493            .inner
494            .try_lock()
495            .map_err(|_| ErrorKind::MutexLocked)?;
496
497        for (i, ranges) in CertificateRepr::new().enumerate() {
498            data.as_mut().iter_mut().for_each(|value| *value = 0);
499
500            for range in ranges {
501                let src = offset..offset + range.len();
502                data.as_mut()[range.clone()].copy_from_slice(&pubkey[src]);
503                offset += range.len();
504            }
505
506            let packet =
507                command::Write::new(inner.packet_builder()).slot(key_id, i as u8, &data)?;
508            inner.execute_blocking(packet)?;
509        }
510        Ok(())
511    }
512
513    pub fn write_aes_key_blocking(&mut self, key_id: Slot, aes_key: &[u8]) -> Result<(), Error> {
514        let mut inner = self
515            .atca
516            .inner
517            .try_lock()
518            .map_err(|_| ErrorKind::MutexLocked)?;
519        let mut data = Block::default();
520        data.as_mut()[..0x10].copy_from_slice(aes_key);
521        let packet = command::Write::new(inner.packet_builder()).slot(key_id, 0u8, &data)?;
522        inner.execute_blocking(packet).map(drop)
523    }
524
525    pub fn is_slot_locked_blocking(&mut self, slot: Slot) -> Result<bool, Error> {
526        let mut inner = self
527            .atca
528            .inner
529            .try_lock()
530            .map_err(|_| ErrorKind::MutexLocked)?;
531        let zone = Zone::Config;
532        let size = Size::Word;
533        let block = 2;
534        let word_offset = 6;
535        let packet =
536            command::Read::new(inner.packet_builder()).read(zone, size, block, word_offset)?;
537        let response = inner.execute_blocking(packet)?;
538        let word = Word::try_from(response.as_ref())?;
539        let slot_locked_bytes = word.as_ref()[..2]
540            .try_into()
541            .map(u16::from_le_bytes)
542            .unwrap_or_else(|_| unreachable!());
543        Ok(slot_locked_bytes & (0x01u16 << slot as u32) == 0x00)
544    }
545
546    pub fn is_locked_blocking(&mut self, zone: Zone) -> Result<bool, Error> {
547        let mut inner = self
548            .atca
549            .inner
550            .try_lock()
551            .map_err(|_| ErrorKind::MutexLocked)?;
552        let size = Size::Word;
553        let block = 2;
554        let word_offset = 5;
555        let packet = command::Read::new(inner.packet_builder()).read(
556            Zone::Config,
557            size,
558            block,
559            word_offset,
560        )?;
561        let response = inner.execute_blocking(packet)?;
562        let word = Word::try_from(response.as_ref())?;
563        match zone {
564            Zone::Config => Ok(word.as_ref()[3] != 0x55),
565            Zone::Data => Ok(word.as_ref()[2] != 0x55),
566            Zone::Otp => Err(ErrorKind::BadParam.into()),
567        }
568    }
569
570    pub fn lock_slot_blocking(&mut self, key_id: Slot) -> Result<(), Error> {
571        let mut inner = self
572            .atca
573            .inner
574            .try_lock()
575            .map_err(|_| ErrorKind::MutexLocked)?;
576        let packet = Lock::new(inner.packet_builder()).slot(key_id)?;
577        inner.execute_blocking(packet).map(drop)
578    }
579
580    pub fn lock_blocking(&mut self, zone: Zone) -> Result<(), Error> {
581        let mut inner = self
582            .atca
583            .inner
584            .try_lock()
585            .map_err(|_| ErrorKind::MutexLocked)?;
586        let packet = Lock::new(inner.packet_builder()).zone(zone, None)?;
587        inner.execute_blocking(packet).map(drop)
588    }
589
590    pub fn lock_crc_blocking(&mut self, zone: Zone, crc: u16) -> Result<(), Error> {
591        let mut inner = self
592            .atca
593            .inner
594            .try_lock()
595            .map_err(|_| ErrorKind::MutexLocked)?;
596        let packet = Lock::new(inner.packet_builder()).zone(zone, Some(crc))?;
597        inner.execute_blocking(packet).map(drop)
598    }
599
600    pub fn chip_options_blocking(&mut self) -> Result<u16, Error> {
601        let (block, offset, pos) = Zone::locate_index(Self::CHIP_OPTIONS_INDEX);
602        let range = pos as usize..pos as usize + 2;
603        let mut inner = self
604            .atca
605            .inner
606            .try_lock()
607            .map_err(|_| ErrorKind::MutexLocked)?;
608        let packet = command::Read::new(inner.packet_builder()).read(
609            Zone::Config,
610            Size::Word,
611            block,
612            offset,
613        )?;
614        inner.execute_blocking(packet).map(|resp| {
615            resp.as_ref()[range]
616                .try_into()
617                .map(u16::from_le_bytes)
618                .unwrap_or_else(|_| unreachable!())
619        })
620    }
621
622    pub fn permission_blocking(&mut self, slot: Slot) -> Result<u16, Error> {
623        let index = Self::SLOT_CONFIG_INDEX + (slot as usize * 2);
624        let (block, offset, pos) = Zone::locate_index(index);
625        let range = pos as usize..pos as usize + 2;
626        let mut inner = self
627            .atca
628            .inner
629            .try_lock()
630            .map_err(|_| ErrorKind::MutexLocked)?;
631        let packet = command::Read::new(inner.packet_builder()).read(
632            Zone::Config,
633            Size::Word,
634            block,
635            offset,
636        )?;
637        inner.execute_blocking(packet).map(|resp| {
638            resp.as_ref()[range]
639                .try_into()
640                .map(u16::from_le_bytes)
641                .unwrap_or_else(|_| unreachable!())
642        })
643    }
644
645    pub fn key_type_blocking(&mut self, slot: Slot) -> Result<u16, Error> {
646        let index = Self::KEY_CONFIG_INDEX + (slot as usize * 2);
647        let (block, offset, pos) = Zone::locate_index(index);
648        let range = pos as usize..pos as usize + 2;
649        let mut inner = self
650            .atca
651            .inner
652            .try_lock()
653            .map_err(|_| ErrorKind::MutexLocked)?;
654        let packet = command::Read::new(inner.packet_builder()).read(
655            Zone::Config,
656            Size::Word,
657            block,
658            offset,
659        )?;
660        inner.execute_blocking(packet).map(|resp| {
661            resp.as_ref()[range]
662                .try_into()
663                .map(u16::from_le_bytes)
664                .unwrap_or_else(|_| unreachable!())
665        })
666    }
667
668    pub fn write_config_blocking(
669        &mut self,
670        size: Size,
671        block: u8,
672        offset: u8,
673        data: &[u8],
674    ) -> Result<(), Error> {
675        let mut inner = self
676            .atca
677            .inner
678            .try_lock()
679            .map_err(|_| ErrorKind::MutexLocked)?;
680        let packet = command::Write::new(inner.packet_builder()).write(
681            Zone::Config,
682            size,
683            block,
684            offset,
685            data,
686        )?;
687        inner.execute_blocking(packet).map(drop)
688    }
689
690    pub fn read_compressed_cert_blocking(
691        &mut self,
692        slot: Slot,
693    ) -> Result<crate::cert::compressed::CompressedCertificate, Error> {
694        if !slot.is_certificate() {
695            return Err(ErrorKind::BadParam.into());
696        }
697
698        let mut cert_data = [0u8; crate::cert::compressed::CompressedCertificate::SIZE];
699        let mut offset = 0;
700        let mut inner = self
701            .atca
702            .inner
703            .try_lock()
704            .map_err(|_| ErrorKind::MutexLocked)?;
705
706        for (i, ranges) in CompressedCertRepr::new().enumerate() {
707            let packet = command::Read::new(inner.packet_builder()).slot(slot, i as u8)?;
708
709            let response = inner.execute_blocking(packet)?;
710            for range in ranges {
711                let dst = offset..offset + range.len();
712                cert_data[dst].copy_from_slice(&response.as_ref()[range.clone()]);
713                offset += range.len();
714            }
715        }
716
717        Ok(crate::cert::compressed::CompressedCertificate::new(
718            cert_data,
719        ))
720    }
721
722    pub fn write_compressed_cert_blocking(
723        &mut self,
724        slot: Slot,
725        cert: &crate::cert::compressed::CompressedCertificate,
726    ) -> Result<(), Error> {
727        if !slot.is_certificate() {
728            return Err(ErrorKind::BadParam.into());
729        }
730
731        let mut data = Block::default();
732        let mut offset = 0;
733        let mut inner = self
734            .atca
735            .inner
736            .try_lock()
737            .map_err(|_| ErrorKind::MutexLocked)?;
738
739        for (i, ranges) in CompressedCertRepr::new().enumerate() {
740            data.as_mut().iter_mut().for_each(|value| *value = 0);
741
742            for range in ranges {
743                let src = offset..offset + range.len();
744                data.as_mut()[range.clone()].copy_from_slice(&cert.as_ref()[src]);
745                offset += range.len();
746            }
747
748            let packet = command::Write::new(inner.packet_builder()).slot(slot, i as u8, &data)?;
749            inner.execute_blocking(packet)?;
750        }
751        Ok(())
752    }
753
754    /// Read a single 32-byte block from the Data08 slot (blocking).
755    pub fn read_data08_block_blocking(&mut self, block: u8) -> Result<Block, Error> {
756        let mut inner = self
757            .atca
758            .inner
759            .try_lock()
760            .map_err(|_| ErrorKind::MutexLocked)?;
761        let packet = command::Read::new(inner.packet_builder()).slot(Slot::Data08, block)?;
762        let response = inner.execute_blocking(packet)?;
763        Block::try_from(response.as_ref())
764    }
765
766    /// Write a single 32-byte block to the Data08 slot (blocking).
767    pub fn write_data08_block_blocking(&mut self, block: u8, data: &Block) -> Result<(), Error> {
768        let mut inner = self
769            .atca
770            .inner
771            .try_lock()
772            .map_err(|_| ErrorKind::MutexLocked)?;
773        let packet = command::Write::new(inner.packet_builder()).slot(Slot::Data08, block, data)?;
774        inner.execute_blocking(packet).map(drop)
775    }
776
777    fn read_addressed_blocking(&mut self, addr: &SlotAddress) -> Result<Block, Error> {
778        match addr {
779            SlotAddress::Data08(block) => self.read_data08_block_blocking(*block),
780            _ => Err(ErrorKind::BadParam.into()),
781        }
782    }
783
784    fn write_addressed_blocking(&mut self, addr: &SlotAddress, data: &Block) -> Result<(), Error> {
785        match addr {
786            SlotAddress::Data08(block) => self.write_data08_block_blocking(*block, data),
787            _ => Err(ErrorKind::BadParam.into()),
788        }
789    }
790
791    pub fn read_certificate_blocking(
792        &mut self,
793        def: &CertificateDefinition<'_>,
794        output: &mut [u8],
795    ) -> Result<usize, Error> {
796        let compressed = self.read_compressed_cert_blocking(def.compressed_slot)?;
797        // A private-key slot is secret: its public key must be derived via
798        // GenKey, not read back. Public-key / cert slots are read directly.
799        let public_key = if def.public_key_slot.is_private_key() {
800            self.gen_pubkey_blocking(def.public_key_slot)?
801        } else {
802            self.pubkey_blocking(def.public_key_slot)?
803        };
804
805        let mut serial_buf = [0u8; 32];
806        let serial: &[u8] = if let SerialSource::Stored(addr) = &def.serial_source {
807            let block = self.read_addressed_blocking(addr)?;
808            let count = def.serial_number.count as usize;
809            serial_buf[..count].copy_from_slice(&block.as_ref()[..count]);
810            &serial_buf[..count]
811        } else {
812            let device_serial = self.serial_number_blocking()?;
813            let mut gen_buf = [0u8; 16];
814            let len = {
815                let s = def.serial_source.generate(
816                    &device_serial,
817                    compressed.signer_id(),
818                    &mut gen_buf,
819                )?;
820                s.len()
821            };
822            serial_buf[..len].copy_from_slice(&gen_buf[..len]);
823            &serial_buf[..len]
824        };
825
826        let mut subject_buf = [0u8; 64];
827        let subject: Option<&[u8]> = match def.subject_source {
828            SubjectSource::Template => None,
829            SubjectSource::Provided(bytes) => Some(bytes),
830            SubjectSource::FromSerial(derive) => {
831                let device_serial = self.serial_number_blocking()?;
832                let n = derive(&device_serial, &mut subject_buf).ok_or(ErrorKind::BadParam)?;
833                Some(&subject_buf[..n])
834            }
835        };
836
837        def.reconstruct(&compressed, &public_key, serial, subject, output)
838    }
839
840    /// Blocking [`write_certificate`](Self::write_certificate); same write order.
841    pub fn write_certificate_blocking(
842        &mut self,
843        def: &CertificateDefinition<'_>,
844        der_cert: &[u8],
845    ) -> Result<(), Error> {
846        let compressed = def.compress(der_cert)?;
847
848        if let SerialSource::Stored(addr) = &def.serial_source {
849            let serial = def.extract_serial(der_cert);
850            let mut block = Block::default();
851            let count = serial.len().min(32);
852            block.as_mut()[..count].copy_from_slice(&serial[..count]);
853            self.write_addressed_blocking(addr, &block)?;
854        }
855
856        self.write_compressed_cert_blocking(def.compressed_slot, &compressed)?;
857
858        Ok(())
859    }
860
861    pub fn erase_certificate_blocking(
862        &mut self,
863        def: &CertificateDefinition<'_>,
864    ) -> Result<(), Error> {
865        let zero_cert = CompressedCertificate::zeroed();
866        self.write_compressed_cert_blocking(def.compressed_slot, &zero_cert)?;
867
868        if let SerialSource::Stored(addr) = &def.serial_source {
869            let zero_block = Block::default();
870            self.write_addressed_blocking(addr, &zero_block)?;
871        }
872
873        Ok(())
874    }
875}