|
| 1 | +use async_trait::async_trait; |
| 2 | +use coins_ledger::{ |
| 3 | + common::{APDUData, APDUResponseCodes}, |
| 4 | + transports::LedgerAsync, |
| 5 | + APDUAnswer, APDUCommand, Ledger, |
| 6 | +}; |
| 7 | +use crypto_bigint::{ArrayEncoding, U256}; |
| 8 | +use starknet_core::{crypto::Signature, types::Felt}; |
| 9 | + |
| 10 | +use crate::{Signer, VerifyingKey}; |
| 11 | + |
| 12 | +pub use coins_bip32::path::DerivationPath; |
| 13 | + |
| 14 | +/// The Ledger application identifier for app-starknet. |
| 15 | +const CLA_STARKNET: u8 = 0x5a; |
| 16 | + |
| 17 | +/// BIP-32 encoding of `2645'` |
| 18 | +const EIP_2645_PURPOSE: u32 = 0x80000a55; |
| 19 | + |
| 20 | +const EIP_2645_PATH_LENGTH: usize = 6; |
| 21 | + |
| 22 | +const PUBLIC_KEY_SIZE: usize = 65; |
| 23 | +const SIGNATURE_SIZE: usize = 65; |
| 24 | + |
| 25 | +#[derive(Debug)] |
| 26 | +pub struct LedgerSigner { |
| 27 | + transport: Ledger, |
| 28 | + derivation_path: DerivationPath, |
| 29 | +} |
| 30 | + |
| 31 | +#[derive(Debug, thiserror::Error)] |
| 32 | +pub enum LedgerError { |
| 33 | + #[error("derivation path is empty, not prefixed with m/2645', or is not 6-level long")] |
| 34 | + InvalidDerivationPath, |
| 35 | + #[error(transparent)] |
| 36 | + TransportError(coins_ledger::LedgerError), |
| 37 | + #[error("unknown response code from Ledger: {0}")] |
| 38 | + UnknownResponseCode(u16), |
| 39 | + #[error("failed Ledger request: {0}")] |
| 40 | + UnsuccessfulRequest(APDUResponseCodes), |
| 41 | + #[error("unexpected response length - expected: {expected}; actual: {actual}")] |
| 42 | + UnexpectedResponseLength { expected: usize, actual: usize }, |
| 43 | +} |
| 44 | + |
| 45 | +/// The `GetPubKey` Ledger command. |
| 46 | +struct GetPubKeyCommand { |
| 47 | + display: bool, |
| 48 | + path: DerivationPath, |
| 49 | +} |
| 50 | + |
| 51 | +/// Part 1 of the `SignHash` command for setting path. |
| 52 | +struct SignHashCommand1 { |
| 53 | + path: DerivationPath, |
| 54 | +} |
| 55 | + |
| 56 | +/// Part 2 of the `SignHash` command for setting hash. |
| 57 | +struct SignHashCommand2 { |
| 58 | + hash: [u8; 32], |
| 59 | +} |
| 60 | + |
| 61 | +impl LedgerSigner { |
| 62 | + /// Initializes the Starknet Ledger app. Attempts to find and connect to a Ledger device. The |
| 63 | + /// device must be unlocked and have the Starknet app open. |
| 64 | + /// |
| 65 | + /// The `derivation_path` passed in _must_ follow EIP-2645, i.e. having `2645'` as its "purpose" |
| 66 | + /// level as per BIP-44, as the Ledger app does not allow other paths to be used. |
| 67 | + /// |
| 68 | + /// The path _must_ also be 6-level in length. An example path for Starknet would be: |
| 69 | + /// |
| 70 | + /// `m/2645'/1195502025'/1470455285'/0'/0'/0` |
| 71 | + /// |
| 72 | + /// where: |
| 73 | + /// |
| 74 | + /// - `2645'` is the EIP-2645 prefix |
| 75 | + /// - `1195502025'`, decimal for `0x4741e9c9`, is the 31 lowest bits for `sha256(starknet)` |
| 76 | + /// - `1470455285'`, decimal for `0x57a55df5`, is the 31 lowest bits for `sha256(starkli)` |
| 77 | + /// |
| 78 | + /// Currently, the Ledger app only enforces the length and the first level of the path. |
| 79 | + pub async fn new(derivation_path: DerivationPath) -> Result<Self, LedgerError> { |
| 80 | + let transport = Ledger::init().await?; |
| 81 | + |
| 82 | + if !matches!(derivation_path.iter().next(), Some(&EIP_2645_PURPOSE)) |
| 83 | + || derivation_path.len() != EIP_2645_PATH_LENGTH |
| 84 | + { |
| 85 | + return Err(LedgerError::InvalidDerivationPath); |
| 86 | + } |
| 87 | + |
| 88 | + Ok(Self { |
| 89 | + transport, |
| 90 | + derivation_path, |
| 91 | + }) |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +#[async_trait] |
| 96 | +impl Signer for LedgerSigner { |
| 97 | + type GetPublicKeyError = LedgerError; |
| 98 | + type SignError = LedgerError; |
| 99 | + |
| 100 | + async fn get_public_key(&self) -> Result<VerifyingKey, Self::GetPublicKeyError> { |
| 101 | + let response = self |
| 102 | + .transport |
| 103 | + .exchange( |
| 104 | + &GetPubKeyCommand { |
| 105 | + display: false, |
| 106 | + path: self.derivation_path.clone(), |
| 107 | + } |
| 108 | + .into(), |
| 109 | + ) |
| 110 | + .await?; |
| 111 | + |
| 112 | + let data = get_apdu_data(&response)?; |
| 113 | + if data.len() != PUBLIC_KEY_SIZE { |
| 114 | + return Err(LedgerError::UnexpectedResponseLength { |
| 115 | + expected: PUBLIC_KEY_SIZE, |
| 116 | + actual: data.len(), |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + // Unwrapping here is safe as length is fixed |
| 121 | + let pubkey_x = Felt::from_bytes_be(&data[1..33].try_into().unwrap()); |
| 122 | + |
| 123 | + Ok(VerifyingKey::from_scalar(pubkey_x)) |
| 124 | + } |
| 125 | + |
| 126 | + async fn sign_hash(&self, hash: &Felt) -> Result<Signature, Self::SignError> { |
| 127 | + get_apdu_data( |
| 128 | + &self |
| 129 | + .transport |
| 130 | + .exchange( |
| 131 | + &SignHashCommand1 { |
| 132 | + path: self.derivation_path.clone(), |
| 133 | + } |
| 134 | + .into(), |
| 135 | + ) |
| 136 | + .await?, |
| 137 | + )?; |
| 138 | + |
| 139 | + let response = self |
| 140 | + .transport |
| 141 | + .exchange( |
| 142 | + &SignHashCommand2 { |
| 143 | + hash: hash.to_bytes_be(), |
| 144 | + } |
| 145 | + .into(), |
| 146 | + ) |
| 147 | + .await?; |
| 148 | + |
| 149 | + let data = get_apdu_data(&response)?; |
| 150 | + |
| 151 | + if data.len() != SIGNATURE_SIZE + 1 || data[0] != SIGNATURE_SIZE as u8 { |
| 152 | + return Err(LedgerError::UnexpectedResponseLength { |
| 153 | + expected: SIGNATURE_SIZE, |
| 154 | + actual: data.len(), |
| 155 | + }); |
| 156 | + } |
| 157 | + |
| 158 | + // Unwrapping here is safe as length is fixed |
| 159 | + let r = Felt::from_bytes_be(&data[1..33].try_into().unwrap()); |
| 160 | + let s = Felt::from_bytes_be(&data[33..65].try_into().unwrap()); |
| 161 | + |
| 162 | + let signature = Signature { r, s }; |
| 163 | + |
| 164 | + Ok(signature) |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +impl From<coins_ledger::LedgerError> for LedgerError { |
| 169 | + fn from(value: coins_ledger::LedgerError) -> Self { |
| 170 | + Self::TransportError(value) |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +impl From<GetPubKeyCommand> for APDUCommand { |
| 175 | + fn from(value: GetPubKeyCommand) -> Self { |
| 176 | + let path = value |
| 177 | + .path |
| 178 | + .iter() |
| 179 | + .flat_map(|level| level.to_be_bytes()) |
| 180 | + .collect::<Vec<_>>(); |
| 181 | + |
| 182 | + Self { |
| 183 | + cla: CLA_STARKNET, |
| 184 | + ins: 0x01, |
| 185 | + p1: if value.display { 0x01 } else { 0x00 }, |
| 186 | + p2: 0x00, |
| 187 | + data: APDUData::new(&path), |
| 188 | + response_len: None, |
| 189 | + } |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +impl From<SignHashCommand1> for APDUCommand { |
| 194 | + fn from(value: SignHashCommand1) -> Self { |
| 195 | + let path = value |
| 196 | + .path |
| 197 | + .iter() |
| 198 | + .flat_map(|level| level.to_be_bytes()) |
| 199 | + .collect::<Vec<_>>(); |
| 200 | + |
| 201 | + Self { |
| 202 | + cla: CLA_STARKNET, |
| 203 | + ins: 0x02, |
| 204 | + p1: 0x00, |
| 205 | + p2: 0x00, |
| 206 | + data: APDUData::new(&path), |
| 207 | + response_len: None, |
| 208 | + } |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +impl From<SignHashCommand2> for APDUCommand { |
| 213 | + fn from(value: SignHashCommand2) -> Self { |
| 214 | + // For some reasons, the Ledger app expects the input to be left shifted by 4 bits... |
| 215 | + let shifted_bytes: [u8; 32] = (U256::from_be_slice(&value.hash) << 4) |
| 216 | + .to_be_byte_array() |
| 217 | + .into(); |
| 218 | + |
| 219 | + Self { |
| 220 | + cla: CLA_STARKNET, |
| 221 | + ins: 0x02, |
| 222 | + p1: 0x01, |
| 223 | + p2: 0x00, |
| 224 | + data: APDUData::new(&shifted_bytes), |
| 225 | + response_len: None, |
| 226 | + } |
| 227 | + } |
| 228 | +} |
| 229 | + |
| 230 | +fn get_apdu_data(answer: &APDUAnswer) -> Result<&[u8], LedgerError> { |
| 231 | + let ret_code = answer.retcode(); |
| 232 | + |
| 233 | + match TryInto::<APDUResponseCodes>::try_into(ret_code) { |
| 234 | + Ok(status) => { |
| 235 | + if status.is_success() { |
| 236 | + // Unwrapping here as we've already checked success |
| 237 | + Ok(answer.data().unwrap()) |
| 238 | + } else { |
| 239 | + Err(LedgerError::UnsuccessfulRequest(status)) |
| 240 | + } |
| 241 | + } |
| 242 | + Err(_) => Err(LedgerError::UnknownResponseCode(ret_code)), |
| 243 | + } |
| 244 | +} |
0 commit comments