lsdk 0.1.1

Rust SDK for hardware wallets speaking the BOLOS APDU protocol: HID/WebHID transport, device info, genuine check, app management, firmware updates and app signers
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
//! Client for the manager HTTP API (app catalog, firmware metadata).

use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};

/// Default manager API base URL.
pub const DEFAULT_BASE_URL: &str = "https://manager.api.live.ledger.com/api";

/// A device version (hardware family) as known by the API.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceVersion {
    pub id: u32,
    pub name: String,
    #[serde(default)]
    pub display_name: Option<String>,
    #[serde(default)]
    pub target_id: Option<String>,
    #[serde(default)]
    pub providers: Vec<u32>,
    #[serde(default)]
    pub mcu_versions: Vec<u32>,
    #[serde(default)]
    pub se_firmware_final_versions: Vec<u32>,
}

/// A final (installed) secure element firmware.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FinalFirmware {
    pub id: u32,
    pub name: String,
    pub version: String,
    pub perso: String,
    #[serde(default)]
    pub firmware: Option<String>,
    #[serde(default)]
    pub firmware_key: Option<String>,
    #[serde(default)]
    pub hash: Option<String>,
    #[serde(default)]
    pub bytes: Option<u64>,
    #[serde(default)]
    pub mcu_versions: Vec<u32>,
    #[serde(default)]
    pub notes: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub display_name: Option<String>,
}

/// An OS updater: the package that moves a device to a new final firmware.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OsuFirmware {
    pub id: u32,
    pub name: String,
    pub perso: String,
    pub firmware: String,
    pub firmware_key: String,
    #[serde(default)]
    pub hash: Option<String>,
    pub next_se_firmware_final_version: u32,
    #[serde(default)]
    pub notes: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub display_name: Option<String>,
}

/// An MCU firmware version.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct McuVersion {
    pub id: u32,
    pub name: String,
    #[serde(default)]
    pub mcu: Option<u32>,
    #[serde(default)]
    pub providers: Vec<u32>,
    #[serde(default)]
    pub from_bootloader_version: String,
    #[serde(default)]
    pub device_versions: Vec<u32>,
    #[serde(default)]
    pub se_firmware_final_versions: Vec<u32>,
}

/// An app in the catalog (v2 API).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Application {
    pub version_id: u64,
    /// App name, as reported by `LIST_APPS` once installed.
    pub version_name: String,
    #[serde(default)]
    pub version_display_name: Option<String>,
    pub version: String,
    #[serde(default)]
    pub currency_id: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub application_type: Option<String>,
    #[serde(default)]
    pub date_modified: Option<String>,
    #[serde(default)]
    pub icon: Option<String>,
    #[serde(default)]
    pub author_name: Option<String>,
    #[serde(default, rename = "supportURL")]
    pub support_url: Option<String>,
    #[serde(default, rename = "sourceURL")]
    pub source_url: Option<String>,
    /// Full app hash, matches [`crate::os::InstalledApp::hash`].
    pub hash: String,
    pub perso: String,
    pub firmware: String,
    pub firmware_key: String,
    pub delete: String,
    pub delete_key: String,
    #[serde(default)]
    pub bytes: Option<u64>,
    #[serde(default)]
    pub warning: Option<String>,
    #[serde(default)]
    pub is_dev_tools: bool,
    #[serde(default)]
    pub category: Option<u32>,
    #[serde(default)]
    pub parent: Option<u64>,
    /// Name of the app this one depends on (e.g. Ethereum for plugins).
    #[serde(default)]
    pub parent_name: Option<String>,
}

/// A language pack from the catalog.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LanguagePackage {
    /// Language name (`french`, `spanish`...).
    pub language: String,
    #[serde(rename = "languagePackageVersionId")]
    pub language_package_version_id: u64,
    pub version: String,
    #[serde(default)]
    pub language_package_id: Option<u64>,
    /// URL of the install APDU script (one hex APDU per line).
    pub apdu_install_url: String,
    /// URL of the uninstall APDU script.
    #[serde(default)]
    pub apdu_uninstall_url: Option<String>,
    #[serde(default)]
    pub bytes: Option<u64>,
}

impl LanguagePackage {
    /// Device language id of this pack.
    pub fn language_id(&self) -> Option<u8> {
        Some(match self.language.as_str() {
            "english" => 0,
            "french" => 1,
            "spanish" => 2,
            "portuguese" | "brazilian" => 3,
            "german" => 4,
            "russian" => 5,
            "turkish" => 6,
            _ => return None,
        })
    }
}

#[derive(Deserialize)]
struct LatestFirmwareResponse {
    result: String,
    se_firmware_osu_version: Option<OsuFirmware>,
}

/// Manager API client.
#[derive(Clone, Debug)]
pub struct ManagerApi {
    base_url: String,
    /// Firmware distribution salt (staged rollouts). `"0"` by default.
    pub salt: String,
}

impl Default for ManagerApi {
    fn default() -> Self {
        Self::new(DEFAULT_BASE_URL)
    }
}

fn http_err(e: rsurl::Error) -> Error {
    Error::Http(e.to_string())
}

/// Percent-encode a query component (RFC 3986 unreserved characters kept).
fn encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

async fn send(req: rsurl::aio::Request) -> Result<rsurl::aio::Response> {
    #[cfg(not(target_arch = "wasm32"))]
    let resp = rsurl::aio::request(&rsurl::aio::TokioRuntime, &req).await;
    #[cfg(target_arch = "wasm32")]
    let resp = rsurl::aio::request(&req).await;
    resp.map_err(http_err)
}

fn check(url: &str, resp: &rsurl::aio::Response) -> Result<()> {
    if resp.is_success() {
        Ok(())
    } else {
        Err(Error::Http(format!(
            "{url}: HTTP {} {}",
            resp.status, resp.reason
        )))
    }
}

fn request(method: &str, url: &str) -> rsurl::aio::Request {
    rsurl::aio::Request::new(method, url)
        .follow_redirects(true)
        .timeout(std::time::Duration::from_secs(60))
}

impl ManagerApi {
    pub fn new(base_url: impl Into<String>) -> Self {
        Self {
            base_url: base_url.into(),
            salt: "0".into(),
        }
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    async fn get<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<T> {
        let mut url = format!("{}{}", self.base_url, path);
        for (i, (k, v)) in query.iter().enumerate() {
            url.push(if i == 0 { '?' } else { '&' });
            url.push_str(&encode(k));
            url.push('=');
            url.push_str(&encode(v));
        }
        let resp = send(request("GET", &url)).await?;
        if resp.status == 404 {
            return Err(Error::NotFound(format!("{path} {query:?}")));
        }
        check(&url, &resp)?;
        resp.json().map_err(http_err)
    }

    /// Device version from a target id.
    pub async fn get_device_version(&self, target_id: u32, provider: u32) -> Result<DeviceVersion> {
        self.get(
            "/get_device_version",
            &[
                ("target_id", target_id.to_string()),
                ("provider", provider.to_string()),
            ],
        )
        .await
    }

    /// Final firmware from its version name (e.g. `1.4.1`).
    pub async fn get_firmware_version(
        &self,
        device_version: u32,
        version_name: &str,
        provider: u32,
    ) -> Result<FinalFirmware> {
        self.get(
            "/get_firmware_version",
            &[
                ("device_version", device_version.to_string()),
                ("version_name", version_name.to_string()),
                ("provider", provider.to_string()),
            ],
        )
        .await
    }

    /// OSU from its version name (e.g. `1.4.1-osu`).
    pub async fn get_osu_version(
        &self,
        device_version: u32,
        version_name: &str,
        provider: u32,
    ) -> Result<OsuFirmware> {
        self.get(
            "/get_osu_version",
            &[
                ("device_version", device_version.to_string()),
                ("version_name", version_name.to_string()),
                ("provider", provider.to_string()),
            ],
        )
        .await
    }

    /// Final firmware by id.
    pub async fn get_final_firmware_by_id(&self, id: u32) -> Result<FinalFirmware> {
        self.get(&format!("/firmware_final_versions/{id}"), &[])
            .await
    }

    /// Latest available OSU for a device, `None` when up to date.
    pub async fn get_latest_firmware(
        &self,
        current_final_id: u32,
        device_version: u32,
        provider: u32,
    ) -> Result<Option<OsuFirmware>> {
        let r: LatestFirmwareResponse = self
            .get(
                "/get_latest_firmware",
                &[
                    (
                        "current_se_firmware_final_version",
                        current_final_id.to_string(),
                    ),
                    ("device_version", device_version.to_string()),
                    ("provider", provider.to_string()),
                    ("salt", self.salt.clone()),
                ],
            )
            .await?;
        match r.result.as_str() {
            "null" => Ok(None),
            "success" => Ok(r.se_firmware_osu_version),
            other => Err(Error::Http(format!("get_latest_firmware: {other}"))),
        }
    }

    /// All MCU versions.
    pub async fn get_mcu_versions(&self) -> Result<Vec<McuVersion>> {
        self.get("/mcu_versions", &[]).await
    }

    /// App catalog for a device / firmware.
    pub async fn get_apps_by_target(
        &self,
        target_id: u32,
        firmware_version_name: &str,
        provider: u32,
    ) -> Result<Vec<Application>> {
        self.get(
            "/v2/apps/by-target",
            &[
                ("target_id", target_id.to_string()),
                ("provider", provider.to_string()),
                ("firmware_version_name", firmware_version_name.to_string()),
            ],
        )
        .await
    }

    /// Language packs available for a device version and final firmware.
    pub async fn get_language_packages(
        &self,
        device_version: u32,
        final_firmware_id: u32,
    ) -> Result<Vec<LanguagePackage>> {
        self.get(
            "/language-packages",
            &[
                ("device_version", device_version.to_string()),
                (
                    "current_se_firmware_final_version",
                    final_firmware_id.to_string(),
                ),
            ],
        )
        .await
    }

    /// Download a text resource (APDU scripts).
    pub async fn fetch_text(&self, url: &str) -> Result<String> {
        let resp = send(request("GET", url)).await?;
        check(url, &resp)?;
        resp.text().map_err(http_err)
    }

    /// Resolve installed app hashes to catalog entries.
    pub async fn get_apps_by_hash(&self, hashes: &[String]) -> Result<Vec<Option<Application>>> {
        let url = format!("{}/v2/apps/hash", self.base_url);
        let body = serde_json::to_vec(hashes).map_err(|e| Error::Http(e.to_string()))?;
        let req = request("POST", &url)
            .header("Content-Type", "application/json")
            .body(body);
        let resp = send(req).await?;
        check(&url, &resp)?;
        resp.json().map_err(http_err)
    }
}

/// Pick the highest MCU version from a list (semver-ish comparison on `name`).
pub fn find_best_mcu(mcus: &[McuVersion]) -> Option<&McuVersion> {
    mcus.iter()
        .max_by_key(|m| crate::model::parse_version(&m.name))
}