-
Notifications
You must be signed in to change notification settings - Fork 771
/
mnemonicWallet.js
260 lines (221 loc) · 7.69 KB
/
mnemonicWallet.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
import EthereumjsTx from 'ethereumjs-tx'
import * as ethUtil from 'ethereumjs-util'
import * as HDKey from 'hdkey'
import HardwareWalletInterface from './hardwareWallet-interface'
import { getDerivationPath, paths } from './deterministicWalletPaths'
import * as bip39 from 'bip39'
let phrase = ''
let pass = ''
export default class MnemonicWallet extends HardwareWalletInterface {
constructor (options) {
super()
this.identifier = 'Mnemonic'
this.wallet = null
options = options || {}
this.addressToWalletMap = {}
this.addressesToIndexMap = {}
this.walletsRetrieved = []
this.id = 0
this.hdk = null
this.numWallets = 0
this.defaultOptions = {
path: this.getDerivationPath().dpath
}
const currentOptions = {
...this.defaultOptions,
...options
}
this.path = currentOptions.path
this.accountsLength = currentOptions.accountsLength || this.defaultAccountsCount
this.accountsOffset = currentOptions.accountsOffset || this.defaultAccountsOffset
this.networkId = currentOptions.networkId || this.defaultNetworkId
this.getAccounts = this.getAccounts.bind(this)
this.getMultipleAccounts = this.getMultipleAccounts.bind(this)
this.signTransaction = this.signTransaction.bind(this)
this.signMessage = this.signMessage.bind(this)
if (options) {
this.decryptWallet(options)
}
}
// ============== (Start) Expected Utility methods ======================
setActiveAddress (address, index) {
this.wallet = this.addressToWalletMap[address]
this.wallet.address = address
}
static async unlock (options) {
try {
return new MnemonicWallet(options)
} catch (e) {
console.error(e) // todo replace with proper error
return e
}
}
get compatibleChains () {
return paths
}
getDerivationPath (networkShortName) {
return getDerivationPath(networkShortName)
}
// ============== (End) Expected Utility methods ======================
// ============== (Start) Implementation of required EthereumJs-wallet interface methods =========
getAddress () {
if (this.wallet) {
return this.wallet.address
} else {
return null
}
}
getAddressString () {
if (this.wallet) {
return ethUtil.toChecksumAddress(this.getAddress())
} else {
return null
}
}
// ============== (End) Implementation of required EthereumJs-wallet interface methods ===========
// ============== (Start) Implementation of wallet usage methods ======================
getAccounts () {
let _this = this
if (arguments.length > 1 && typeof arguments[2] === 'function') {
return _this.getMultipleAccounts(arguments[0], arguments[1])
} else {
return _this._getAccounts()
}
}
getMultipleAccounts (count, offset) {
// if the particular wallet does not support multiple accounts this should just return the primary account
return this._getAccounts(count, offset)
}
signTransaction (txData) {
return this.signTxMnemonic(txData)
}
signMessage (msgData) {
let thisMessage = msgData.data ? msgData.data : msgData
return this.signMessageMnemonic(thisMessage)
}
// ============== (End) Implementation of wallet usage methods ======================
async changeDerivationPath (path) {
this.path = path
await this.decryptWallet({mnemonicPhrase: phrase, mnemonicPassword: pass})
}
// ============== (Start) Internally used methods ======================
set phrase (mnemonicPhrase) {
phrase = mnemonicPhrase
}
set password (mnemonicPassword) {
pass = mnemonicPassword
}
// (Start) Internal setup methods
decryptWallet (options) {
try {
if (!bip39.validateMnemonic(options.mnemonicPhrase)) throw new Error('Invalid Mnemonic Supplied')
this.phrase = options.mnemonicPhrase
this.password = options.mnemonicPassword
this.hdk = HDKey.fromMasterSeed(bip39.mnemonicToSeed(options.mnemonicPhrase.trim(), options.mnemonicPassword))
this.setHDAddresses()
} catch (e) {
throw e
}
};
createWallet (priv, pub, path, hwType, hwTransport) {
let wallet = {}
if (typeof priv !== 'undefined') {
wallet.privKey = priv.length === 32 ? priv : Buffer.from(priv, 'hex')
}
wallet.pubKey = pub
wallet.path = path
wallet.hwType = this.identifier
wallet.hwTransport = hwTransport
wallet.type = this.brand
return wallet
}
// (End) Internal setup methods
AddRemoveHDAddresses (isAdd) {
if (isAdd) this.setHDAddressesHWWallet(this.numWallets, this.accountsLength)
else this.setHDAddressesHWWallet(this.numWallets - 2 * this.accountsLength, this.accountsLength)
}
setHDWallet () {
this.wallet = this.walletsRetrieved[this.id]
this.wallet.type = 'default'
}
// (Start) Internal methods underlying wallet usage methods
async _getAccounts (count, offset) {
return new Promise((resolve, reject) => {
let collect = {}
if (this.addressesToIndexMap[offset] && this.addressesToIndexMap[offset + count - 1]) {
for (let i = offset; i < offset + count; i++) {
collect[i] = this.addressesToIndexMap[i]
}
} else {
this.setHDAddresses(offset, count)
for (let i = offset; i < offset + count; i++) {
collect[i] = this.addressesToIndexMap[i]
}
}
resolve(collect)
})
}
setHDAddresses (start = 0, limit = 5) { // TODO: Move to a worker thread
this.walletsRetrieved = []
for (let i = start; i < start + limit; i++) {
const tempWallet = this.createWallet(this.hdk.derive(this.path + '/' + i)._privateKey)
this.addressToWalletMap[this._getAddressForWallet(tempWallet)] = tempWallet
this.walletsRetrieved.push(tempWallet)
this.addressesToIndexMap[i] = this._getAddressForWallet(tempWallet)
this.walletsRetrieved[this.walletsRetrieved.length - 1].type = 'addressOnly'
}
this.id = 0
this.numWallets = start + limit
}
async signTxMnemonic (rawTx) {
try {
if (!this.wallet) throw new Error('no wallet present. wallet not have been decrypted')
const txData = {
nonce: rawTx.nonce,
gasPrice: rawTx.gasprice,
gas: rawTx.gas,
to: rawTx.to,
value: rawTx.value,
data: rawTx.data,
chainId: rawTx.chainId
}
txData.data = txData.data === '' ? '0x' : txData.data
let tx = new EthereumjsTx(txData)
tx.sign(Buffer.from(this.wallet.privKey, 'hex'))
txData.rawTx = JSON.stringify(txData)
return {
rawTx: txData,
messageHash: tx.hash(), // figure out what exactly web3 is putting here
v: tx.v,
r: tx.r,
s: tx.s,
rawTransaction: `0x${tx.serialize().toString('hex')}`
}
} catch (e) {
return e
}
}
async signMessageMnemonic (stringMessage) {
try {
if (!this.wallet) throw new Error('no wallet present. wallet may not have been decrypted')
let msg = ethUtil.hashPersonalMessage(ethUtil.toBuffer(stringMessage))
let signed = ethUtil.ecsign(msg, this.wallet.privKey)
let combined = Buffer.concat([Buffer.from(signed.r), Buffer.from(signed.s), Buffer.from([signed.v])])
let combinedHex = combined.toString('hex')
return '0x' + combinedHex
} catch (e) {
return e
}
}
// (End) Internal methods underlying wallet usage methods
// (Start) Internal utility methods
_getAddressForWallet (wallet) {
if (typeof wallet.pubKey === 'undefined') {
return '0x' + ethUtil.privateToAddress(wallet.privKey).toString('hex')
} else {
return '0x' + ethUtil.publicToAddress(wallet.pubKey, true).toString('hex')
}
}
// (End) Internal utility methods
// ============== (End) Internally used methods ======================
}