This repository has been archived by the owner on Oct 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 792
Workaround for https://github.com/LedgerHQ/app-ethereum/issues/409 #2192
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,6 +29,16 @@ pub struct LedgerEthereum { | |
pub(crate) address: Address, | ||
} | ||
|
||
impl std::fmt::Display for LedgerEthereum { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
write!( | ||
f, | ||
"LedgerApp. Key at index {} with address {:?} on chain_id {}", | ||
self.derivation, self.address, self.chain_id | ||
) | ||
} | ||
} | ||
|
||
const EIP712_MIN_VERSION: &str = ">=1.6.0"; | ||
|
||
impl LedgerEthereum { | ||
|
@@ -68,6 +78,7 @@ impl LedgerEthereum { | |
Self::get_address_with_path_transport(&transport, derivation).await | ||
} | ||
|
||
#[tracing::instrument(skip(transport))] | ||
async fn get_address_with_path_transport( | ||
transport: &Ledger, | ||
derivation: &DerivationType, | ||
|
@@ -82,6 +93,7 @@ impl LedgerEthereum { | |
response_len: None, | ||
}; | ||
|
||
tracing::debug!("Dispatching get_address request to ethereum app"); | ||
let answer = block_on(transport.exchange(&command))?; | ||
let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?; | ||
|
||
|
@@ -93,7 +105,7 @@ impl LedgerEthereum { | |
address.copy_from_slice(&hex::decode(address_str)?); | ||
Address::from(address) | ||
}; | ||
|
||
tracing::debug!(?address, "Received address from device"); | ||
Ok(address) | ||
} | ||
|
||
|
@@ -109,10 +121,15 @@ impl LedgerEthereum { | |
response_len: None, | ||
}; | ||
|
||
tracing::debug!("Dispatching get_version"); | ||
let answer = block_on(transport.exchange(&command))?; | ||
let result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?; | ||
|
||
Ok(format!("{}.{}.{}", result[1], result[2], result[3])) | ||
if result.len() < 4 { | ||
return Err(LedgerError::ShortResponse { got: result.len(), at_least: 4 }) | ||
} | ||
let version = format!("{}.{}.{}", result[1], result[2], result[3]); | ||
tracing::debug!(version, "Retrieved version from device"); | ||
Ok(version) | ||
} | ||
|
||
/// Signs an Ethereum transaction (requires confirmation on the ledger) | ||
|
@@ -125,7 +142,7 @@ impl LedgerEthereum { | |
let mut payload = Self::path_to_bytes(&self.derivation); | ||
payload.extend_from_slice(tx_with_chain.rlp().as_ref()); | ||
|
||
let mut signature = self.sign_payload(INS::SIGN, payload).await?; | ||
let mut signature = self.sign_payload(INS::SIGN, &payload).await?; | ||
|
||
// modify `v` value of signature to match EIP-155 for chains with large chain ID | ||
// The logic is derived from Ledger's library | ||
|
@@ -158,7 +175,7 @@ impl LedgerEthereum { | |
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 | ||
self.sign_payload(INS::SIGN_PERSONAL_MESSAGE, &payload).await | ||
} | ||
|
||
/// Signs an EIP712 encoded domain separator and message | ||
|
@@ -185,16 +202,20 @@ impl LedgerEthereum { | |
payload.extend_from_slice(&domain_separator); | ||
payload.extend_from_slice(&struct_hash); | ||
|
||
self.sign_payload(INS::SIGN_ETH_EIP_712, payload).await | ||
self.sign_payload(INS::SIGN_ETH_EIP_712, &payload).await | ||
} | ||
|
||
#[tracing::instrument(err, skip_all, fields(command = %command, payload = hex::encode(payload)))] | ||
// Helper function for signing either transaction data, personal messages or EIP712 derived | ||
// structs | ||
pub async fn sign_payload( | ||
&self, | ||
command: INS, | ||
mut payload: Vec<u8>, | ||
payload: &Vec<u8>, | ||
) -> Result<Signature, LedgerError> { | ||
if payload.is_empty() { | ||
return Err(LedgerError::EmptyPayload) | ||
} | ||
let transport = self.transport.lock().await; | ||
let mut command = APDUCommand { | ||
ins: command as u8, | ||
|
@@ -204,25 +225,47 @@ impl LedgerEthereum { | |
response_len: None, | ||
}; | ||
|
||
let mut result = Vec::new(); | ||
let mut answer = None; | ||
// workaround for https://github.com/LedgerHQ/app-ethereum/issues/409 | ||
// TODO: remove in future version | ||
let chunk_size = | ||
(0..=255).rev().find(|i| payload.len() % i != 3).expect("true for any length"); | ||
|
||
// Iterate in 255 byte chunks | ||
while !payload.is_empty() { | ||
let chunk_size = std::cmp::min(payload.len(), 255); | ||
let data = payload.drain(0..chunk_size).collect::<Vec<_>>(); | ||
command.data = APDUData::new(&data); | ||
|
||
let answer = block_on(transport.exchange(&command))?; | ||
result = answer.data().ok_or(LedgerError::UnexpectedNullResponse)?.to_vec(); | ||
let span = tracing::debug_span!("send_loop", index = 0, chunk = ""); | ||
let guard = span.entered(); | ||
for (index, chunk) in payload.chunks(chunk_size).enumerate() { | ||
guard.record("index", index); | ||
guard.record("chunk", hex::encode(chunk)); | ||
Comment on lines
+238
to
+239
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TIL |
||
command.data = APDUData::new(chunk); | ||
|
||
tracing::debug!("Dispatching packet to device"); | ||
answer = Some(block_on(transport.exchange(&command))?); | ||
|
||
let data = answer.as_ref().expect("just assigned").data(); | ||
if data.is_none() { | ||
return Err(LedgerError::UnexpectedNullResponse) | ||
} | ||
tracing::debug!( | ||
response = hex::encode(data.expect("just checked")), | ||
"Received response from device" | ||
); | ||
|
||
// We need more data | ||
command.p1 = P1::MORE as u8; | ||
} | ||
|
||
drop(guard); | ||
let answer = answer.expect("payload is non-empty, therefore loop ran"); | ||
let result = answer.data().expect("check in loop"); | ||
if result.len() < 65 { | ||
return Err(LedgerError::ShortResponse { got: result.len(), at_least: 65 }) | ||
} | ||
let v = result[0] as u64; | ||
let r = U256::from_big_endian(&result[1..33]); | ||
let s = U256::from_big_endian(&result[33..]); | ||
Ok(Signature { r, s, v }) | ||
let sig = Signature { r, s, v }; | ||
tracing::debug!(sig = %sig, "Received signature from device"); | ||
Ok(sig) | ||
} | ||
|
||
// helper which converts a derivation path to bytes | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
finds the largest chunk size that does not leave 3 hanging bytes on the payload lol
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ridiculous