@ledgerhq/hw-app-trx 6.24.1 → 6.25.1-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,362 @@
1
+ /********************************************************************************
2
+ * Ledger Node JS API
3
+ * (c) 2016-2017 Ledger
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ ********************************************************************************/
17
+ //@flow
18
+
19
+ // FIXME drop:
20
+ import { splitPath, foreach, decodeVarint } from "./utils";
21
+ //import { StatusCodes, TransportStatusError } from "@ledgerhq/errors";
22
+ import type Transport from "@ledgerhq/hw-transport";
23
+
24
+ const remapTransactionRelatedErrors = (e) => {
25
+ if (e && e.statusCode === 0x6a80) {
26
+ // TODO:
27
+ }
28
+ return e;
29
+ };
30
+
31
+ const PATH_SIZE = 4;
32
+ const PATHS_LENGTH_SIZE = 1;
33
+ const CLA = 0xe0;
34
+ const ADDRESS = 0x02;
35
+ const SIGN = 0x04;
36
+ const SIGN_HASH = 0x05;
37
+ const SIGN_MESSAGE = 0x08;
38
+ const ECDH_SECRET = 0x0a;
39
+ const VERSION = 0x06;
40
+ const CHUNK_SIZE = 250;
41
+
42
+ /**
43
+ * Tron API
44
+ *
45
+ * @example
46
+ * import Trx from "@ledgerhq/hw-app-trx";
47
+ * const trx = new Trx(transport)
48
+ */
49
+ export default class Trx {
50
+ transport: Transport<*>;
51
+
52
+ constructor(transport: Transport<*>, scrambleKey: string = "TRX") {
53
+ this.transport = transport;
54
+ transport.decorateAppAPIMethods(
55
+ this,
56
+ [
57
+ "getAddress",
58
+ "getECDHPairKey",
59
+ "signTransaction",
60
+ "signTransactionHash",
61
+ "signPersonalMessage",
62
+ "getAppConfiguration",
63
+ ],
64
+ scrambleKey
65
+ );
66
+ }
67
+
68
+ /**
69
+ * get Tron address for a given BIP 32 path.
70
+ * @param path a path in BIP 32 format
71
+ * @option boolDisplay optionally enable or not the display
72
+ * @return an object with a publicKey and address
73
+ * @example
74
+ * const address = await tron.getAddress("44'/195'/0'/0/0").then(o => o.address)
75
+ */
76
+ getAddress(
77
+ path: string,
78
+ boolDisplay?: boolean
79
+ ): Promise<{
80
+ publicKey: string,
81
+ address: string,
82
+ }> {
83
+ let paths = splitPath(path);
84
+ let buffer = Buffer.alloc(PATHS_LENGTH_SIZE + paths.length * PATH_SIZE);
85
+ buffer[0] = paths.length;
86
+ paths.forEach((element, index) => {
87
+ buffer.writeUInt32BE(element, 1 + 4 * index);
88
+ });
89
+ return this.transport
90
+ .send(CLA, ADDRESS, boolDisplay ? 0x01 : 0x00, 0x00, buffer)
91
+ .then((response) => {
92
+ let result = {};
93
+ let publicKeyLength = response[0];
94
+ let addressLength = response[1 + publicKeyLength];
95
+ result.publicKey = response
96
+ .slice(1, 1 + publicKeyLength)
97
+ .toString("hex");
98
+ result.address = response
99
+ .slice(
100
+ 1 + publicKeyLength + 1,
101
+ 1 + publicKeyLength + 1 + addressLength
102
+ )
103
+ .toString("ascii");
104
+ return result;
105
+ });
106
+ }
107
+
108
+ getNextLength(tx: Buffer) {
109
+ const field = decodeVarint(tx, 0);
110
+ const data = decodeVarint(tx, field.pos);
111
+ if ((field.value & 0x07) === 0) return data.pos;
112
+ return data.value + data.pos;
113
+ }
114
+
115
+ /**
116
+ * sign a Tron transaction with a given BIP 32 path and Token Names
117
+ *
118
+ * @param path a path in BIP 32 format
119
+ * @param rawTxHex a raw transaction hex string
120
+ * @param tokenSignatures Tokens Signatures array
121
+ * @option version pack message based on ledger firmware version
122
+ * @option smartContract boolean hack to set limit buffer on ledger device
123
+ * @return a signature as hex string
124
+ * @example
125
+ * const signature = await tron.signTransaction("44'/195'/0'/0/0", "0a02f5942208704dda506d59dceb40f0f4978f802e5a69080112650a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412340a1541978dbd103cfe59c35e753d09dd44ae1ae64621c7121541e2ae49db6a70b9b4757d2137a43b69b24a445780188ef8b5ba0470cbb5948f802e", [], 105);
126
+ */
127
+ signTransaction(
128
+ path: string,
129
+ rawTxHex: string,
130
+ tokenSignatures: string[]
131
+ ): Promise<string> {
132
+ const paths = splitPath(path);
133
+ let rawTx = Buffer.from(rawTxHex, "hex");
134
+ const toSend = [];
135
+
136
+ let data = Buffer.alloc(PATHS_LENGTH_SIZE + paths.length * PATH_SIZE);
137
+ // write path for first chuck only
138
+ data[0] = paths.length;
139
+ paths.forEach((element, index) => {
140
+ data.writeUInt32BE(element, 1 + 4 * index);
141
+ });
142
+
143
+ while (rawTx.length > 0) {
144
+ // get next message field
145
+ const newpos = this.getNextLength(rawTx);
146
+ if (newpos > CHUNK_SIZE) throw new Error("Too many bytes to encode.");
147
+ if (data.length + newpos > CHUNK_SIZE) {
148
+ toSend.push(data);
149
+ data = Buffer.alloc(0);
150
+ continue;
151
+ }
152
+ // append data
153
+ data = Buffer.concat([data, rawTx.slice(0, newpos)]);
154
+ rawTx = rawTx.slice(newpos, rawTx.length);
155
+ }
156
+ toSend.push(data);
157
+
158
+ const startBytes = [];
159
+ let response;
160
+
161
+ const tokenPos = toSend.length;
162
+ if (tokenSignatures !== undefined) {
163
+ for (let i = 0; i < tokenSignatures.length; i += 1) {
164
+ const buffer = Buffer.from(tokenSignatures[i], "hex");
165
+ toSend.push(buffer);
166
+ }
167
+ }
168
+
169
+ // get startBytes
170
+ if (toSend.length === 1) {
171
+ startBytes.push(0x10);
172
+ } else {
173
+ startBytes.push(0x00);
174
+ for (let i = 1; i < toSend.length - 1; i += 1) {
175
+ if (i >= tokenPos) {
176
+ startBytes.push(0xa0 | 0x00 | (i - tokenPos)); // eslint-disable-line no-bitwise
177
+ } else {
178
+ startBytes.push(0x80);
179
+ }
180
+ }
181
+ if (tokenSignatures !== undefined && tokenSignatures.length) {
182
+ startBytes.push(0xa0 | 0x08 | (tokenSignatures.length - 1)); // eslint-disable-line no-bitwise
183
+ } else {
184
+ startBytes.push(0x90);
185
+ }
186
+ }
187
+
188
+ return foreach(toSend, (data, i) => {
189
+ return this.transport
190
+ .send(CLA, SIGN, startBytes[i], 0x00, data)
191
+ .then((apduResponse) => {
192
+ response = apduResponse;
193
+ });
194
+ }).then(
195
+ () => {
196
+ return response.slice(0, 65).toString("hex");
197
+ },
198
+ (e) => {
199
+ throw remapTransactionRelatedErrors(e);
200
+ }
201
+ );
202
+ }
203
+
204
+ /**
205
+ * sign a Tron transaction hash with a given BIP 32 path
206
+ *
207
+ * @param path a path in BIP 32 format
208
+ * @param rawTxHex a raw transaction hex string
209
+ * @return a signature as hex string
210
+ * @example
211
+ * const signature = await tron.signTransactionHash("44'/195'/0'/0/0", "25b18a55f86afb10e7aca38d0073d04c80397c6636069193953fdefaea0b8369");
212
+ */
213
+ signTransactionHash(path: string, rawTxHashHex: string): Promise<string> {
214
+ const paths = splitPath(path);
215
+ let data = Buffer.alloc(PATHS_LENGTH_SIZE + paths.length * PATH_SIZE);
216
+ data[0] = paths.length;
217
+ paths.forEach((element, index) => {
218
+ data.writeUInt32BE(element, 1 + 4 * index);
219
+ });
220
+ data = Buffer.concat([data, Buffer.from(rawTxHashHex, "hex")]);
221
+
222
+ return this.transport
223
+ .send(CLA, SIGN_HASH, 0x00, 0x00, data)
224
+ .then((response) => {
225
+ return response.slice(0, 65).toString("hex");
226
+ });
227
+ }
228
+
229
+ /**
230
+ * get the version of the Tron app installed on the hardware device
231
+ *
232
+ * @return an object with a version
233
+ * @example
234
+ * const result = await tron.getAppConfiguration();
235
+ * {
236
+ * "version": "0.1.5",
237
+ * "versionN": "105".
238
+ * "allowData": false,
239
+ * "allowContract": false,
240
+ * "truncateAddress": false,
241
+ * "signByHash": false
242
+ * }
243
+ */
244
+ getAppConfiguration(): Promise<{
245
+ allowContract: Boolean,
246
+ truncateAddress: Boolean,
247
+ allowData: Boolean,
248
+ signByHash: Boolean,
249
+ version: string,
250
+ versionN: number,
251
+ }> {
252
+ return this.transport.send(CLA, VERSION, 0x00, 0x00).then((response) => {
253
+ // eslint-disable-next-line no-bitwise
254
+ let signByHash = (response[0] & (1 << 3)) > 0;
255
+ // eslint-disable-next-line no-bitwise
256
+ let truncateAddress = (response[0] & (1 << 2)) > 0;
257
+ // eslint-disable-next-line no-bitwise
258
+ let allowContract = (response[0] & (1 << 1)) > 0;
259
+ // eslint-disable-next-line no-bitwise
260
+ let allowData = (response[0] & (1 << 0)) > 0;
261
+ if (response[1] === 0 && response[2] === 1 && response[3] < 2) {
262
+ allowData = true;
263
+ allowContract = false;
264
+ }
265
+ if (response[1] === 0 && response[2] === 1 && response[3] < 5) {
266
+ truncateAddress = false;
267
+ }
268
+ const result = {
269
+ version: `${response[1]}.${response[2]}.${response[3]}`,
270
+ versionN: response[1] * 10000 + response[2] * 100 + response[3],
271
+ allowData,
272
+ allowContract,
273
+ truncateAddress,
274
+ signByHash,
275
+ };
276
+ return result;
277
+ });
278
+ }
279
+
280
+ /**
281
+ * sign a Tron Message with a given BIP 32 path
282
+ *
283
+ * @param path a path in BIP 32 format
284
+ * @param message hex string to sign
285
+ * @return a signature as hex string
286
+ * @example
287
+ * const signature = await tron.signPersonalMessage("44'/195'/0'/0/0", "43727970746f436861696e2d54726f6e5352204c6564676572205472616e73616374696f6e73205465737473");
288
+ */
289
+ signPersonalMessage(path: string, messageHex: string): Promise<string> {
290
+ let paths = splitPath(path);
291
+ const message = Buffer.from(messageHex, "hex");
292
+ let offset = 0;
293
+ let toSend = [];
294
+
295
+ const size = message.length.toString(16);
296
+ const sizePack = "00000000".substr(size.length) + size;
297
+ const packed = Buffer.concat([Buffer.from(sizePack, "hex"), message]);
298
+
299
+ while (offset < packed.length) {
300
+ // Use small buffer to be compatible with old and new protocol
301
+ let maxChunkSize =
302
+ offset === 0 ? CHUNK_SIZE - 1 - paths.length * 4 : CHUNK_SIZE;
303
+ let chunkSize =
304
+ offset + maxChunkSize > packed.length
305
+ ? packed.length - offset
306
+ : maxChunkSize;
307
+ let buffer = Buffer.alloc(
308
+ offset === 0 ? 1 + paths.length * 4 + chunkSize : chunkSize
309
+ );
310
+ if (offset === 0) {
311
+ buffer[0] = paths.length;
312
+ paths.forEach((element, index) => {
313
+ buffer.writeUInt32BE(element, 1 + 4 * index);
314
+ });
315
+ packed.copy(buffer, 1 + 4 * paths.length, offset, offset + chunkSize);
316
+ } else {
317
+ packed.copy(buffer, 0, offset, offset + chunkSize);
318
+ }
319
+ toSend.push(buffer);
320
+ offset += chunkSize;
321
+ }
322
+ let response;
323
+ return foreach(toSend, (data, i) => {
324
+ return this.transport
325
+ .send(CLA, SIGN_MESSAGE, i === 0 ? 0x00 : 0x80, 0x00, data)
326
+ .then((apduResponse) => {
327
+ response = apduResponse;
328
+ });
329
+ }).then(() => {
330
+ return response.slice(0, 65).toString("hex");
331
+ });
332
+ }
333
+
334
+ /**
335
+ * get Tron address for a given BIP 32 path.
336
+ * @param path a path in BIP 32 format
337
+ * @param publicKey address public key to generate pair key
338
+ * @return shared key hex string,
339
+ * @example
340
+ * const signature = await tron.getECDHPairKey("44'/195'/0'/0/0", "04ff21f8e64d3a3c0198edfbb7afdc79be959432e92e2f8a1984bb436a414b8edcec0345aad0c1bf7da04fd036dd7f9f617e30669224283d950fab9dd84831dc83");
341
+ */
342
+ getECDHPairKey(
343
+ path: string,
344
+ publicKey: string
345
+ ): Promise<{
346
+ publicKey: string,
347
+ address: string,
348
+ }> {
349
+ const paths = splitPath(path);
350
+ const data = Buffer.from(publicKey, "hex");
351
+ const buffer = Buffer.alloc(1 + paths.length * 4 + data.length);
352
+ buffer[0] = paths.length;
353
+ paths.forEach((element, index) => {
354
+ buffer.writeUInt32BE(element, 1 + 4 * index);
355
+ });
356
+ data.copy(buffer, 1 + 4 * paths.length, 0, data.length);
357
+
358
+ return this.transport
359
+ .send(CLA, ECDH_SECRET, 0x00, 0x01, buffer)
360
+ .then((response) => response.slice(0, 65).toString("hex"));
361
+ }
362
+ }
@@ -0,0 +1,126 @@
1
+ /********************************************************************************
2
+ * Ledger Node JS API
3
+ * (c) 2016-2017 Ledger
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ ********************************************************************************/
17
+ //@flow
18
+
19
+ type Defer<T> = {
20
+ promise: Promise<T>,
21
+ resolve: (T) => void,
22
+ reject: (any) => void,
23
+ };
24
+
25
+ export function defer<T>(): Defer<T> {
26
+ let resolve, reject;
27
+ let promise = new Promise(function (success, failure) {
28
+ resolve = success;
29
+ reject = failure;
30
+ });
31
+ if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy
32
+ return { promise, resolve, reject };
33
+ }
34
+
35
+ // TODO use bip32-path library
36
+ export function splitPath(path: string): number[] {
37
+ let result = [];
38
+ let components = path.split("/");
39
+ components.forEach((element) => {
40
+ let number = parseInt(element, 10);
41
+ if (isNaN(number)) {
42
+ return; // FIXME shouldn't it throws instead?
43
+ }
44
+ if (element.length > 1 && element[element.length - 1] === "'") {
45
+ number += 0x80000000;
46
+ }
47
+ result.push(number);
48
+ });
49
+ return result;
50
+ }
51
+
52
+ // TODO use async await
53
+
54
+ export function eachSeries<A>(arr: A[], fun: (A) => Promise<*>): Promise<*> {
55
+ return arr.reduce((p, e) => p.then(() => fun(e)), Promise.resolve());
56
+ }
57
+
58
+ export function foreach<T, A>(
59
+ arr: T[],
60
+ callback: (T, number) => Promise<A>
61
+ ): Promise<A[]> {
62
+ function iterate(index, array, result) {
63
+ if (index >= array.length) {
64
+ return result;
65
+ } else
66
+ return callback(array[index], index).then(function (res) {
67
+ result.push(res);
68
+ return iterate(index + 1, array, result);
69
+ });
70
+ }
71
+ return Promise.resolve().then(() => iterate(0, arr, []));
72
+ }
73
+
74
+ export function doIf(
75
+ condition: boolean,
76
+ callback: () => any | Promise<any>
77
+ ): Promise<void> {
78
+ return Promise.resolve().then(() => {
79
+ if (condition) {
80
+ return callback();
81
+ }
82
+ });
83
+ }
84
+
85
+ export function asyncWhile<T>(
86
+ predicate: () => boolean,
87
+ callback: () => Promise<T>
88
+ ): Promise<Array<T>> {
89
+ function iterate(result) {
90
+ if (!predicate()) {
91
+ return result;
92
+ } else {
93
+ return callback().then((res) => {
94
+ result.push(res);
95
+ return iterate(result);
96
+ });
97
+ }
98
+ }
99
+ return Promise.resolve([]).then(iterate);
100
+ }
101
+
102
+ interface DecodeResult {
103
+ value: number;
104
+ pos: number;
105
+ }
106
+
107
+ export function decodeVarint(stream: Buffer, index: number): DecodeResult {
108
+ let result = 0;
109
+ let shift = 0;
110
+ let pos = index;
111
+ // eslint-disable-next-line no-constant-condition
112
+ while (shift < 64) {
113
+ const b = stream[pos];
114
+ result |= (b & 0x7f) << shift;
115
+ pos += 1;
116
+ if (!(b & 0x80)) {
117
+ result &= 0xffffffff;
118
+ return {
119
+ value: result,
120
+ pos,
121
+ };
122
+ }
123
+ shift += 7;
124
+ }
125
+ throw new Error("Too many bytes when decoding varint.");
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ledgerhq/hw-app-trx",
3
- "version": "6.24.1",
3
+ "version": "6.25.1-alpha.3+eb669e17",
4
4
  "description": "Ledger Hardware Wallet Tron Application API",
5
5
  "keywords": [
6
6
  "Ledger",
@@ -28,7 +28,7 @@
28
28
  "license": "Apache-2.0",
29
29
  "dependencies": {
30
30
  "@ledgerhq/errors": "^6.10.0",
31
- "@ledgerhq/hw-transport": "^6.24.1"
31
+ "@ledgerhq/hw-transport": "^6.25.1-alpha.3+eb669e17"
32
32
  },
33
33
  "scripts": {
34
34
  "clean": "bash ../../script/clean.sh",
@@ -36,5 +36,5 @@
36
36
  "watch": "bash ../../script/watch.sh",
37
37
  "doc": "bash ../../script/doc.sh"
38
38
  },
39
- "gitHead": "159269dafc5f177c7af5b20761ab0ef3550e3faf"
39
+ "gitHead": "eb669e17dd87d3ab568beab1f9a5ddb1a2536e83"
40
40
  }