2021-02-04 19:15:23 +01:00
|
|
|
import log from 'loglevel';
|
|
|
|
import Wallet from 'ethereumjs-wallet';
|
|
|
|
import importers from 'ethereumjs-wallet/thirdparty';
|
2022-09-22 17:04:24 +02:00
|
|
|
import { toBuffer, isValidPrivate, bufferToHex } from 'ethereumjs-util';
|
2021-02-04 19:15:23 +01:00
|
|
|
import { addHexPrefix } from '../lib/util';
|
2022-09-22 17:04:24 +02:00
|
|
|
import { stripHexPrefix } from '../../../shared/modules/hexstring-utils';
|
2017-01-19 00:17:08 +01:00
|
|
|
|
|
|
|
const accountImporter = {
|
2023-01-20 21:20:18 +01:00
|
|
|
async importAccount(strategy, args) {
|
|
|
|
const importer = this.strategies[strategy];
|
|
|
|
const privateKeyHex = importer(...args);
|
|
|
|
return privateKeyHex;
|
2017-01-19 00:17:08 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
strategies: {
|
|
|
|
'Private Key': (privateKey) => {
|
2018-06-05 22:44:03 +02:00
|
|
|
if (!privateKey) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error('Cannot import an empty key.');
|
2018-06-05 22:44:03 +02:00
|
|
|
}
|
2018-06-11 23:58:05 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const prefixed = addHexPrefix(privateKey);
|
2021-04-16 17:05:13 +02:00
|
|
|
const buffer = toBuffer(prefixed);
|
2018-06-11 23:58:05 +02:00
|
|
|
|
2021-04-16 17:05:13 +02:00
|
|
|
if (!isValidPrivate(buffer)) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error('Cannot import invalid private key.');
|
2018-06-11 23:58:05 +02:00
|
|
|
}
|
|
|
|
|
2021-04-16 17:05:13 +02:00
|
|
|
const stripped = stripHexPrefix(prefixed);
|
2021-02-04 19:15:23 +01:00
|
|
|
return stripped;
|
2017-01-19 00:17:08 +01:00
|
|
|
},
|
|
|
|
'JSON File': (input, password) => {
|
2021-02-04 19:15:23 +01:00
|
|
|
let wallet;
|
2017-01-19 01:45:39 +01:00
|
|
|
try {
|
2021-02-04 19:15:23 +01:00
|
|
|
wallet = importers.fromEtherWallet(input, password);
|
2017-01-19 01:45:39 +01:00
|
|
|
} catch (e) {
|
2021-02-04 19:15:23 +01:00
|
|
|
log.debug('Attempt to import as EtherWallet format failed, trying V3');
|
|
|
|
wallet = Wallet.fromV3(input, password, true);
|
2017-01-19 01:45:39 +01:00
|
|
|
}
|
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
return walletToPrivateKey(wallet);
|
2017-01-19 00:17:08 +01:00
|
|
|
},
|
|
|
|
},
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2017-01-19 00:17:08 +01:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
function walletToPrivateKey(wallet) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const privateKeyBuffer = wallet.getPrivateKey();
|
2021-04-16 17:05:13 +02:00
|
|
|
return bufferToHex(privateKeyBuffer);
|
2017-01-19 00:17:08 +01:00
|
|
|
}
|
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
export default accountImporter;
|