1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#![deny(warnings, trivial_casts, trivial_numeric_casts)]
#![deny(unused_import_braces, unused_qualifications)]
#![deny(missing_docs)]
#![doc(html_root_url = "https://docs.rs/ledger-filecoin/0.1.0")]
use ledger_transport::{APDUCommand, APDUErrorCode, Exchange};
use ledger_zondax_generic::{App, AppExt, ChunkPayloadType, Version};
pub use ledger_zondax_generic::LedgerAppError;
mod params;
use params::{InstructionCode, CLA};
use std::str;
const PK_LEN: usize = 65;
#[derive(Debug, thiserror::Error)]
pub enum FilError<E>
where
E: std::error::Error,
{
#[error("Ledger | {0}")]
Ledger(#[from] LedgerAppError<E>),
#[error("Secp256k1 error: {0}")]
Secp256k1(#[from] k256::elliptic_curve::Error),
#[error("Ecdsa error: {0}")]
Ecdsa(#[from] k256::ecdsa::Error),
}
pub struct FilecoinApp<E> {
apdu_transport: E,
}
impl<E: Exchange> App for FilecoinApp<E> {
const CLA: u8 = CLA;
}
pub struct Address {
pub public_key: k256::PublicKey,
pub addr_byte: [u8; 21],
pub addr_string: String,
}
pub struct Signature {
pub r: [u8; 32],
pub s: [u8; 32],
pub v: u8,
pub sig: k256::ecdsa::Signature,
}
pub struct BIP44Path {
pub purpose: u32,
pub coin: u32,
pub account: u32,
pub change: u32,
pub index: u32,
}
impl BIP44Path {
pub fn serialize_bip44(&self) -> Vec<u8> {
use byteorder::{LittleEndian, WriteBytesExt};
let mut m = Vec::new();
m.write_u32::<LittleEndian>(self.purpose).unwrap();
m.write_u32::<LittleEndian>(self.coin).unwrap();
m.write_u32::<LittleEndian>(self.account).unwrap();
m.write_u32::<LittleEndian>(self.change).unwrap();
m.write_u32::<LittleEndian>(self.index).unwrap();
m
}
}
impl<E> FilecoinApp<E> {
pub const fn new(transport: E) -> Self {
FilecoinApp {
apdu_transport: transport,
}
}
}
impl<E> FilecoinApp<E>
where
E: Exchange + Send + Sync,
E::Error: std::error::Error,
{
pub async fn version(&self) -> Result<Version, FilError<E::Error>> {
<Self as AppExt<E>>::get_version(&self.apdu_transport)
.await
.map_err(Into::into)
}
pub async fn address(
&self,
path: &BIP44Path,
require_confirmation: bool,
) -> Result<Address, FilError<E::Error>> {
let serialized_path = path.serialize_bip44();
let p1 = if require_confirmation { 1 } else { 0 };
let command = APDUCommand {
cla: CLA,
ins: InstructionCode::GetAddrSecp256k1 as _,
p1,
p2: 0x00,
data: serialized_path,
};
let response = self
.apdu_transport
.exchange(&command)
.await
.map_err(LedgerAppError::TransportError)?;
let response_data = response.data();
match response.error_code() {
Ok(APDUErrorCode::NoError) if response_data.len() < PK_LEN => {
return Err(FilError::Ledger(LedgerAppError::InvalidPK))
}
Ok(APDUErrorCode::NoError) => {}
Ok(err) => {
return Err(FilError::Ledger(LedgerAppError::AppSpecific(
err as _,
err.description(),
)))
}
Err(err) => {
return Err(FilError::Ledger(LedgerAppError::AppSpecific(
err,
"[APDU_ERROR] Unknown".to_string(),
)))
}
}
let public_key = k256::PublicKey::from_sec1_bytes(&response_data[..PK_LEN])?;
let mut addr_byte = [Default::default(); 21];
addr_byte.copy_from_slice(&response_data[PK_LEN + 1..PK_LEN + 1 + 21]);
let tmp =
str::from_utf8(&response_data[PK_LEN + 2 + 21..]).map_err(|_| LedgerAppError::Utf8)?;
let addr_string = tmp.to_owned();
Ok(Address {
public_key,
addr_byte,
addr_string,
})
}
pub async fn sign(
&self,
path: &BIP44Path,
message: &[u8],
) -> Result<Signature, FilError<E::Error>> {
let bip44path = path.serialize_bip44();
let start_command = APDUCommand {
cla: CLA,
ins: InstructionCode::SignSecp256k1 as _,
p1: ChunkPayloadType::Init as u8,
p2: 0x00,
data: bip44path,
};
let response =
<Self as AppExt<E>>::send_chunks(&self.apdu_transport, start_command, message).await?;
let response_data = response.data();
match response.error_code() {
Ok(APDUErrorCode::NoError) if response_data.is_empty() => {
return Err(FilError::Ledger(LedgerAppError::NoSignature))
}
Ok(APDUErrorCode::NoError) if response_data.len() < 3 => {
return Err(FilError::Ledger(LedgerAppError::InvalidSignature))
}
Ok(APDUErrorCode::NoError) => {}
Ok(err) => {
return Err(FilError::Ledger(LedgerAppError::AppSpecific(
err as _,
err.description(),
)))
}
Err(err) => {
return Err(FilError::Ledger(LedgerAppError::AppSpecific(
err,
"[APDU_ERROR] Unknown".to_string(),
)))
}
}
let mut r = [0; 32];
r.copy_from_slice(&response_data[..32]);
let mut s = [0; 32];
s.copy_from_slice(&response_data[32..64]);
let v = response_data[64];
let sig = k256::ecdsa::Signature::from_der(&response_data[65..])?;
let signature = Signature { r, s, v, sig };
Ok(signature)
}
}
#[cfg(test)]
mod tests {
use super::BIP44Path;
#[test]
fn bip44() {
let path = BIP44Path {
purpose: 0x8000_0000 | 0x2c,
coin: 0x8000_0000 | 1,
account: 0x1234,
change: 0,
index: 0x5678,
};
let serialized_path = path.serialize_bip44();
assert_eq!(serialized_path.len(), 20);
assert_eq!(
hex::encode(&serialized_path),
"2c00008001000080341200000000000078560000"
);
}
}