ethereumjs / keythereum

Create, import and export Ethereum keys
MIT License
609 stars 163 forks source link

How to make it work with web workers? #77

Closed miguelmota closed 5 years ago

miguelmota commented 5 years ago

The number of rounds slows down the main UI thread so was wondering if there's a way to use it in a web worker. I've tried using webworkify with no luck. Thanks

miguelmota commented 5 years ago

Got it working

keystoreRecoverWorker.js

const keythereum = require('keythereum')

module.exports = function (self) {
  self.addEventListener('message', function(event) {
    const keystore = event.data.keystore
    const password = event.data.password

    const privateKey = keythereum.recover(password, keystore).toString('hex')
    self.postMessage([privateKey])
  })
}

worker.js

const work = require('webworkify')
const worker = work(require('./keystoreRecoverWorker'))

window.keystoreRecoverWorker = function(keystore, password) {
  worker.postMessage({keystore, password})

  return new Promise((resolve, reject) => {
    worker.addEventListener('message', (event) => {
      resolve(event.data[0])
    })
  })
}
browserify src/worker.js -o dist/worker.js

main.js

import `dist/worker.js`

// ...

const privateKey = await keystoreRecoverWorker(keystore, password)

Closing issue.