aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/account-import-strategies/index.js
blob: 8f4456cdf431f7daeeb72085f3838ee5ff1862eb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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]
      const wallet = importer.apply(null, args)
      const privateKeyHex = walletToPrivateKey(wallet)
      return Promise.resolve(privateKeyHex)
    } catch (e) {
      return Promise.reject(e)
    }
  },

  strategies: {
    'Private Key': (privateKey) => {
      const stripped = ethUtil.stripHexPrefix(privateKey)
      const buffer = new Buffer(stripped, 'hex')
      return Wallet.fromPrivateKey(buffer)
    },
    'JSON File': (input, password) => {
      const wallet = importers.fromEtherWallet(input, password)
      return walletToPrivateKey(wallet)
    },
  },

}

function walletToPrivateKey (wallet) {
  const privateKeyBuffer = wallet.getPrivateKey()
  return ethUtil.bufferToHex(privateKeyBuffer)
}

module.exports = accountImporter