Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

Commit

Permalink
address comments
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasad1 committed Feb 13, 2018
1 parent a3704c8 commit fd41215
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 60 deletions.
58 changes: 29 additions & 29 deletions hw/src/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ use parking_lot::{Mutex, RwLock};

use super::{WalletInfo, KeyPath};

// Expose these to the callback configuration
/// Ledger vendor ID
pub const LEDGER_VID: u16 = 0x2c97;
pub const LEDGER_PIDS: [u16; 2] = [0x0000, 0x0001]; // Nano S and Blue
/// Legder product IDs: [Nano S and Blue]
pub const LEDGER_PIDS: [u16; 2] = [0x0000, 0x0001];

const ETH_DERIVATION_PATH_BE: [u8; 17] = [4, 0x80, 0, 0, 44, 0x80, 0, 0, 60, 0x80, 0, 0, 0, 0, 0, 0, 0]; // 44'/60'/0'/0
const ETC_DERIVATION_PATH_BE: [u8; 21] = [5, 0x80, 0, 0, 44, 0x80, 0, 0, 60, 0x80, 0x02, 0x73, 0xd0, 0x80, 0, 0, 0, 0, 0, 0, 0]; // 44'/60'/160720'/0'/0

Expand Down Expand Up @@ -249,10 +251,7 @@ impl Manager {
fn open_path<R, F>(&self, f: F) -> Result<R, Error>
where F: Fn() -> Result<R, &'static str>
{
match f() {
Ok(handle) => Ok(handle),
Err(e) => Err(From::from(e)),
}
f().map_err(Into::into)
}

fn send_apdu(handle: &hidapi::HidDevice, command: u8, p1: u8, p2: u8, data: &[u8]) -> Result<Vec<u8>, Error> {
Expand Down Expand Up @@ -342,18 +341,8 @@ impl Manager {
message.truncate(new_len);
Ok(message)
}
}

pub struct EventHandler {
ledger: Weak<Manager>,
}

impl EventHandler {
pub fn new(ledger: Weak<Manager>) -> Self {
Self { ledger: ledger }
}

fn is_valid_product(&self, device: &libusb::Device) -> Result<(), Error> {
fn is_valid_ledger(device: &libusb::Device) -> Result<(), Error> {
let desc = device.device_descriptor()?;
let vendor_id = desc.vendor_id();
let product_id = desc.product_id();
Expand All @@ -364,28 +353,39 @@ impl EventHandler {
Err(Error::InvalidDevice)
}
}

}

/// Ledger event handler
/// A seperate thread is handling incoming events
pub struct EventHandler {
ledger: Weak<Manager>,
}

impl EventHandler {
/// Ledger event handler constructor
pub fn new(ledger: Weak<Manager>) -> Self {
Self { ledger: ledger }
}
}

impl libusb::Hotplug for EventHandler {
fn device_arrived(&mut self, device: libusb::Device) {
println!("ledger arrived");
Duration::from_millis(1000);

if let (Some(t), Ok(_)) = (self.ledger.upgrade(), self.is_valid_product(&device)) {
// Wait for the device to bootup
if let (Some(ledger), Ok(_)) = (self.ledger.upgrade(), Manager::is_valid_ledger(&device)) {
debug!("Ledger arrived");
// Wait for the device to boot up
thread::sleep(Duration::from_millis(1000));
if let Err(e) = t.update_devices() {
debug!("Ledger Connect Error: {:?}", e);
if let Err(e) = ledger.update_devices() {
debug!("Ledger connect error: {:?}", e);
}
}
}

fn device_left(&mut self, _device: libusb::Device) {
println!("ledger left");
if let Some(l) = self.ledger.upgrade() {
if let Err(e) = l.update_devices() {
debug!("Ledger Disconnect Error: {:?}", e);
fn device_left(&mut self, device: libusb::Device) {
if let (Some(ledger), Ok(_)) = (self.ledger.upgrade(), Manager::is_valid_ledger(&device)) {
debug!("Ledger left");
if let Err(e) = ledger.update_devices() {
debug!("Ledger disconnect error: {:?}", e);
}
}
}
Expand Down
14 changes: 6 additions & 8 deletions hw/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ use ethereum_types::U256;

const USB_DEVICE_CLASS_DEVICE: u8 = 0;


/// Hardware wallet error.
#[derive(Debug)]
pub enum Error {
Expand Down Expand Up @@ -139,10 +138,11 @@ pub struct HardwareWalletManager {


impl HardwareWalletManager {
/// Hardware wallet constructor
pub fn new() -> Result<HardwareWalletManager, Error> {
let usb_context_trezor = Arc::new(libusb::Context::new()?);
let usb_context_ledger = Arc::new(libusb::Context::new()?);
let mut active_threads: Vec<Option<thread::JoinHandle<()>>> = Vec::with_capacity(10);
let mut active_threads: Vec<Option<thread::JoinHandle<()>>> = Vec::new();
let hidapi = Arc::new(Mutex::new(hidapi::HidApi::new().map_err(|e| Error::Hid(e.to_string().clone()))?));
let ledger = Arc::new(ledger::Manager::new(hidapi.clone()));
let trezor = Arc::new(trezor::Manager::new(hidapi.clone()));
Expand All @@ -169,16 +169,15 @@ impl HardwareWalletManager {
let t = trezor.clone();

// Ledger event thread
// FIXME: check if we can move it to ledger.rs (lifetime issue)
active_threads.push(thread::Builder::new()
.name("hw_wallet_ledger".to_string())
.spawn(move || {
if let Err(e) = l.update_devices() {
debug!("Error updating ledger devices: {}", e);
debug!("Ledger could not connect at startup, error: {}", e);
}
loop {
usb_context_ledger.handle_events(Some(Duration::from_millis(500)))
.unwrap_or_else(|e| debug!("Error processing USB events: {}", e));
.unwrap_or_else(|e| debug!("Ledger event handler error: {}", e));
if thread_exiting_ledger.load(atomic::Ordering::Acquire) {
break;
}
Expand All @@ -187,16 +186,15 @@ impl HardwareWalletManager {
.ok());

// Trezor event thread
// FIXME: check if we can move it to trezor.rs (lifetime issue)
active_threads.push(thread::Builder::new()
.name("hw_wallet_trezor".to_string())
.spawn(move || {
if let Err(e) = t.update_devices() {
debug!("Error updating ledger devices: {}", e);
debug!("Trezor could not connect at startup, error: {}", e);
}
loop {
usb_context_trezor.handle_events(Some(Duration::from_millis(500)))
.unwrap_or_else(|e| debug!("Error processing USB events: {}", e));
.unwrap_or_else(|e| debug!("Trezor event handler error: {}", e));
if thread_exiting_trezor.load(atomic::Ordering::Acquire) {
break;
}
Expand Down
45 changes: 22 additions & 23 deletions hw/src/trezor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,14 @@ use protobuf::{Message, ProtobufEnum};

use trezor_sys::messages::{EthereumAddress, PinMatrixAck, MessageType, EthereumTxRequest, EthereumSignTx, EthereumGetAddress, EthereumTxAck, ButtonAck};

// Expose these to the callback configuration
/// Trezor v1 vendor ID
pub const TREZOR_VID: u16 = 0x534c;
pub const TREZOR_PIDS: [u16; 1] = [0x0001]; // Trezor v1, keeping this as an array to leave room for Trezor v2 which is in progress
/// Trezor product IDs
pub const TREZOR_PIDS: [u16; 1] = [0x0001];

const ETH_DERIVATION_PATH: [u32; 5] = [0x8000002C, 0x8000003C, 0x80000000, 0, 0]; // m/44'/60'/0'/0/0
const ETC_DERIVATION_PATH: [u32; 5] = [0x8000002C, 0x8000003D, 0x80000000, 0, 0]; // m/44'/61'/0'/0/0


/// Hardware wallet error.
#[derive(Debug)]
pub enum Error {
Expand All @@ -59,7 +60,7 @@ pub enum Error {
/// The Message Type given in the trezor RPC call is not something we recognize
BadMessageType,
/// Trying to read from a closed device at the given path
ClosedDevice(String),
LockedDevice(String),
}

impl fmt::Display for Error {
Expand All @@ -70,7 +71,7 @@ impl fmt::Display for Error {
Error::KeyNotFound => write!(f, "Key not found"),
Error::UserCancel => write!(f, "Operation has been cancelled"),
Error::BadMessageType => write!(f, "Bad Message Type in RPC call"),
Error::ClosedDevice(ref s) => write!(f, "Device is closed, needs PIN to perform operations: {}", s),
Error::LockedDevice(ref s) => write!(f, "Device is locked, needs PIN to perform operations: {}", s),
}
}
}
Expand All @@ -87,7 +88,7 @@ impl From<protobuf::ProtobufError> for Error {
}
}

/// Ledger device manager.
/// Ledger device manager
pub struct Manager {
usb: Arc<Mutex<hidapi::HidApi>>,
devices: RwLock<Vec<Device>>,
Expand Down Expand Up @@ -143,7 +144,7 @@ impl Manager {
}
match self.read_device_info(&usb, &usb_device) {
Ok(device) => new_devices.push(device),
Err(Error::ClosedDevice(path)) => locked_devices.push(path.to_string()),
Err(Error::LockedDevice(path)) => locked_devices.push(path.to_string()),
Err(e) => {
warn!("Error reading device: {:?}", e);
error = Some(e);
Expand Down Expand Up @@ -177,7 +178,7 @@ impl Manager {
},
})
}
Ok(None) => Err(Error::ClosedDevice(dev_info.path.clone())),
Ok(None) => Err(Error::LockedDevice(dev_info.path.clone())),
Err(e) => Err(e),
}
}
Expand All @@ -204,10 +205,7 @@ impl Manager {
fn open_path<R, F>(&self, f: F) -> Result<R, Error>
where F: Fn() -> Result<R, &'static str>
{
match f() {
Ok(handle) => Ok(handle),
Err(e) => Err(From::from(e)),
}
f().map_err(Into::into)
}

pub fn pin_matrix_ack(&self, device_path: &str, pin: &str) -> Result<bool, Error> {
Expand Down Expand Up @@ -404,36 +402,37 @@ impl Manager {
}
}

/// Trezor event handler
/// A separate thread is handeling incoming events
pub struct EventHandler {
trezor: Weak<Manager>,
}

impl EventHandler {
// Trezor event handler constructor
pub fn new(trezor: Weak<Manager>) -> Self {
Self { trezor: trezor }
}
}

impl libusb::Hotplug for EventHandler {
fn device_arrived(&mut self, _device: libusb::Device) {
println!("trezor arrived");
if let Some(t) = self.trezor.upgrade() {
// Wait for the device to boot-up
debug!("Trezor V1 arrived");
if let Some(trezor) = self.trezor.upgrade() {
// Wait for the device to boot up
thread::sleep(Duration::from_millis(1000));
if let Err(e) = t.update_devices() {
debug!("TREZOR Connect Error: {:?}", e);
if let Err(e) = trezor.update_devices() {
debug!("Trezor V1 connect error: {:?}", e);
}
println!("unlocked devices: {:?}", t.list_devices());
println!("locked devices: {:?}", t.list_locked_devices());

}
}

fn device_left(&mut self, _device: libusb::Device) {
println!("trezor left");
if let Some(t) = self.trezor.upgrade() {
if let Err(e) = t.update_devices() {
debug!("TREZOR Disconnect fail: {:?}", e);
debug!("Trezor V1 left");
if let Some(trezor) = self.trezor.upgrade() {
if let Err(e) = trezor.update_devices() {
debug!("Trezor V1 disconnect error: {:?}", e);
}
}
}
Expand Down

0 comments on commit fd41215

Please sign in to comment.