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

Commit

Permalink
Clean up things that I missed
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasad1 committed Jun 13, 2018
1 parent 23c249b commit 7b72f2b
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 73 deletions.
45 changes: 23 additions & 22 deletions hw/src/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,20 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.

//! Ledger hardware wallet module. Supports Ledger Blue and Nano S.
/// See https://github.com/LedgerHQ/blue-app-eth/blob/master/doc/ethapp.asc for protocol details.
/// See <https://github.com/LedgerHQ/blue-app-eth/blob/master/doc/ethapp.asc> for protocol details.

use std::cmp::min;
use std::str::FromStr;
use std::sync::{atomic, atomic::AtomicBool, Arc, Weak};
use std::time::{Duration, Instant};
use std::{fmt, thread};

use ethereum_types::{H256, Address};
use ethkey::Signature;
use hidapi;
use libusb;
use parking_lot::{Mutex, RwLock};
use semver::Version as FirmwareVersion;
use std::cmp::min;
use std::str::FromStr;
use std::sync::{atomic, atomic::AtomicBool, Arc, Weak};
use std::time::{Duration, Instant};
use std::{fmt, thread};
use super::{WalletInfo, KeyPath, Device, DeviceDirection, Wallet, USB_DEVICE_CLASS_DEVICE, POLLING_DURATION};

const APDU_TAG: u8 = 0x05;
Expand Down Expand Up @@ -97,13 +98,13 @@ impl fmt::Display for Error {
}

impl From<hidapi::HidError> for Error {
fn from(err: hidapi::HidError) -> Error {
fn from(err: hidapi::HidError) -> Self {
Error::Usb(err)
}
}

impl From<libusb::Error> for Error {
fn from(err: libusb::Error) -> Error {
fn from(err: libusb::Error) -> Self {
Error::LibUsb(err)
}
}
Expand All @@ -117,8 +118,8 @@ pub (crate) struct Manager {

impl Manager {
/// Create a new instance.
pub fn new(hidapi: Arc<Mutex<hidapi::HidApi>>, exiting: Arc<AtomicBool>) -> Result<Arc<Manager>, libusb::Error> {
let manager = Arc::new(Manager {
pub fn new(hidapi: Arc<Mutex<hidapi::HidApi>>, exiting: Arc<AtomicBool>) -> Result<Arc<Self>, libusb::Error> {
let manager = Arc::new(Self {
usb: hidapi,
devices: RwLock::new(Vec::new()),
key_path: RwLock::new(KeyPath::Ethereum),
Expand Down Expand Up @@ -180,14 +181,14 @@ impl Manager {
let size = min(64 - header, data_len - offset);
{
let chunk = &mut hid_chunk[HID_PREFIX_ZERO..];
&mut chunk[0..5].copy_from_slice(&[0x01, 0x01, APDU_TAG, (sequence_number >> 8) as u8, (sequence_number & 0xff) as u8 ]);
chunk[0..5].copy_from_slice(&[0x01, 0x01, APDU_TAG, (sequence_number >> 8) as u8, (sequence_number & 0xff) as u8 ]);

if sequence_number == 0 {
let data_len = data.len() + 5;
&mut chunk[5..12].copy_from_slice(&[(data_len >> 8) as u8, (data_len & 0xff) as u8, APDU_CLA, command, p1, p2, data.len() as u8]);
chunk[5..12].copy_from_slice(&[(data_len >> 8) as u8, (data_len & 0xff) as u8, APDU_CLA, command, p1, p2, data.len() as u8]);
}

&mut chunk[header..header + size].copy_from_slice(&data[offset..offset + size]);
chunk[header..header + size].copy_from_slice(&data[offset..offset + size]);
}
trace!(target: "hw", "Ledger write {:?}", &hid_chunk[..]);
let n = handle.write(&hid_chunk[..])?;
Expand Down Expand Up @@ -262,7 +263,7 @@ impl Manager {
0x6a82 => Err(Error::Protocol("File not found")),
0x6a85 => Err(Error::UserCancel),
0x6b00 => Err(Error::Protocol("Incorrect parameters")),
0x6d00 => Err(Error::Protocol("Not implemented. Make sure Ethereum app is running.")),
0x6d00 => Err(Error::Protocol("Not implemented. Make sure the Ledger Ethereum Wallet app is running.")),
0x6faa => Err(Error::Protocol("Your Ledger need to be unplugged")),
0x6f00...0x6fff => Err(Error::Protocol("Internal error")),
0x9000 => Ok(()),
Expand Down Expand Up @@ -324,7 +325,7 @@ impl Manager {
let derivation_path = self.get_derivation_path();

// Copy the address of the key (only done once)
&mut chunk[0..derivation_path.len()].copy_from_slice(derivation_path);
chunk[0..derivation_path.len()].copy_from_slice(derivation_path);

let key_length = derivation_path.len();
let max_payload_size = MAX_CHUNK_SIZE - key_length;
Expand Down Expand Up @@ -363,7 +364,7 @@ impl Manager {
}

// Try to connect to the device using polling in at most the time specified by the `timeout`
fn try_connect_polling(ledger: Arc<Manager>, timeout: &Duration, device_direction: DeviceDirection) -> bool {
fn try_connect_polling(ledger: &Arc<Manager>, timeout: &Duration, device_direction: DeviceDirection) -> bool {
let start_time = Instant::now();
while start_time.elapsed() <= *timeout {
if let Ok(num_devices) = ledger.update_devices(device_direction) {
Expand Down Expand Up @@ -436,9 +437,9 @@ impl <'a>Wallet<'a> for Manager {
Ok(Device {
path: dev_info.path.clone(),
info: WalletInfo {
name: name,
manufacturer: manufacturer,
serial: serial,
name,
manufacturer,
serial,
address: addr,
},
})
Expand Down Expand Up @@ -502,15 +503,15 @@ struct EventHandler {
impl EventHandler {
/// Ledger event handler constructor
fn new(ledger: Weak<Manager>) -> Self {
Self { ledger: ledger }
Self { ledger }
}
}

impl libusb::Hotplug for EventHandler {
fn device_arrived(&mut self, device: libusb::Device) {
debug!(target: "hw", "Ledger arrived");
if let (Some(ledger), Ok(_)) = (self.ledger.upgrade(), Manager::is_valid_ledger(&device)) {
if try_connect_polling(ledger, &POLLING_DURATION, DeviceDirection::Arrived) != true {
if try_connect_polling(&ledger, &POLLING_DURATION, DeviceDirection::Arrived) != true {
debug!(target: "hw", "No Ledger device was connected");
}
}
Expand All @@ -519,7 +520,7 @@ impl libusb::Hotplug for EventHandler {
fn device_left(&mut self, device: libusb::Device) {
debug!(target: "hw", "Ledger left");
if let (Some(ledger), Ok(_)) = (self.ledger.upgrade(), Manager::is_valid_ledger(&device)) {
if try_connect_polling(ledger, &POLLING_DURATION, DeviceDirection::Left) != true {
if try_connect_polling(&ledger, &POLLING_DURATION, DeviceDirection::Left) != true {
debug!(target: "hw", "No Ledger device was disconnected");
}
}
Expand Down
38 changes: 21 additions & 17 deletions hw/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

//! Hardware wallet management.

#[warn(missing_docs)]
#[warn(warnings)]
#![warn(missing_docs)]
#![warn(warnings)]

extern crate ethereum_types;
extern crate ethkey;
Expand All @@ -34,22 +34,24 @@ extern crate trezor_sys;
mod ledger;
mod trezor;

use ethkey::{Address, Signature};

use parking_lot::Mutex;
use std::{fmt, time::Duration};
use std::sync::{Arc, atomic, atomic::AtomicBool};
use std::{fmt, time::Duration};

use ethereum_types::U256;
use ethkey::{Address, Signature};
use parking_lot::Mutex;

const USB_DEVICE_CLASS_DEVICE: u8 = 0;
const POLLING_DURATION: Duration = Duration::from_millis(500);

/// `HardwareWallet` device
#[derive(Debug)]
pub struct Device {
path: String,
info: WalletInfo,
}

/// `Wallet` trait
pub trait Wallet<'a> {
/// Error
type Error;
Expand Down Expand Up @@ -109,7 +111,7 @@ pub enum Error {
}

/// This is the transaction info we need to supply to Trezor message. It's more
/// or less a duplicate of ethcore::transaction::Transaction, but we can't
/// or less a duplicate of `ethcore::transaction::Transaction`, but we can't
/// import ethcore here as that would be a circular dependency.
pub struct TransactionInfo {
/// Nonce
Expand Down Expand Up @@ -163,7 +165,7 @@ impl fmt::Display for Error {
}

impl From<ledger::Error> for Error {
fn from(err: ledger::Error) -> Error {
fn from(err: ledger::Error) -> Self {
match err {
ledger::Error::KeyNotFound => Error::KeyNotFound,
_ => Error::LedgerDevice(err),
Expand All @@ -172,7 +174,7 @@ impl From<ledger::Error> for Error {
}

impl From<trezor::Error> for Error {
fn from(err: trezor::Error) -> Error {
fn from(err: trezor::Error) -> Self {
match err {
trezor::Error::KeyNotFound => Error::KeyNotFound,
_ => Error::TrezorDevice(err),
Expand All @@ -181,16 +183,18 @@ impl From<trezor::Error> for Error {
}

impl From<libusb::Error> for Error {
fn from(err: libusb::Error) -> Error {
fn from(err: libusb::Error) -> Self {
Error::Usb(err)
}
}

/// Specifies the direction of the `HardwareWallet` i.e, whether it arrived or left
#[derive(Debug, Copy, Clone)]
pub enum DeviceDirection {
Arrived,
Left,
/// Device arrived
Arrived,
/// Device left
Left,
}

impl fmt::Display for DeviceDirection {
Expand All @@ -211,16 +215,16 @@ pub struct HardwareWalletManager {

impl HardwareWalletManager {
/// Hardware wallet constructor
pub fn new() -> Result<HardwareWalletManager, Error> {
pub fn new() -> Result<Self, Error> {
let exiting = Arc::new(AtomicBool::new(false));
let hidapi = Arc::new(Mutex::new(hidapi::HidApi::new().map_err(|e| Error::Hid(e.to_string().clone()))?));
let ledger = ledger::Manager::new(hidapi.clone(), exiting.clone())?;
let trezor = trezor::Manager::new(hidapi.clone(), exiting.clone())?;

Ok(HardwareWalletManager {
exiting: exiting,
ledger: ledger,
trezor: trezor,
Ok(Self {
exiting,
ledger,
trezor,
})
}

Expand Down
Loading

0 comments on commit 7b72f2b

Please sign in to comment.