ledger_lib/
lib.rs

1//! A Ledger hardware wallet communication library
2//!
3//! [Device] provides a high-level API for exchanging APDUs with Ledger devices using the [ledger_proto] traits.
4//! This is suitable for extension with application-specific interface traits, and automatically
5//! implemented over [Exchange] for low-level byte exchange with devices.
6//!
7//! [LedgerProvider] and [LedgerHandle] provide a high-level tokio-compatible [Transport]
8//! for application integration, supporting connecting to and interacting with ledger devices.
9//! This uses a pinned thread to avoid thread safety issues with `hidapi` and async executors.
10//!
11//! Low-level [Transport] implementations are provided for [USB/HID](transport::UsbTransport),
12//! [BLE](transport::BleTransport) and [TCP](transport::TcpTransport), with a [Generic](transport::GenericTransport)
13//! implementation providing a common interface over all enabled transports.
14//!
15//! ## Safety
16//!
17//! Transports are currently marked as `Send` due to limitations of [async_trait] and are NOT all
18//! thread safe. If you're calling this from an async context, please use [LedgerProvider].
19//!
20//! This will be corrected when the unstable async trait feature is stabilised,
21//! which until then can be opted-into using the `unstable_async_trait` feature
22//!
23//! ## Examples
24//!
25//! ```no_run
26//! use ledger_lib::{LedgerProvider, Filters, Transport, Device, DEFAULT_TIMEOUT};
27//!
28//! #[tokio::main]
29//! async fn main() -> anyhow::Result<()> {
30//!     // Fetch provider handle
31//!     let mut provider = LedgerProvider::init().await;
32//!
33//!     // List available devices
34//!     let devices = provider.list(Filters::Any).await?;
35//!
36//!     // Check we have -a- device to connect to
37//!     if devices.is_empty() {
38//!         return Err(anyhow::anyhow!("No devices found"));
39//!     }
40//!
41//!     // Connect to the first device
42//!     let mut ledger = provider.connect(devices[0].clone()).await?;
43//!
44//!     // Request device information
45//!     let info = ledger.app_info(DEFAULT_TIMEOUT).await?;
46//!     println!("info: {info:?}");
47//!
48//!     Ok(())
49//! }
50//! ```
51
52#![cfg_attr(feature = "unstable_async_trait", feature(async_fn_in_trait))]
53#![feature(negative_impls)]
54
55use std::time::Duration;
56
57pub mod info;
58pub use info::LedgerInfo;
59
60mod error;
61pub use error::Error;
62
63pub mod transport;
64pub use transport::Transport;
65
66mod provider;
67pub use provider::{LedgerHandle, LedgerProvider};
68
69mod device;
70pub use device::Device;
71
72/// Default timeout helper for use with [Device] and [Exchange]
73pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(3);
74
75/// Device discovery filter
76#[derive(Copy, Clone, Debug, PartialEq, strum::Display)]
77#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
78#[non_exhaustive]
79pub enum Filters {
80    /// List all devices available using supported transport
81    Any,
82    /// List only HID devices
83    Hid,
84    /// List only TCP devices
85    Tcp,
86    /// List only BLE device
87    Ble,
88}
89
90impl Default for Filters {
91    fn default() -> Self {
92        Self::Any
93    }
94}
95
96/// [Exchange] trait provides a low-level interface for byte-wise exchange of APDU commands with a ledger devices
97#[cfg_attr(not(feature = "unstable_async_trait"), async_trait::async_trait)]
98pub trait Exchange {
99    async fn exchange(&mut self, command: &[u8], timeout: Duration) -> Result<Vec<u8>, Error>;
100}
101
102/// Blanket [Exchange] impl for mutable references
103#[cfg_attr(not(feature = "unstable_async_trait"), async_trait::async_trait)]
104impl<T: Exchange + Send> Exchange for &mut T {
105    async fn exchange(&mut self, command: &[u8], timeout: Duration) -> Result<Vec<u8>, Error> {
106        <T as Exchange>::exchange(self, command, timeout).await
107    }
108}