1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/app/scripts/account-import-strategies/index.js

59 lines
1.4 KiB
JavaScript
Raw Normal View History

import log from 'loglevel';
import Wallet from 'ethereumjs-wallet';
import importers from 'ethereumjs-wallet/thirdparty';
2021-04-16 17:05:13 +02:00
import {
toBuffer,
isValidPrivate,
bufferToHex,
stripHexPrefix,
} from 'ethereumjs-util';
import { addHexPrefix } from '../lib/util';
const accountImporter = {
2020-11-03 00:41:28 +01:00
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);
2021-04-16 17:05:13 +02:00
const buffer = toBuffer(prefixed);
2021-04-16 17:05:13 +02:00
if (!isValidPrivate(buffer)) {
throw new Error('Cannot import invalid private key.');
}
2021-04-16 17:05:13 +02:00
const stripped = 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);
},
},
};
2020-11-03 00:41:28 +01:00
function walletToPrivateKey(wallet) {
const privateKeyBuffer = wallet.getPrivateKey();
2021-04-16 17:05:13 +02:00
return bufferToHex(privateKeyBuffer);
}
export default accountImporter;