-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
295 lines (255 loc) · 8.54 KB
/
index.js
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
const { EventEmitter } = require('events')
const ethUtil = require('ethereumjs-util')
const Transaction = require('ethereumjs-tx')
const HDKey = require('hdkey')
const TrezorConnect = require('trezor-connect').default
const hdPathString = `m/44'/237'/0'/0`
const keyringType = 'Trezor Hardware'
const pathBase = 'm'
const MAX_INDEX = 1000
const DELAY_BETWEEN_POPUPS = 1000
const TREZOR_CONNECT_MANIFEST = {
email: '[email protected]',
appUrl: 'https://metamask.io',
}
class TrezorKeyring extends EventEmitter {
constructor (opts = {}) {
super()
this.type = keyringType
this.accounts = []
this.hdk = new HDKey()
this.page = 0
this.perPage = 5
this.unlockedAccount = 0
this.paths = {}
this.deserialize(opts)
TrezorConnect.manifest(TREZOR_CONNECT_MANIFEST)
}
serialize () {
return Promise.resolve({
hdPath: this.hdPath,
accounts: this.accounts,
page: this.page,
paths: this.paths,
perPage: this.perPage,
unlockedAccount: this.unlockedAccount,
})
}
deserialize (opts = {}) {
this.hdPath = opts.hdPath || hdPathString
this.accounts = opts.accounts || []
this.page = opts.page || 0
this.perPage = opts.perPage || 5
return Promise.resolve()
}
isUnlocked () {
return !!(this.hdk && this.hdk.publicKey)
}
unlock () {
if (this.isUnlocked()) return Promise.resolve('already unlocked')
return new Promise((resolve, reject) => {
TrezorConnect.getPublicKey({
path: this.hdPath,
coin: 'ETH',
}).then(response => {
if (response.success) {
this.hdk.publicKey = new Buffer(response.payload.publicKey, 'hex')
this.hdk.chainCode = new Buffer(response.payload.chainCode, 'hex')
resolve('just unlocked')
} else {
reject(new Error(response.payload && response.payload.error || 'Unknown error'))
}
}).catch(e => {
reject(new Error(e && e.toString() || 'Unknown error'))
})
})
}
setAccountToUnlock (index) {
this.unlockedAccount = parseInt(index, 10)
}
addAccounts (n = 1) {
return new Promise((resolve, reject) => {
this.unlock()
.then(_ => {
const from = this.unlockedAccount
const to = from + n
this.accounts = []
for (let i = from; i < to; i++) {
const address = this._addressFromIndex(pathBase, i)
this.accounts.push(address)
this.page = 0
}
resolve(this.accounts)
})
.catch(e => {
reject(e)
})
})
}
getFirstPage () {
this.page = 0
return this.__getPage(1)
}
getNextPage () {
return this.__getPage(1)
}
getPreviousPage () {
return this.__getPage(-1)
}
__getPage (increment) {
this.page += increment
if (this.page <= 0) { this.page = 1 }
return new Promise((resolve, reject) => {
this.unlock()
.then(_ => {
const from = (this.page - 1) * this.perPage
const to = from + this.perPage
const accounts = []
for (let i = from; i < to; i++) {
const address = this._addressFromIndex(pathBase, i)
accounts.push({
address: address,
balance: null,
index: i,
})
this.paths[ethUtil.toChecksumAddress(address)] = i
}
resolve(accounts)
})
.catch(e => {
reject(e)
})
})
}
getAccounts () {
return Promise.resolve(this.accounts.slice())
}
removeAccount (address) {
if (!this.accounts.map(a => a.toLowerCase()).includes(address.toLowerCase())) {
throw new Error(`Address ${address} not found in this keyring`)
}
this.accounts = this.accounts.filter(a => a.toLowerCase() !== address.toLowerCase())
}
// tx is an instance of the ethereumjs-transaction class.
signTransaction (address, tx) {
return new Promise((resolve, reject) => {
this.unlock()
.then(status => {
setTimeout(_ => {
TrezorConnect.ethereumSignTransaction({
path: this._pathFromAddress(address),
transaction: {
to: this._normalize(tx.to),
value: this._normalize(tx.value),
data: this._normalize(tx.data),
chainId: tx._chainId,
nonce: this._normalize(tx.nonce),
gasLimit: this._normalize(tx.gasLimit),
gasPrice: this._normalize(tx.gasPrice),
},
}).then(response => {
if (response.success) {
tx.v = response.payload.v
tx.r = response.payload.r
tx.s = response.payload.s
const signedTx = new Transaction(tx)
const addressSignedWith = ethUtil.toChecksumAddress(`0x${signedTx.from.toString('hex')}`)
const correctAddress = ethUtil.toChecksumAddress(address)
if (addressSignedWith !== correctAddress) {
reject(new Error('signature doesnt match the right address'))
}
resolve(signedTx)
} else {
reject(new Error(response.payload && response.payload.error || 'Unknown error'))
}
}).catch(e => {
reject(new Error(e && e.toString() || 'Unknown error'))
})
// This is necessary to avoid popup collision
// between the unlock & sign trezor popups
}, status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0)
}).catch(e => {
reject(new Error(e && e.toString() || 'Unknown error'))
})
})
}
signMessage (withAccount, data) {
return this.signPersonalMessage(withAccount, data)
}
// For personal_sign, we need to prefix the message:
signPersonalMessage (withAccount, message) {
return new Promise((resolve, reject) => {
this.unlock()
.then(status => {
setTimeout(_ => {
TrezorConnect.ethereumSignMessage({
path: this._pathFromAddress(withAccount),
message: ethUtil.stripHexPrefix(message),
hex: true,
}).then(response => {
if (response.success) {
if (response.payload.address !== ethUtil.toChecksumAddress(withAccount)) {
reject(new Error('signature doesnt match the right address'))
}
const signature = `0x${response.payload.signature}`
resolve(signature)
} else {
reject(new Error(response.payload && response.payload.error || 'Unknown error'))
}
}).catch(e => {
console.log('Error while trying to sign a message ', e)
reject(new Error(e && e.toString() || 'Unknown error'))
})
// This is necessary to avoid popup collision
// between the unlock & sign trezor popups
}, status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0)
}).catch(e => {
console.log('Error while trying to sign a message ', e)
reject(new Error(e && e.toString() || 'Unknown error'))
})
})
}
signTypedData (withAccount, typedData) {
// Waiting on trezor to enable this
return Promise.reject(new Error('Not supported on this device'))
}
exportAccount (address) {
return Promise.reject(new Error('Not supported on this device'))
}
forgetDevice () {
this.accounts = []
this.hdk = new HDKey()
this.page = 0
this.unlockedAccount = 0
this.paths = {}
}
/* PRIVATE METHODS */
_normalize (buf) {
return ethUtil.bufferToHex(buf).toString()
}
_addressFromIndex (pathBase, i) {
const dkey = this.hdk.derive(`${pathBase}/${i}`)
const address = ethUtil
.publicToAddress(dkey.publicKey, true)
.toString('hex')
return ethUtil.toChecksumAddress(address)
}
_pathFromAddress (address) {
const checksummedAddress = ethUtil.toChecksumAddress(address)
let index = this.paths[checksummedAddress]
if (typeof index === 'undefined') {
for (let i = 0; i < MAX_INDEX; i++) {
if (checksummedAddress === this._addressFromIndex(pathBase, i)) {
index = i
break
}
}
}
if (typeof index === 'undefined') {
throw new Error('Unknown address')
}
return `${this.hdPath}/${index}`
}
}
TrezorKeyring.type = keyringType
module.exports = TrezorKeyring