ledger_lib/
device.rs

1//! High-level Ledger [Device] abstraction for application development
2
3use std::time::Duration;
4
5use encdec::{EncDec, Encode};
6use tracing::error;
7
8use ledger_proto::{
9    apdus::{AppInfoReq, AppInfoResp, DeviceInfoReq, DeviceInfoResp},
10    ApduError, ApduReq,
11};
12
13use crate::{
14    info::{AppInfo, DeviceInfo},
15    Error, Exchange,
16};
17
18const APDU_BUFF_LEN: usize = 256;
19
20/// [Device] provides a high-level interface exchanging APDU objects with implementers of [Exchange]
21#[cfg_attr(not(feature = "unstable_async_trait"), async_trait::async_trait)]
22pub trait Device {
23    /// Issue a request APDU, returning a reponse APDU
24    async fn request<'a, 'b, RESP: EncDec<'b, ApduError>>(
25        &mut self,
26        request: impl ApduReq<'a> + Send,
27        buff: &'b mut [u8],
28        timeout: Duration,
29    ) -> Result<RESP, Error>;
30
31    /// Fetch application information
32    async fn app_info(&mut self, timeout: Duration) -> Result<AppInfo, Error> {
33        let mut buff = [0u8; APDU_BUFF_LEN];
34
35        let r = self
36            .request::<AppInfoResp>(AppInfoReq {}, &mut buff[..], timeout)
37            .await?;
38
39        Ok(AppInfo {
40            name: r.name.to_string(),
41            version: r.version.to_string(),
42            flags: r.flags,
43        })
44    }
45
46    /// Fetch device information
47    async fn device_info(&mut self, timeout: Duration) -> Result<DeviceInfo, Error> {
48        let mut buff = [0u8; APDU_BUFF_LEN];
49
50        let r = self
51            .request::<DeviceInfoResp>(DeviceInfoReq {}, &mut buff[..], timeout)
52            .await?;
53
54        Ok(DeviceInfo {
55            target_id: r.target_id,
56            se_version: r.se_version.to_string(),
57            mcu_version: r.mcu_version.to_string(),
58            flags: r.flags.to_vec(),
59        })
60    }
61}
62
63/// Generic [Device] implementation for types supporting [Exchange]
64#[cfg_attr(not(feature = "unstable_async_trait"), async_trait::async_trait)]
65impl<T: Exchange + Send> Device for T {
66    /// Issue a request APDU to a device, encoding and decoding internally then returning a response APDU
67    async fn request<'a, 'b, RESP: EncDec<'b, ApduError>>(
68        &mut self,
69        req: impl ApduReq<'a> + Send,
70        buff: &'b mut [u8],
71        timeout: Duration,
72    ) -> Result<RESP, Error> {
73        // Encode request
74        let n = encode_request(req, buff)?;
75
76        // Send request to device
77        let resp_bytes = self.exchange(&buff[..n], timeout).await?;
78
79        // Copy response back to buffer prior to decode
80        // (these hijinks are required to allow devices to avoid ownership of APDU data)
81        let n = resp_bytes.len();
82        if n > buff.len() {
83            error!(
84                "Response length exceeds buffer length ({} > {})",
85                n,
86                buff.len()
87            );
88            return Err(ApduError::InvalidLength.into());
89        }
90        buff[..n].copy_from_slice(&resp_bytes[..]);
91
92        // Handle error responses (2 bytes long, only a status)
93        if n == 2 {
94            return Err(Error::Response(resp_bytes[0], resp_bytes[1]));
95        }
96
97        // Decode response
98        // TODO: is it useful to also return the status bytes?
99        let (resp, _) = RESP::decode(&buff[..n])?;
100
101        // Return decode response
102        Ok(resp)
103    }
104}
105
106/// Helper to perform APDU request encoding including the header, length, and body
107fn encode_request<'a, REQ: ApduReq<'a>>(req: REQ, buff: &mut [u8]) -> Result<usize, Error> {
108    let mut index = 0;
109
110    let data_len = req.encode_len()?;
111
112    // Check buffer length is reasonable
113    if buff.len() < 5 + data_len {
114        return Err(ApduError::InvalidLength.into());
115    }
116
117    // Encode request object
118
119    // First the header
120    let h = req.header();
121    index += h.encode(&mut buff[index..])?;
122
123    // Then the data length
124    if data_len > u8::MAX as usize {
125        return Err(ApduError::InvalidLength.into());
126    }
127    buff[index] = data_len as u8;
128    index += 1;
129
130    // Then finally the data
131    index += req.encode(&mut buff[index..])?;
132
133    Ok(index)
134}
135
136#[cfg(test)]
137mod tests {
138    use ledger_proto::{apdus::AppInfoReq, ApduStatic};
139
140    use super::encode_request;
141
142    #[test]
143    fn test_encode_requests() {
144        let mut buff = [0u8; 256];
145
146        let req = AppInfoReq {};
147        let n = encode_request(req, &mut buff).unwrap();
148        assert_eq!(n, 5);
149        assert_eq!(
150            &buff[..n],
151            &[AppInfoReq::CLA, AppInfoReq::INS, 0x00, 0x00, 0x00]
152        );
153    }
154}