1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 03:36:18 +02:00
metamask-extension/app/scripts/account-import-strategies/index.js
Patryk Łucka ee205b893f
Create custom addHexPrefix function (#9306)
* create custom addHexPrefix function

* switch to custom addHexPrefix

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
Co-authored-by: Erik Marks <rekmarks@protonmail.com>
2020-11-06 13:18:00 -08:00

54 lines
1.4 KiB
JavaScript

import log from 'loglevel'
import Wallet from 'ethereumjs-wallet'
import importers from 'ethereumjs-wallet/thirdparty'
import ethUtil from 'ethereumjs-util'
import { addHexPrefix } from '../lib/util'
const accountImporter = {
importAccount(strategy, args) {
try {
const importer = this.strategies[strategy]
const privateKeyHex = importer(...args)
return Promise.resolve(privateKeyHex)
} catch (e) {
return Promise.reject(e)
}
},
strategies: {
'Private Key': (privateKey) => {
if (!privateKey) {
throw new Error('Cannot import an empty key.')
}
const prefixed = addHexPrefix(privateKey)
const buffer = ethUtil.toBuffer(prefixed)
if (!ethUtil.isValidPrivate(buffer)) {
throw new Error('Cannot import invalid private key.')
}
const stripped = ethUtil.stripHexPrefix(prefixed)
return stripped
},
'JSON File': (input, password) => {
let wallet
try {
wallet = importers.fromEtherWallet(input, password)
} catch (e) {
log.debug('Attempt to import as EtherWallet format failed, trying V3')
wallet = Wallet.fromV3(input, password, true)
}
return walletToPrivateKey(wallet)
},
},
}
function walletToPrivateKey(wallet) {
const privateKeyBuffer = wallet.getPrivateKey()
return ethUtil.bufferToHex(privateKeyBuffer)
}
export default accountImporter