aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/idStore-migrator.js
blob: 14bd0d8b8046b631bc6297e36e1ac47695be0a21 (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const IdentityStore = require('./idStore')
const HdKeyring = require('../keyrings/hd')
const sigUtil = require('./sig-util')
const normalize = sigUtil.normalize

module.exports = class IdentityStoreMigrator {

  constructor ({ configManager }) {
    this.configManager = configManager
    const hasOldVault = this.hasOldVault()
    if (!hasOldVault) {
      this.idStore = new IdentityStore({ configManager })
    }
  }

  migratedVaultForPassword (password) {
    const hasOldVault = this.hasOldVault()
    const configManager = this.configManager

    if (!this.idStore) {
      this.idStore = new IdentityStore({ configManager })
    }

    if (!hasOldVault) {
      return Promise.resolve(null)
    }

    return new Promise((resolve, reject) => {
      this.idStore.submitPassword(password, (err) => {
        if (err) return reject(err)
        const serialized = this.serializeVault()
        this.checkForErrors(serialized)
        .then(resolve)
        .catch(reject)
      })
    })
  }

  serializeVault () {
    const mnemonic = this.idStore._idmgmt.getSeed()
    const numberOfAccounts = this.idStore._getAddresses().length

    return {
      type: 'HD Key Tree',
      data: { mnemonic, numberOfAccounts },
    }
  }

  checkForErrors (serialized) {
    const hd = new HdKeyring()
    return hd.deserialize(serialized.data)
    .then((hexAccounts) => {
      const newAccounts = hexAccounts.map(normalize)
      const oldAccounts = this.idStore._getAddresses().map(normalize)
      const lostAccounts = oldAccounts.reduce((result, account) => {
        if (newAccounts.includes(account)) {
          return result
        } else {
          result.push(account)
          return result
        }
      }, [])

      return {
        serialized,
        lostAccounts,
      }
    })
  }

  hasOldVault () {
    const wallet = this.configManager.getWallet()
    return wallet
  }
}