This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 328
/
hooked-wallet.js
474 lines (413 loc) · 15.4 KB
/
hooked-wallet.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*
* Emulate 'eth_accounts' / 'eth_sendTransaction' using 'eth_sendRawTransaction'
*
* The two callbacks a user needs to implement are:
* - getAccounts() -- array of addresses supported
* - signTransaction(tx) -- sign a raw transaction object
*/
const waterfall = require('async/waterfall')
const parallel = require('async/parallel')
const inherits = require('util').inherits
const ethUtil = require('ethereumjs-util')
const sigUtil = require('eth-sig-util')
const extend = require('xtend')
const Semaphore = require('semaphore')
const Subprovider = require('./subprovider.js')
const estimateGas = require('../util/estimate-gas.js')
const hexRegex = /^[0-9A-Fa-f]+$/g
module.exports = HookedWalletSubprovider
// handles the following RPC methods:
// eth_coinbase
// eth_accounts
// eth_sendTransaction
// eth_sign
// personal_sign
// personal_ecRecover
//
// Tx Signature Flow
//
// handleRequest: eth_sendTransaction
// validateTransaction (basic validity check)
// validateSender (checks that sender is in accounts)
// processTransaction (sign tx and submit to network)
// approveTransaction (UI approval hook)
// checkApproval
// finalizeAndSubmitTx (tx signing)
// nonceLock.take (bottle neck to ensure atomic nonce)
// fillInTxExtras (set fallback gasPrice, nonce, etc)
// signTransaction (perform the signature)
// publishTransaction (publish signed tx to network)
//
inherits(HookedWalletSubprovider, Subprovider)
function HookedWalletSubprovider(opts){
const self = this
// control flow
self.nonceLock = Semaphore(1)
// data lookup
if (!opts.getAccounts) throw new Error('ProviderEngine - HookedWalletSubprovider - did not provide "getAccounts" fn in constructor options')
self.getAccounts = opts.getAccounts
// high level override
if (opts.processTransaction) self.processTransaction = opts.processTransaction
if (opts.processMessage) self.processMessage = opts.processMessage
if (opts.processPersonalMessage) self.processPersonalMessage = opts.processPersonalMessage
if (opts.processTypedMessage) self.processTypedMessage = opts.processTypedMessage
// approval hooks
self.approveTransaction = opts.approveTransaction || self.autoApprove
self.approveMessage = opts.approveMessage || self.autoApprove
self.approvePersonalMessage = opts.approvePersonalMessage || self.autoApprove
self.approveTypedMessage = opts.approveTypedMessage || self.autoApprove
// actually perform the signature
if (opts.signTransaction) self.signTransaction = opts.signTransaction
if (opts.signMessage) self.signMessage = opts.signMessage
if (opts.signPersonalMessage) self.signPersonalMessage = opts.signPersonalMessage
if (opts.signTypedMessage) self.signTypedMessage = opts.signTypedMessage
if (opts.recoverPersonalSignature) self.recoverPersonalSignature = opts.recoverPersonalSignature
// publish to network
if (opts.publishTransaction) self.publishTransaction = opts.publishTransaction
}
HookedWalletSubprovider.prototype.handleRequest = function(payload, next, end){
const self = this
switch(payload.method) {
case 'eth_coinbase':
self.getAccounts(function(err, accounts){
if (err) return end(err)
var result = accounts[0] || null
end(null, result)
})
return
case 'eth_accounts':
self.getAccounts(function(err, accounts){
if (err) return end(err)
end(null, accounts)
})
return
case 'eth_sendTransaction':
var txParams = payload.params[0]
waterfall([
(cb) => self.validateTransaction(txParams, cb),
(cb) => self.processTransaction(txParams, cb),
], end)
return
case 'eth_signTransaction':
var txParams = payload.params[0]
waterfall([
(cb) => self.validateTransaction(txParams, cb),
(cb) => self.processSignTransaction(txParams, cb),
], end)
return
case 'eth_sign':
var address = payload.params[0]
var message = payload.params[1]
// non-standard "extraParams" to be appended to our "msgParams" obj
// good place for metadata
var extraParams = payload.params[2] || {}
var msgParams = extend(extraParams, {
from: address,
data: message,
})
waterfall([
(cb) => self.validateMessage(msgParams, cb),
(cb) => self.processMessage(msgParams, cb),
], end)
return
case 'personal_sign':
const first = payload.params[0]
const second = payload.params[1]
var message, address
// We initially incorrectly ordered these parameters.
// To gracefully respect users who adopted this API early,
// we are currently gracefully recovering from the wrong param order
// when it is clearly identifiable.
//
// That means when the first param is definitely an address,
// and the second param is definitely not, but is hex.
if (resemblesData(second) && resemblesAddress(first)) {
let warning = `The eth_personalSign method requires params ordered `
warning += `[message, address]. This was previously handled incorrectly, `
warning += `and has been corrected automatically. `
warning += `Please switch this param order for smooth behavior in the future.`
console.warn(warning)
address = payload.params[0]
message = payload.params[1]
} else {
message = payload.params[0]
address = payload.params[1]
}
// non-standard "extraParams" to be appended to our "msgParams" obj
// good place for metadata
var extraParams = payload.params[2] || {}
var msgParams = extend(extraParams, {
from: address,
data: message,
})
waterfall([
(cb) => self.validatePersonalMessage(msgParams, cb),
(cb) => self.processPersonalMessage(msgParams, cb),
], end)
return
case 'personal_ecRecover':
var message = payload.params[0]
var signature = payload.params[1]
// non-standard "extraParams" to be appended to our "msgParams" obj
// good place for metadata
var extraParams = payload.params[2] || {}
var msgParams = extend(extraParams, {
sig: signature,
data: message,
})
self.recoverPersonalSignature(msgParams, end)
return
case 'eth_signTypedData':
message = payload.params[0]
address = payload.params[1]
var extraParams = payload.params[2] || {}
var msgParams = extend(extraParams, {
from: address,
data: message,
})
waterfall([
(cb) => self.validateTypedMessage(msgParams, cb),
(cb) => self.processTypedMessage(msgParams, cb),
], end)
return
default:
next()
return
}
}
//
// "process" high level flow
//
HookedWalletSubprovider.prototype.processTransaction = function(txParams, cb) {
const self = this
waterfall([
(cb) => self.approveTransaction(txParams, cb),
(didApprove, cb) => self.checkApproval('transaction', didApprove, cb),
(cb) => self.finalizeAndSubmitTx(txParams, cb),
], cb)
}
HookedWalletSubprovider.prototype.processSignTransaction = function(txParams, cb) {
const self = this
waterfall([
(cb) => self.approveTransaction(txParams, cb),
(didApprove, cb) => self.checkApproval('transaction', didApprove, cb),
(cb) => self.finalizeTx(txParams, cb),
], cb)
}
HookedWalletSubprovider.prototype.processMessage = function(msgParams, cb) {
const self = this
waterfall([
(cb) => self.approveMessage(msgParams, cb),
(didApprove, cb) => self.checkApproval('message', didApprove, cb),
(cb) => self.signMessage(msgParams, cb),
], cb)
}
HookedWalletSubprovider.prototype.processPersonalMessage = function(msgParams, cb) {
const self = this
waterfall([
(cb) => self.approvePersonalMessage(msgParams, cb),
(didApprove, cb) => self.checkApproval('message', didApprove, cb),
(cb) => self.signPersonalMessage(msgParams, cb),
], cb)
}
HookedWalletSubprovider.prototype.processTypedMessage = function(msgParams, cb) {
const self = this
waterfall([
(cb) => self.approveTypedMessage(msgParams, cb),
(didApprove, cb) => self.checkApproval('message', didApprove, cb),
(cb) => self.signTypedMessage(msgParams, cb),
], cb)
}
//
// approval
//
HookedWalletSubprovider.prototype.autoApprove = function(txParams, cb) {
cb(null, true)
}
HookedWalletSubprovider.prototype.checkApproval = function(type, didApprove, cb) {
cb( didApprove ? null : new Error('User denied '+type+' signature.') )
}
//
// signature and recovery
//
HookedWalletSubprovider.prototype.signTransaction = function(tx, cb) {
cb(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "signTransaction" fn in constructor options'))
}
HookedWalletSubprovider.prototype.signMessage = function(msgParams, cb) {
cb(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "signMessage" fn in constructor options'))
}
HookedWalletSubprovider.prototype.signPersonalMessage = function(msgParams, cb) {
cb(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "signPersonalMessage" fn in constructor options'))
}
HookedWalletSubprovider.prototype.signTypedMessage = function(msgParams, cb) {
cb(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "signTypedMessage" fn in constructor options'))
}
HookedWalletSubprovider.prototype.recoverPersonalSignature = function(msgParams, cb) {
let senderHex
try {
senderHex = sigUtil.recoverPersonalSignature(msgParams)
} catch (err) {
return cb(err)
}
cb(null, senderHex)
}
//
// validation
//
HookedWalletSubprovider.prototype.validateTransaction = function(txParams, cb){
const self = this
// shortcut: undefined sender is invalid
if (txParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign transaction.`))
self.validateSender(txParams.from, function(err, senderIsValid){
if (err) return cb(err)
if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign transaction for this address: "${txParams.from}"`))
cb()
})
}
HookedWalletSubprovider.prototype.validateMessage = function(msgParams, cb){
const self = this
if (msgParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign message.`))
self.validateSender(msgParams.from, function(err, senderIsValid){
if (err) return cb(err)
if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`))
cb()
})
}
HookedWalletSubprovider.prototype.validatePersonalMessage = function(msgParams, cb){
const self = this
if (msgParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign personal message.`))
if (msgParams.data === undefined) return cb(new Error(`Undefined message - message required to sign personal message.`))
if (!isValidHex(msgParams.data)) return cb(new Error(`HookedWalletSubprovider - validateMessage - message was not encoded as hex.`))
self.validateSender(msgParams.from, function(err, senderIsValid){
if (err) return cb(err)
if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`))
cb()
})
}
HookedWalletSubprovider.prototype.validateTypedMessage = function(msgParams, cb){
if (msgParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign typed data.`))
if (msgParams.data === undefined) return cb(new Error(`Undefined data - message required to sign typed data.`))
this.validateSender(msgParams.from, function(err, senderIsValid){
if (err) return cb(err)
if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`))
cb()
})
}
HookedWalletSubprovider.prototype.validateSender = function(senderAddress, cb){
const self = this
// shortcut: undefined sender is invalid
if (!senderAddress) return cb(null, false)
self.getAccounts(function(err, accounts){
if (err) return cb(err)
var senderIsValid = (accounts.map(toLowerCase).indexOf(senderAddress.toLowerCase()) !== -1)
cb(null, senderIsValid)
})
}
//
// tx helpers
//
HookedWalletSubprovider.prototype.finalizeAndSubmitTx = function(txParams, cb) {
const self = this
// can only allow one tx to pass through this flow at a time
// so we can atomically consume a nonce
self.nonceLock.take(function(){
waterfall([
self.fillInTxExtras.bind(self, txParams),
self.signTransaction.bind(self),
self.publishTransaction.bind(self),
], function(err, txHash){
self.nonceLock.leave()
if (err) return cb(err)
cb(null, txHash)
})
})
}
HookedWalletSubprovider.prototype.finalizeTx = function(txParams, cb) {
const self = this
// can only allow one tx to pass through this flow at a time
// so we can atomically consume a nonce
self.nonceLock.take(function(){
waterfall([
self.fillInTxExtras.bind(self, txParams),
self.signTransaction.bind(self),
], function(err, signedTx){
self.nonceLock.leave()
if (err) return cb(err)
cb(null, {raw: signedTx, tx: txParams})
})
})
}
HookedWalletSubprovider.prototype.publishTransaction = function(rawTx, cb) {
const self = this
self.emitPayload({
method: 'eth_sendRawTransaction',
params: [rawTx],
}, function(err, res){
if (err) return cb(err)
cb(null, res.result)
})
}
HookedWalletSubprovider.prototype.fillInTxExtras = function(txParams, cb){
const self = this
var address = txParams.from
// console.log('fillInTxExtras - address:', address)
var reqs = {}
if (txParams.gasPrice === undefined) {
// console.log("need to get gasprice")
reqs.gasPrice = self.emitPayload.bind(self, { method: 'eth_gasPrice', params: [] })
}
if (txParams.nonce === undefined) {
// console.log("need to get nonce")
reqs.nonce = self.emitPayload.bind(self, { method: 'eth_getTransactionCount', params: [address, 'pending'] })
}
if (txParams.gas === undefined) {
// console.log("need to get gas")
reqs.gas = estimateGas.bind(null, self.engine, cloneTxParams(txParams))
}
parallel(reqs, function(err, result) {
if (err) return cb(err)
// console.log('fillInTxExtras - result:', result)
var res = {}
if (result.gasPrice) res.gasPrice = result.gasPrice.result
if (result.nonce) res.nonce = result.nonce.result
if (result.gas) res.gas = result.gas
cb(null, extend(res, txParams))
})
}
// util
// we use this to clean any custom params from the txParams
function cloneTxParams(txParams){
return {
from: txParams.from,
to: txParams.to,
value: txParams.value,
data: txParams.data,
gas: txParams.gas,
gasPrice: txParams.gasPrice,
nonce: txParams.nonce,
}
}
function toLowerCase(string){
return string.toLowerCase()
}
function resemblesAddress (string) {
const fixed = ethUtil.addHexPrefix(string)
const isValid = ethUtil.isValidAddress(fixed)
return isValid
}
// Returns true if resembles hex data
// but definitely not a valid address.
function resemblesData (string) {
const fixed = ethUtil.addHexPrefix(string)
const isValidAddress = ethUtil.isValidAddress(fixed)
return !isValidAddress && isValidHex(string)
}
function isValidHex(data) {
const isString = typeof data === 'string'
if (!isString) return false
const isHexPrefixed = data.slice(0,2) === '0x'
if (!isHexPrefixed) return false
const nonPrefixed = data.slice(2)
const isValid = nonPrefixed.match(hexRegex)
return isValid
}