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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*******************************************************************************
*   (c) 2018 ZondaX GmbH
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
********************************************************************************/
//! Provider for Ledger cosmos validator app
#[macro_use]
extern crate quick_error;

#[cfg(test)]
#[macro_use]
extern crate matches;

extern crate byteorder;
extern crate ledger;

const CLA: u8 = 0x56;
const INS_GET_VERSION: u8 = 0x00;
const INS_PUBLIC_KEY_ED25519: u8 = 0x01;
const INS_SIGN_ED25519: u8 = 0x02;

const USER_MESSAGE_CHUNK_SIZE: usize = 250;

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        InvalidVersion{
            description("This version is not supported")
        }
        InvalidEmptyMessage{
            description("message cannot be empty")
        }
        InvalidMessageSize{
            description("message size is invalid (too big)")
        }
        InvalidPK{
            description("received an invalid PK")
        }
        InvalidSignature {
            description("received an invalid signature")
        }
        InvalidDerivationPath {
            description("invalid derivation path")
        }
        Ledger ( err: ledger::Error ) {
            from()
            description("ledger error")
            display("Ledger error: {}", err)
            cause(err)
        }
    }
}

#[allow(dead_code)]
pub struct CosmosValidatorApp
{
    app: ledger::LedgerApp
}

unsafe impl Send for CosmosValidatorApp {}

#[allow(dead_code)]
pub struct Version {
    mode: u8,
    major: u8,
    minor: u8,
    patch: u8,
}

fn to_bip32array(path: &[u32]) -> Result<Vec<u8>, Error> {
    use byteorder::{LittleEndian, WriteBytesExt};

    if path.len() > 10 {
        return Err(Error::InvalidDerivationPath);
    }

    let mut answer = Vec::new();
    answer.write_u8(path.len() as u8).unwrap();

    for v in path { answer.write_u32::<LittleEndian>(*v).unwrap(); }

    Ok(answer)
}

impl CosmosValidatorApp {
    pub fn connect() -> Result<Self, Error> {
        let app = ledger::LedgerApp::new()?;
        Ok(CosmosValidatorApp { app })
    }

    pub fn version(&self) -> Result<Version, Error> {
        use ledger::ApduCommand;

        let command = ApduCommand {
            cla: CLA,
            ins: INS_GET_VERSION,
            p1: 0x00,
            p2: 0x00,
            length: 0,
            data: Vec::new(),
        };

        let response = self.app.exchange(command)?;

        // TODO: this is just temporary, ledger errors should check for 0x9000
        if response.retcode != 0x9000 {
            return Err(Error::InvalidVersion);
        }

        let version = Version {
            mode: response.data[0],
            major: response.data[1],
            minor: response.data[2],
            patch: response.data[3],
        };

        Result::Ok(version)
    }

    pub fn public_key(&self) -> Result<[u8; 32], Error> {
        use ledger::ApduCommand;

        // TODO: Define what to do with the derivation path
        let mut bip32 = vec![44, 118, 0, 0, 0];
        for i in &mut bip32 {
            *i |= 0x8000_0000;
        }

        let bip32path = to_bip32array(&bip32)?;

        let command = ApduCommand {
            cla: CLA,
            ins: INS_PUBLIC_KEY_ED25519,
            p1: 0x00,
            p2: 0x00,
            length: bip32path.len() as u8,
            data: bip32path,
        };

        let response = self.app.exchange(command)?;

        if response.retcode != 0x9000 {
            println!("WARNING: retcode={:X?}", response.retcode);
        }

        if response.data.len() != 32 {
            return Err(Error::InvalidPK);
        }

        let mut array = [0u8; 32];
        array.copy_from_slice(&response.data[..32]);
        Ok(array)
    }

    // Sign message
    pub fn sign(&self, message: &[u8]) -> Result<[u8; 64], Error> {
        use ledger::ApduCommand;
        use ledger::ApduAnswer;

        let chunks = message.chunks(USER_MESSAGE_CHUNK_SIZE);

        if chunks.len() > 255 {
            return Err(Error::InvalidMessageSize);
        }

        if chunks.len() == 0 {
            return Err(Error::InvalidEmptyMessage);
        }

        let packet_count = chunks.len() as u8;
        let mut response: ApduAnswer = ApduAnswer{ data: vec![], retcode: 0 };

        // Send message chunks
        for (packet_idx, chunk) in chunks.enumerate() {
            let _command = ApduCommand {
                cla: CLA,
                ins: INS_SIGN_ED25519,
                p1: packet_idx as u8,
                p2: packet_count,
                length: chunk.len() as u8,
                data: chunk.to_vec(),
            };

            response = self.app.exchange(_command)?;
        }

        // Last response should contain the answer
        if response.data.len() != 64 {
            return Err(Error::InvalidSignature);
        }

        let mut array = [0u8; 64];
        array.copy_from_slice(&response.data[..64]);
        Ok(array)
    }
}

#[cfg(test)]
mod tests {
    use std::time;
    use std::thread;

    #[test]
    fn derivation_path() {
        use to_bip32array;

        let mut answer = to_bip32array(&vec![1]).unwrap();
        assert_eq!(answer, b"\x01\
                             \x01\x00\x00\x00");

        answer = to_bip32array(&vec![1, 2]).unwrap();
        assert_eq!(answer, b"\x02\
                             \x01\x00\x00\x00\
                             \x02\x00\x00\x00");

        answer = to_bip32array(&vec![1, 2, 12345]).unwrap();
        assert_eq!(answer, b"\x03\
                             \x01\x00\x00\x00\
                             \x02\x00\x00\x00\
                             \x39\x30\x00\x00");

        answer = to_bip32array(&vec![44, 118, 0, 0, 0]).unwrap();
        assert_eq!(answer, b"\x05\
                             \x2c\x00\x00\x00\
                             \x76\x00\x00\x00\
                             \x00\x00\x00\x00\
                             \x00\x00\x00\x00\
                             \x00\x00\x00\x00");

        answer = to_bip32array(&vec![
            44 | 0x80000000,
            118 | 0x80000000,
            0 | 0x80000000,
            0 | 0x80000000,
            0 | 0x80000000]).unwrap();

        assert_eq!(answer, b"\x05\
                             \x2c\x00\x00\x80\
                             \x76\x00\x00\x80\
                             \x00\x00\x00\x80\
                             \x00\x00\x00\x80\
                             \x00\x00\x00\x80");
    }

    #[test]
    fn version() {
        use CosmosValidatorApp;

        let app = CosmosValidatorApp::connect().unwrap();

        let version = app.version().unwrap();

        assert_eq!(version.mode, 0xFF);
        assert_eq!(version.major, 0x00);
        assert_eq!(version.minor, 0x01);
        assert_eq!(version.patch, 0x00);
    }

    #[test]
    fn public_key() {
        use CosmosValidatorApp;

        let app = CosmosValidatorApp::connect().unwrap();
        let resp = app.public_key();

        match resp {
            Ok(pk) => {
                assert_eq!(pk.len(), 32);
                println!("{:?}", pk);
            }
            Err(err) => {
                eprintln!("Error: {:?}", err);
            }
        }

    }

    #[test]
    fn sign_empty() {
        use CosmosValidatorApp;
        use Error;

        let app = CosmosValidatorApp::connect().unwrap();

        let some_message0 = b"";

        let signature = app.sign(some_message0);
        assert!(signature.is_err());
        assert!(matches!(signature.err().unwrap(), Error::InvalidEmptyMessage));
    }

    #[test]
    fn sign() {
        use CosmosValidatorApp;

        let app = CosmosValidatorApp::connect().unwrap();

        // First, get public key
        let resp = app.public_key();
        match resp {
            Ok(pk) => {
                assert_eq!(pk.len(), 32);
                println!("{:?}", pk);
            }
            Err(err) => {
                eprintln!("Error: {:?}", err);
            }
        }

        let some_message1= [
            0x8,                                    // (field_number << 3) | wire_type
            0x1,                                    // PrevoteType
            0x11,                                   // (field_number << 3) | wire_type
            0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height
            0x19,                                   // (field_number << 3) | wire_type
            0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round
            0x22, // (field_number << 3) | wire_type
            // remaining fields (timestamp):
            0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1];

        let signature = app.sign(&some_message1).unwrap();
        println!("{:#?}", signature.to_vec());

        let some_message2= [
            0x8,                                    // (field_number << 3) | wire_type
            0x1,                                    // PrevoteType
            0x11,                                   // (field_number << 3) | wire_type
            0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height
            0x19,                                   // (field_number << 3) | wire_type
            0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round
            0x22, // (field_number << 3) | wire_type
            // remaining fields (timestamp):
            0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1];

        let signature = app.sign(&some_message2).unwrap();
        println!("{:#?}", signature.to_vec());
    }

    #[test]
    fn sign_many() {
        use CosmosValidatorApp;

        let app = CosmosValidatorApp::connect().unwrap();

        // First, get public key
        let resp = app.public_key();
        match resp {
            Ok(pk) => {
                assert_eq!(pk.len(), 32);
                println!("{:?}", pk);
            }
            Err(err) => {
                eprintln!("Error: {:?}", err);
            }
        }


        // Now send several votes
        for index in 50u8..254u8 {
            let some_message1 = [
                0x8,                                    // (field_number << 3) | wire_type
                0x1,                                    // PrevoteType
                0x11,                                   // (field_number << 3) | wire_type
                index, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // height
                0x19,                                   // (field_number << 3) | wire_type
                0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round
                0x22, // (field_number << 3) | wire_type
                // remaining fields (timestamp):
                0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1];

            let signature = app.sign(&some_message1);
            match signature {
                Ok(sig) => {
//                    println!("{:#?}", sig.to_vec());
                },
                Err(e) => {
                    println!("Err {:#?}", e);
                }
            }
        }
    }
}