metamask-extension/app/scripts/account-import-strategies/index.js
这部分就是用户如果往metamask中import一个已有的账户调用的接口,就是是直接输入私钥privateKey还是使用json file
即如下图:
const Wallet = require('ethereumjs-wallet') const importers = require('ethereumjs-wallet/thirdparty') const ethUtil = require('ethereumjs-util') const accountImporter = { importAccount (strategy, args) { try { const importer = this.strategies[strategy]//确认使用的是那种import的方法 const privateKeyHex = importer.apply(null, args) //args就是输入的值,如privateKey或者input, password 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 = ethUtil.addHexPrefix(privateKey)//加入0x前缀 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) { console.log('Attempt to import as EtherWallet format failed, trying V3...') } if (!wallet) { wallet = Wallet.fromV3(input, password, true) } return walletToPrivateKey(wallet) }, }, } function walletToPrivateKey (wallet) { const privateKeyBuffer = wallet.getPrivateKey() return ethUtil.bufferToHex(privateKeyBuffer) } module.exports = accountImporter
ethereumjs-wallet
fromV1(input, password)
- import a wallet (Version 1 of the Ethereum wallet format)fromV3(input, password, [nonStrict])
- import a wallet (Version 3 of the Ethereum wallet format). SetnonStrict
true to accept files with mixed-caps.
var thirdparty = require('ethereumjs-wallet/thirdparty')
fromEtherWallet(input, password)
- import a wallet generated by EtherWallet