-
Notifications
You must be signed in to change notification settings - Fork 30
/
generic_app.ts
286 lines (248 loc) · 10.6 KB
/
generic_app.ts
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
/** ******************************************************************************
* (c) 2019 - 2024 Zondax AG
*
* 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.
******************************************************************************* */
import axios from 'axios'
import type Transport from '@ledgerhq/hw-transport'
import BaseApp, { BIP32Path, INSGeneric, LedgerError, ResponseError, processErrorResponse, processResponse } from '@zondax/ledger-js'
import {
GenericResponseSign,
GenericeResponseAddress,
P1_VALUES,
SS58Prefix,
TransactionBlob,
TransactionMetadataBlob,
TxMetadata,
} from './common'
export class PolkadotGenericApp extends BaseApp {
static _INS = {
GET_VERSION: 0x00 as number,
GET_ADDR: 0x01 as number,
SIGN: 0x02 as number,
SIGN_RAW: 0x03 as number,
}
static _params = {
cla: 0xf9,
ins: { ...PolkadotGenericApp._INS } as INSGeneric,
p1Values: { ONLY_RETRIEVE: 0x00 as 0, SHOW_ADDRESS_IN_DEVICE: 0x01 as 1 },
chunkSize: 250,
requiredPathLengths: [5],
}
txMetadataChainId?: string
txMetadataSrvUrl?: string
/**
* Constructs a new PolkadotGenericApp instance.
* @param transport - The transport instance.
* @param txMetadataChainId - The chain ID in the transaction metadata service.
* @param txMetadataSrvUrl - The optional transaction metadata service URL.
* @throws {Error} - If the transport is not defined.
*/
constructor(transport: Transport, txMetadataChainId?: string, txMetadataSrvUrl?: string) {
super(transport, PolkadotGenericApp._params)
this.txMetadataSrvUrl = txMetadataSrvUrl
this.txMetadataChainId = txMetadataChainId
if (!this.transport) {
throw new Error('Transport has not been defined')
}
}
/**
* Retrieves transaction metadata from the metadata service.
* @param txBlob - The transaction blob.
* @param txMetadataChainId - The optional chain ID for the transaction metadata service. This value temporarily overrides the one set in the constructor.
* @param txMetadataSrvUrl - The optional URL for the transaction metadata service. This value temporarily overrides the one set in the constructor.
* @returns The transaction metadata.
* @throws {ResponseError} - If the txMetadataSrvUrl is not defined.
*/
async getTxMetadata(txBlob: TransactionBlob, txMetadataChainId?: string, txMetadataSrvUrl?: string): Promise<TransactionMetadataBlob> {
const txMetadataChainIdVal = txMetadataChainId ?? this.txMetadataChainId
const txMetadataSrvUrlVal = txMetadataSrvUrl ?? this.txMetadataSrvUrl
if (!txMetadataChainIdVal) {
throw new ResponseError(
LedgerError.GenericError,
'txMetadataSrvUrl is not defined or is empty. The use of the method requires access to a metadata shortening service.'
)
}
if (!txMetadataSrvUrlVal) {
throw new ResponseError(
LedgerError.GenericError,
'txMetadataChainId is not defined or is empty. These values are configured in the metadata shortening service. Check the corresponding configuration in the service.'
)
}
const resp = await axios.post<TxMetadata>(txMetadataSrvUrlVal, {
txBlob: txBlob.toString('hex'),
chain: { id: txMetadataChainIdVal },
})
let txMetadata = resp.data.txMetadata
if (txMetadata.slice(0, 2) === '0x') {
txMetadata = txMetadata.slice(2)
}
return Buffer.from(txMetadata, 'hex')
}
/**
* Retrieves the address for a given BIP44 path and SS58 prefix.
* @param bip44Path - The BIP44 path.
* @param ss58prefix - The SS58 prefix, must be an integer up to 65535.
* @param showAddrInDevice - Whether to show the address on the device.
* @returns The address response.
* @throws {ResponseError} If the response from the device indicates an error.
*/
async getAddress(bip44Path: BIP32Path, ss58prefix: SS58Prefix, showAddrInDevice = false): Promise<GenericeResponseAddress> {
// needs to be integer, and up to 65535
if (!Number.isInteger(ss58prefix) || ss58prefix < 0 || ss58prefix >> 16 !== 0) {
throw new ResponseError(
LedgerError.ConditionsOfUseNotSatisfied,
`Unexpected ss58prefix ${ss58prefix}. Needs to be a non-negative integer up to 2^16`
)
}
const bip44PathBuffer = this.serializePath(bip44Path)
const prefixBuffer = Buffer.alloc(2)
prefixBuffer.writeUInt16LE(ss58prefix)
const payload = Buffer.concat([bip44PathBuffer, prefixBuffer])
const p1 = showAddrInDevice ? P1_VALUES.SHOW_ADDRESS_IN_DEVICE : P1_VALUES.ONLY_RETRIEVE
try {
const responseBuffer = await this.transport.send(this.CLA, this.INS.GET_ADDR, p1, 0, payload)
const response = processResponse(responseBuffer)
const pubKey = response.readBytes(32).toString('hex')
const address = response.readBytes(response.length()).toString('ascii')
return {
pubKey,
address,
} as GenericeResponseAddress
} catch (e) {
throw processErrorResponse(e)
}
}
private splitBufferToChunks(message: Buffer, chunkSize: number) {
const chunks = []
const buffer = Buffer.from(message)
for (let i = 0; i < buffer.length; i += chunkSize) {
let end = i + chunkSize
if (i > buffer.length) {
end = buffer.length
}
chunks.push(buffer.subarray(i, end))
}
return chunks
}
private getSignReqChunks(path: BIP32Path, txBlob: TransactionBlob, metadata?: TransactionMetadataBlob) {
const chunks: Buffer[] = []
const bip44Path = this.serializePath(path)
const blobLen = Buffer.alloc(2)
blobLen.writeUInt16LE(txBlob.length)
chunks.push(Buffer.concat([bip44Path, blobLen]))
if (metadata == null) {
chunks.push(...this.splitBufferToChunks(txBlob, this.CHUNK_SIZE))
} else {
chunks.push(...this.splitBufferToChunks(Buffer.concat([txBlob, metadata]), this.CHUNK_SIZE))
}
return chunks
}
/**
* Signs a transaction blob.
* @param path - The BIP44 path.
* @param ins - The instruction for signing.
* @param blob - The transaction blob.
* @param metadata - The optional metadata.
* @throws {ResponseError} If the response from the device indicates an error.
* @returns The response containing the signature and status.
*/
private async signImpl(
path: BIP32Path,
ins: number,
blob: TransactionBlob,
metadata?: TransactionMetadataBlob
): Promise<GenericResponseSign> {
const chunks = this.getSignReqChunks(path, blob, metadata)
try {
let result = await this.signSendChunk(ins, 1, chunks.length, chunks[0])
for (let i = 1; i < chunks.length; i += 1) {
result = await this.signSendChunk(ins, 1 + i, chunks.length, chunks[i])
}
return {
signature: result.readBytes(result.length()),
}
} catch (e) {
throw processErrorResponse(e)
}
}
/**
* Signs a transaction blob retrieving the correct metadata from a metadata service.
* @param path - The BIP44 path.
* @param txBlob - The transaction blob.
* @throws {ResponseError} If the response from the device indicates an error.
* @returns The response containing the signature and status.
*/
async sign(path: BIP32Path, txBlob: TransactionBlob) {
if (!this.txMetadataSrvUrl) {
throw new ResponseError(
LedgerError.GenericError,
'txMetadataSrvUrl is not defined or is empty. The use of the method requires access to a metadata shortening service.'
)
}
if (!this.txMetadataChainId) {
throw new ResponseError(
LedgerError.GenericError,
'txMetadataChainId is not defined or is empty. These values are configured in the metadata shortening service. Check the corresponding configuration in the service.'
)
}
const txMetadata = await this.getTxMetadata(txBlob)
return await this.signImpl(path, this.INS.SIGN, txBlob, txMetadata)
}
/**
* Signs a transaction blob with provided metadata.
* @param path - The BIP44 path.
* @param txBlob - The transaction blob.
* @param txMetadataChainId - The optional chain ID for the transaction metadata service. This value temporarily overrides the one set in the constructor.
* @param txMetadataSrvUrl - The optional URL for the transaction metadata service. This value temporarily overrides the one set in the constructor.
* @throws {ResponseError} If the response from the device indicates an error.
* @returns The response containing the signature and status.
*/
async signMigration(path: BIP32Path, txBlob: TransactionBlob, txMetadataChainId?: string, txMetadataSrvUrl?: string) {
if (!this.txMetadataSrvUrl) {
throw new ResponseError(
LedgerError.GenericError,
'txMetadataSrvUrl is not defined or is empty. The use of the method requires access to a metadata shortening service.'
)
}
if (!this.txMetadataChainId) {
throw new ResponseError(
LedgerError.GenericError,
'txMetadataChainId is not defined or is empty. These values are configured in the metadata shortening service. Check the corresponding configuration in the service.'
)
}
const txMetadata = await this.getTxMetadata(txBlob, txMetadataChainId, txMetadataSrvUrl)
return await this.signImpl(path, this.INS.SIGN, txBlob, txMetadata)
}
/**
* Signs a raw transaction blob.
* @param path - The BIP44 path.
* @param txBlob - The transaction blob.
* @throws {ResponseError} If the response from the device indicates an error.
* @returns The response containing the signature and status.
*/
async signRaw(path: BIP32Path, txBlob: TransactionBlob) {
return await this.signImpl(path, this.INS.SIGN_RAW, txBlob)
}
/**
* [Expert-only Method] Signs a transaction blob with provided metadata (this could be used also with a migration app)
* @param path - The BIP44 path.
* @param txBlob - The transaction blob.
* @param txMetadata - The transaction metadata.
* @throws {ResponseError} If the response from the device indicates an error.
* @returns The response containing the signature and status.
*/
async signWithMetadata(path: BIP32Path, txBlob: TransactionBlob, txMetadata: TransactionMetadataBlob) {
return await this.signImpl(path, this.INS.SIGN, txBlob, txMetadata)
}
}