1use 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#[cfg_attr(not(feature = "unstable_async_trait"), async_trait::async_trait)]
22pub trait Device {
23 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 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 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#[cfg_attr(not(feature = "unstable_async_trait"), async_trait::async_trait)]
65impl<T: Exchange + Send> Device for T {
66 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 let n = encode_request(req, buff)?;
75
76 let resp_bytes = self.exchange(&buff[..n], timeout).await?;
78
79 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 if n == 2 {
94 return Err(Error::Response(resp_bytes[0], resp_bytes[1]));
95 }
96
97 let (resp, _) = RESP::decode(&buff[..n])?;
100
101 Ok(resp)
103 }
104}
105
106fn 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 if buff.len() < 5 + data_len {
114 return Err(ApduError::InvalidLength.into());
115 }
116
117 let h = req.header();
121 index += h.encode(&mut buff[index..])?;
122
123 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 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}