2020-01-18 00:29:47 +01:00
|
|
|
import log from 'loglevel'
|
2020-01-09 04:34:58 +01:00
|
|
|
import Wallet from 'ethereumjs-wallet'
|
|
|
|
import importers from 'ethereumjs-wallet/thirdparty'
|
|
|
|
import ethUtil from 'ethereumjs-util'
|
2017-01-19 00:17:08 +01:00
|
|
|
|
|
|
|
const accountImporter = {
|
|
|
|
|
2017-04-27 06:05:45 +02:00
|
|
|
importAccount (strategy, args) {
|
2017-01-19 00:17:08 +01:00
|
|
|
try {
|
|
|
|
const importer = this.strategies[strategy]
|
2017-01-19 01:45:39 +01:00
|
|
|
const privateKeyHex = importer.apply(null, args)
|
2017-01-19 00:17:08 +01:00
|
|
|
return Promise.resolve(privateKeyHex)
|
|
|
|
} catch (e) {
|
|
|
|
return Promise.reject(e)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
strategies: {
|
|
|
|
'Private Key': (privateKey) => {
|
2018-06-05 22:44:03 +02:00
|
|
|
if (!privateKey) {
|
|
|
|
throw new Error('Cannot import an empty key.')
|
|
|
|
}
|
2018-06-11 23:58:05 +02:00
|
|
|
|
2018-06-14 06:06:33 +02:00
|
|
|
const prefixed = ethUtil.addHexPrefix(privateKey)
|
|
|
|
const buffer = ethUtil.toBuffer(prefixed)
|
2018-06-11 23:58:05 +02:00
|
|
|
|
|
|
|
if (!ethUtil.isValidPrivate(buffer)) {
|
|
|
|
throw new Error('Cannot import invalid private key.')
|
|
|
|
}
|
|
|
|
|
2018-06-14 06:06:33 +02:00
|
|
|
const stripped = ethUtil.stripHexPrefix(prefixed)
|
2017-01-19 01:45:39 +01:00
|
|
|
return stripped
|
2017-01-19 00:17:08 +01:00
|
|
|
},
|
|
|
|
'JSON File': (input, password) => {
|
2017-01-19 01:45:39 +01:00
|
|
|
let wallet
|
|
|
|
try {
|
|
|
|
wallet = importers.fromEtherWallet(input, password)
|
|
|
|
} catch (e) {
|
2020-01-18 00:29:47 +01:00
|
|
|
log.debug('Attempt to import as EtherWallet format failed, trying V3')
|
2017-01-19 01:45:39 +01:00
|
|
|
wallet = Wallet.fromV3(input, password, true)
|
|
|
|
}
|
|
|
|
|
2017-01-19 00:17:08 +01:00
|
|
|
return walletToPrivateKey(wallet)
|
|
|
|
},
|
|
|
|
},
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
function walletToPrivateKey (wallet) {
|
|
|
|
const privateKeyBuffer = wallet.getPrivateKey()
|
|
|
|
return ethUtil.bufferToHex(privateKeyBuffer)
|
|
|
|
}
|
|
|
|
|
2020-01-09 04:34:58 +01:00
|
|
|
export default accountImporter
|