2020-09-20 15:17:02 +00:00
|
|
|
#![allow(unused)]
|
|
|
|
use coins_ledger::{
|
|
|
|
common::{APDUAnswer, APDUCommand, APDUData},
|
|
|
|
transports::{Ledger, LedgerAsync},
|
|
|
|
};
|
2020-10-08 15:56:36 +00:00
|
|
|
use futures_executor::block_on;
|
2020-09-20 15:17:02 +00:00
|
|
|
use futures_util::lock::Mutex;
|
|
|
|
|
|
|
|
use ethers_core::{
|
|
|
|
types::{
|
2021-10-19 08:52:36 +00:00
|
|
|
transaction::{eip2718::TypedTransaction, eip712::Eip712},
|
|
|
|
Address, NameOrAddress, Signature, Transaction, TransactionRequest, TxHash, H256, U256,
|
2020-09-20 15:17:02 +00:00
|
|
|
},
|
|
|
|
utils::keccak256,
|
|
|
|
};
|
|
|
|
use std::convert::TryFrom;
|
|
|
|
use thiserror::Error;
|
|
|
|
|
|
|
|
use super::types::*;
|
|
|
|
|
|
|
|
/// A Ledger Ethereum App.
|
|
|
|
///
|
|
|
|
/// This is a simple wrapper around the [Ledger transport](Ledger)
|
2020-09-24 21:33:09 +00:00
|
|
|
#[derive(Debug)]
|
2020-09-20 15:17:02 +00:00
|
|
|
pub struct LedgerEthereum {
|
|
|
|
transport: Mutex<Ledger>,
|
|
|
|
derivation: DerivationType,
|
2021-07-29 20:22:25 +00:00
|
|
|
pub(crate) chain_id: u64,
|
|
|
|
pub(crate) address: Address,
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|
|
|
|
|
2021-10-19 08:52:36 +00:00
|
|
|
const EIP712_MIN_VERSION: &str = ">=1.6.0";
|
|
|
|
|
2020-09-20 15:17:02 +00:00
|
|
|
impl LedgerEthereum {
|
|
|
|
/// Instantiate the application by acquiring a lock on the ledger device.
|
|
|
|
///
|
|
|
|
///
|
2020-09-24 21:33:09 +00:00
|
|
|
/// ```
|
|
|
|
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
|
2021-08-28 21:06:29 +00:00
|
|
|
/// use ethers_signers::{Ledger, HDPath};
|
2020-09-24 21:33:09 +00:00
|
|
|
///
|
2021-07-29 20:22:25 +00:00
|
|
|
/// let ledger = Ledger::new(HDPath::LedgerLive(0), 1).await?;
|
2020-09-24 21:33:09 +00:00
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2021-07-29 20:22:25 +00:00
|
|
|
pub async fn new(derivation: DerivationType, chain_id: u64) -> Result<Self, LedgerError> {
|
2020-09-24 21:33:09 +00:00
|
|
|
let transport = Ledger::init().await?;
|
|
|
|
let address = Self::get_address_with_path_transport(&transport, &derivation).await?;
|
|
|
|
|
2021-10-29 12:29:35 +00:00
|
|
|
Ok(Self { transport: Mutex::new(transport), derivation, chain_id, address })
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Consume self and drop the ledger mutex
|
|
|
|
pub fn close(self) {}
|
|
|
|
|
|
|
|
/// Get the account which corresponds to our derivation path
|
|
|
|
pub async fn get_address(&self) -> Result<Address, LedgerError> {
|
|
|
|
self.get_address_with_path(&self.derivation).await
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the account which corresponds to the provided derivation path
|
|
|
|
pub async fn get_address_with_path(
|
|
|
|
&self,
|
|
|
|
derivation: &DerivationType,
|
|
|
|
) -> Result<Address, LedgerError> {
|
2021-10-10 08:31:34 +00:00
|
|
|
let data = APDUData::new(&Self::path_to_bytes(derivation));
|
2020-09-20 15:17:02 +00:00
|
|
|
let transport = self.transport.lock().await;
|
2020-09-24 21:33:09 +00:00
|
|
|
Self::get_address_with_path_transport(&transport, derivation).await
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn get_address_with_path_transport(
|
|
|
|
transport: &Ledger,
|
|
|
|
derivation: &DerivationType,
|
|
|
|
) -> Result<Address, LedgerError> {
|
2021-10-10 08:31:34 +00:00
|
|
|
let data = APDUData::new(&Self::path_to_bytes(derivation));
|
2020-09-20 15:17:02 +00:00
|
|
|
|
|
|
|
let command = APDUCommand {
|
|
|
|
ins: INS::GET_PUBLIC_KEY as u8,
|
|
|
|
p1: P1::NON_CONFIRM as u8,
|
|
|
|
p2: P2::NO_CHAINCODE as u8,
|
|
|
|
data,
|
|
|
|
response_len: None,
|
|
|
|
};
|
|
|
|
|
2020-10-08 15:56:36 +00:00
|
|
|
let answer = block_on(transport.exchange(&command))?;
|
2020-09-20 15:17:02 +00:00
|
|
|
let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?;
|
|
|
|
|
|
|
|
let address = {
|
|
|
|
// extract the address from the response
|
|
|
|
let offset = 1 + result[0] as usize;
|
2020-12-31 17:19:14 +00:00
|
|
|
let address_str = &result[offset + 1..offset + 1 + result[offset] as usize];
|
|
|
|
let mut address = [0; 20];
|
|
|
|
address.copy_from_slice(&hex::decode(address_str)?);
|
|
|
|
Address::from(address)
|
2020-09-20 15:17:02 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
Ok(address)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the semver of the Ethereum ledger app
|
|
|
|
pub async fn version(&self) -> Result<String, LedgerError> {
|
|
|
|
let transport = self.transport.lock().await;
|
|
|
|
|
|
|
|
let command = APDUCommand {
|
|
|
|
ins: INS::GET_APP_CONFIGURATION as u8,
|
|
|
|
p1: P1::NON_CONFIRM as u8,
|
|
|
|
p2: P2::NO_CHAINCODE as u8,
|
|
|
|
data: APDUData::new(&[]),
|
|
|
|
response_len: None,
|
|
|
|
};
|
|
|
|
|
2020-10-08 15:56:36 +00:00
|
|
|
let answer = block_on(transport.exchange(&command))?;
|
2020-09-20 15:17:02 +00:00
|
|
|
let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?;
|
|
|
|
|
|
|
|
Ok(format!("{}.{}.{}", result[1], result[2], result[3]))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Signs an Ethereum transaction (requires confirmation on the ledger)
|
2021-08-09 00:31:11 +00:00
|
|
|
pub async fn sign_tx(&self, tx: &TypedTransaction) -> Result<Signature, LedgerError> {
|
2020-09-24 21:33:09 +00:00
|
|
|
let mut payload = Self::path_to_bytes(&self.derivation);
|
2021-07-29 20:22:25 +00:00
|
|
|
payload.extend_from_slice(tx.rlp(self.chain_id).as_ref());
|
2020-09-24 21:33:09 +00:00
|
|
|
self.sign_payload(INS::SIGN, payload).await
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Signs an ethereum personal message
|
|
|
|
pub async fn sign_message<S: AsRef<[u8]>>(&self, message: S) -> Result<Signature, LedgerError> {
|
|
|
|
let message = message.as_ref();
|
|
|
|
|
2020-09-24 21:33:09 +00:00
|
|
|
let mut payload = Self::path_to_bytes(&self.derivation);
|
2020-09-20 15:17:02 +00:00
|
|
|
payload.extend_from_slice(&(message.len() as u32).to_be_bytes());
|
|
|
|
payload.extend_from_slice(message);
|
|
|
|
|
|
|
|
self.sign_payload(INS::SIGN_PERSONAL_MESSAGE, payload).await
|
|
|
|
}
|
|
|
|
|
2021-10-19 08:52:36 +00:00
|
|
|
/// Signs an EIP712 encoded domain separator and message
|
|
|
|
pub async fn sign_typed_struct<T>(&self, payload: &T) -> Result<Signature, LedgerError>
|
|
|
|
where
|
|
|
|
T: Eip712,
|
|
|
|
{
|
|
|
|
// See comment for v1.6.0 requirement
|
|
|
|
// https://github.com/LedgerHQ/app-ethereum/issues/105#issuecomment-765316999
|
|
|
|
let req = semver::VersionReq::parse(EIP712_MIN_VERSION)?;
|
|
|
|
let version = semver::Version::parse(&self.version().await?)?;
|
|
|
|
|
|
|
|
// Enforce app version is greater than EIP712_MIN_VERSION
|
|
|
|
if !req.matches(&version) {
|
2021-10-29 12:29:35 +00:00
|
|
|
return Err(LedgerError::UnsupportedAppVersion(EIP712_MIN_VERSION.to_string()))
|
2021-10-19 08:52:36 +00:00
|
|
|
}
|
|
|
|
|
2021-10-29 12:29:35 +00:00
|
|
|
let domain_separator =
|
|
|
|
payload.domain_separator().map_err(|e| LedgerError::Eip712Error(e.to_string()))?;
|
|
|
|
let struct_hash =
|
|
|
|
payload.struct_hash().map_err(|e| LedgerError::Eip712Error(e.to_string()))?;
|
2021-10-19 08:52:36 +00:00
|
|
|
|
|
|
|
let mut payload = Self::path_to_bytes(&self.derivation);
|
|
|
|
payload.extend_from_slice(&domain_separator);
|
|
|
|
payload.extend_from_slice(&struct_hash);
|
|
|
|
|
|
|
|
self.sign_payload(INS::SIGN_ETH_EIP_712, payload).await
|
|
|
|
}
|
|
|
|
|
2021-10-29 12:29:35 +00:00
|
|
|
// Helper function for signing either transaction data, personal messages or EIP712 derived
|
|
|
|
// structs
|
derive-eip712: initial implementation of eip712 derive macro (#481)
* derive-eip712: initial implementation of eip712 derive macro
This commit provides an initial implementation for a derive macro
to encode typed data according to EIP-712, https://eips.ethereum.org/EIPS/eip-712
Additionally, this commit introduces a new signer trait method:
async fn sign_typed_data<T: Eip712 + Send + Sync>(
&self,
payload: &T,
) -> Result<Signature, Self::Error>;
And implements the new method for each of the signers (wallet, ledger,
aws).
Additionally, these changes include using `WalletError` for the Wallet
signer error type
At the moment, derive does not recurse the primary type to find nested
Eip712 structs. This is something that is noted in the source and
currently responds with an error regarding custom types.
A subsequent PR should be opened once this issue becomes needed. For the
moment, the current implementation should satisfy non-nested, basic struct types.
* rename to ethers-derive-eip712; move to ethers-core
* refactor of derive-eip712 macro; use ParamType and EthAbiToken
* macro updates; add byte array checker for paramtype; use literal constant for domain type hash
* replace std::convert::Infallible with WalletError as Wallet signer error type
* update workspace members and dev dependencies for examples folder
* add example for eip712 and test against contract
* remove extraneous backward slash in '\x19\x01' prefix; example tests pass
* update unreleased change log
* remove print statements
* use parse_macro_input macro; remove dead code; handle nest struct not implemented error
* move eip712 example to solidity-contract tests folder; update cargo workspace dependencies
* allow optional EIP712Domain parameter when encoding eip712 struct and signing typed data
* add documentation for eip712 feature
* Update ethers-signers/src/ledger/mod.rs
Co-authored-by: Sebastian Martinez <me@sebastinez.dev>
* add error enum for Eip712Error; use sign_payload for ledger signer
* add EIP712WithDomain type for providing a wrapper around custom setting of the domain
* make LedgerWallet sign_payload public
* use optional feature gated dependencies for eip712; add default method for encode_eip712
* add default domain_separator method, pre-compute separator hash
* move derive-eip712 deps to dev deps
* remove invalid sign payload parameter, add await on async method
* remove deprecated comment
* debugging 'bad key handle' error for ledger signer
try using 'sign_message'
* await sign digest for aws signer
* remove extra space, fix fmt warning
* fix test, fmt errors
* use gt 0.6.0 pragma compiler version
* enable ABIEncoderV2 for solidity test contract
* chore: make test constructor public
Co-authored-by: Sebastian Martinez <me@sebastinez.dev>
Co-authored-by: Georgios Konstantopoulos <me@gakonst.com>
2021-10-08 15:22:51 +00:00
|
|
|
pub async fn sign_payload(
|
2020-09-20 15:17:02 +00:00
|
|
|
&self,
|
|
|
|
command: INS,
|
|
|
|
mut payload: Vec<u8>,
|
|
|
|
) -> Result<Signature, LedgerError> {
|
|
|
|
let transport = self.transport.lock().await;
|
|
|
|
let mut command = APDUCommand {
|
|
|
|
ins: command as u8,
|
|
|
|
p1: P1_FIRST,
|
|
|
|
p2: P2::NO_CHAINCODE as u8,
|
|
|
|
data: APDUData::new(&[]),
|
|
|
|
response_len: None,
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut result = Vec::new();
|
|
|
|
|
|
|
|
// Iterate in 255 byte chunks
|
2020-10-02 08:41:16 +00:00
|
|
|
while !payload.is_empty() {
|
2020-09-20 15:17:02 +00:00
|
|
|
let chunk_size = std::cmp::min(payload.len(), 255);
|
|
|
|
let data = payload.drain(0..chunk_size).collect::<Vec<_>>();
|
|
|
|
command.data = APDUData::new(&data);
|
|
|
|
|
2020-10-08 15:56:36 +00:00
|
|
|
let answer = block_on(transport.exchange(&command))?;
|
2021-10-29 12:29:35 +00:00
|
|
|
result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?.to_vec();
|
2020-09-20 15:17:02 +00:00
|
|
|
|
|
|
|
// We need more data
|
|
|
|
command.p1 = P1::MORE as u8;
|
|
|
|
}
|
|
|
|
|
|
|
|
let v = result[0] as u64;
|
2021-08-15 11:30:44 +00:00
|
|
|
let r = U256::from_big_endian(&result[1..33]);
|
|
|
|
let s = U256::from_big_endian(&result[33..]);
|
2021-07-05 11:03:38 +00:00
|
|
|
Ok(Signature { r, s, v })
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// helper which converts a derivation path to bytes
|
2020-09-24 21:33:09 +00:00
|
|
|
fn path_to_bytes(derivation: &DerivationType) -> Vec<u8> {
|
2020-09-20 15:17:02 +00:00
|
|
|
let derivation = derivation.to_string();
|
|
|
|
let elements = derivation.split('/').skip(1).collect::<Vec<_>>();
|
|
|
|
let depth = elements.len();
|
|
|
|
|
|
|
|
let mut bytes = vec![depth as u8];
|
|
|
|
for derivation_index in elements {
|
2020-10-02 08:41:16 +00:00
|
|
|
let hardened = derivation_index.contains('\'');
|
2020-09-20 15:17:02 +00:00
|
|
|
let mut index = derivation_index.replace("'", "").parse::<u32>().unwrap();
|
|
|
|
if hardened {
|
2020-10-02 08:41:16 +00:00
|
|
|
index |= 0x80000000;
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
bytes.extend(&index.to_be_bytes());
|
|
|
|
}
|
|
|
|
|
|
|
|
bytes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-08 15:56:36 +00:00
|
|
|
#[cfg(all(test, feature = "ledger"))]
|
2020-09-20 15:17:02 +00:00
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2020-09-24 21:33:09 +00:00
|
|
|
use crate::Signer;
|
2021-10-19 08:52:36 +00:00
|
|
|
use ethers_contract::EthAbiType;
|
|
|
|
use ethers_core::types::{
|
|
|
|
transaction::eip712::Eip712, Address, TransactionRequest, I256, U256,
|
|
|
|
};
|
|
|
|
use ethers_derive_eip712::*;
|
2020-09-20 15:17:02 +00:00
|
|
|
use std::str::FromStr;
|
|
|
|
|
2021-10-19 08:52:36 +00:00
|
|
|
#[derive(Debug, Clone, Eip712, EthAbiType)]
|
|
|
|
#[eip712(
|
|
|
|
name = "Eip712Test",
|
|
|
|
version = "1",
|
|
|
|
chain_id = 1,
|
|
|
|
verifying_contract = "0x0000000000000000000000000000000000000001",
|
|
|
|
salt = "eip712-test-75F0CCte"
|
|
|
|
)]
|
|
|
|
struct FooBar {
|
|
|
|
foo: I256,
|
|
|
|
bar: U256,
|
|
|
|
fizz: Vec<u8>,
|
|
|
|
buzz: [u8; 32],
|
|
|
|
far: String,
|
|
|
|
out: Address,
|
|
|
|
}
|
|
|
|
|
2020-09-20 15:17:02 +00:00
|
|
|
#[tokio::test]
|
2020-09-24 21:33:09 +00:00
|
|
|
#[ignore]
|
2020-09-20 15:17:02 +00:00
|
|
|
// Replace this with your ETH addresses.
|
|
|
|
async fn test_get_address() {
|
|
|
|
// Instantiate it with the default ledger derivation path
|
2021-10-29 12:29:35 +00:00
|
|
|
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1).await.unwrap();
|
2020-09-20 15:17:02 +00:00
|
|
|
assert_eq!(
|
|
|
|
ledger.get_address().await.unwrap(),
|
|
|
|
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".parse().unwrap()
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2021-10-29 12:29:35 +00:00
|
|
|
ledger.get_address_with_path(&DerivationType::Legacy(0)).await.unwrap(),
|
2020-09-20 15:17:02 +00:00
|
|
|
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee".parse().unwrap()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
2020-09-24 21:33:09 +00:00
|
|
|
#[ignore]
|
2020-09-20 15:17:02 +00:00
|
|
|
async fn test_sign_tx() {
|
2021-10-29 12:29:35 +00:00
|
|
|
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1).await.unwrap();
|
2020-09-20 15:17:02 +00:00
|
|
|
|
|
|
|
// approve uni v2 router 0xff
|
2020-12-31 17:19:14 +00:00
|
|
|
let data = hex::decode("095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap();
|
2020-09-20 15:17:02 +00:00
|
|
|
|
|
|
|
let tx_req = TransactionRequest::new()
|
2021-10-29 12:29:35 +00:00
|
|
|
.to("2ed7afa17473e17ac59908f088b4371d28585476".parse::<Address>().unwrap())
|
2020-09-20 15:17:02 +00:00
|
|
|
.gas(1000000)
|
|
|
|
.gas_price(400e9 as u64)
|
|
|
|
.nonce(5)
|
|
|
|
.data(data)
|
2021-08-09 00:31:11 +00:00
|
|
|
.value(ethers_core::utils::parse_ether(100).unwrap())
|
|
|
|
.into();
|
2020-09-24 21:33:09 +00:00
|
|
|
let tx = ledger.sign_transaction(&tx_req).await.unwrap();
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
2020-09-24 21:33:09 +00:00
|
|
|
#[ignore]
|
2020-09-20 15:17:02 +00:00
|
|
|
async fn test_version() {
|
2021-10-29 12:29:35 +00:00
|
|
|
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1).await.unwrap();
|
2020-09-20 15:17:02 +00:00
|
|
|
|
|
|
|
let version = ledger.version().await.unwrap();
|
|
|
|
assert_eq!(version, "1.3.7");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
2020-09-24 21:33:09 +00:00
|
|
|
#[ignore]
|
2020-09-20 15:17:02 +00:00
|
|
|
async fn test_sign_message() {
|
2021-10-29 12:29:35 +00:00
|
|
|
let ledger = LedgerEthereum::new(DerivationType::Legacy(0), 1).await.unwrap();
|
2020-09-20 15:17:02 +00:00
|
|
|
let message = "hello world";
|
|
|
|
let sig = ledger.sign_message(message).await.unwrap();
|
|
|
|
let addr = ledger.get_address().await.unwrap();
|
|
|
|
sig.verify(message, addr).unwrap();
|
|
|
|
}
|
2021-10-19 08:52:36 +00:00
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
#[ignore]
|
|
|
|
async fn test_sign_eip712_struct() {
|
2021-10-29 12:29:35 +00:00
|
|
|
let ledger = LedgerEthereum::new(DerivationType::LedgerLive(0), 1u64).await.unwrap();
|
2021-10-19 08:52:36 +00:00
|
|
|
|
|
|
|
let foo_bar = FooBar {
|
|
|
|
foo: I256::from(10),
|
|
|
|
bar: U256::from(20),
|
|
|
|
fizz: b"fizz".to_vec(),
|
|
|
|
buzz: keccak256("buzz"),
|
|
|
|
far: String::from("space"),
|
|
|
|
out: Address::from([0; 20]),
|
|
|
|
};
|
|
|
|
|
2021-10-29 12:29:35 +00:00
|
|
|
let sig = ledger.sign_typed_struct(&foo_bar).await.expect("failed to sign typed data");
|
2021-10-19 08:52:36 +00:00
|
|
|
let foo_bar_hash = foo_bar.encode_eip712().unwrap();
|
|
|
|
sig.verify(foo_bar_hash, ledger.address).unwrap();
|
|
|
|
}
|
2020-09-20 15:17:02 +00:00
|
|
|
}
|