refactor: improve script ux

This commit is contained in:
José Oliveira 2021-08-09 12:47:36 +01:00 committed by Josh Harvey
parent bd3fd3e218
commit 7896925b9d

61
bin/lamassu-eth-recovery Normal file
View file

@ -0,0 +1,61 @@
#!/usr/bin/env node
const hdkey = require('ethereumjs-wallet/hdkey')
const hkdf = require('futoin-hkdf')
const db = require('../lib/db')
const mnemonicHelpers = require('../lib/mnemonic-helpers')
const pify = require('pify')
const fs = pify(require('fs'))
const options = require('../lib/options')
const defaultPrefixPath = "m/44'/60'/1'/0'"
const address = process.argv[2]
if (!options || !options.mnemonicPath) {
console.error(`Unable to fetch mnemonic from your account!`)
process.exit(1)
}
if (!address) {
console.log('Usage: lamassu-eth-recovery <cash-out address>')
process.exit(2)
}
function run (address) {
Promise.all([fetchMnemonic(), searchForHdIndex(address)])
.then(([mnemonic, hdIndex]) => {
try {
console.log(`Private key: `, defaultHdNode(mnemonic).deriveChild(hdIndex).getWallet().getPrivateKeyString())
process.exit(0)
} catch (err) {
console.error(`Error while retrieving private key!`)
process.exit(3)
}
})
}
function searchForHdIndex (address) {
const sql = `SELECT hd_index FROM cash_out_txs WHERE to_address = $1`
return db.oneOrNone(sql, [address])
}
function fetchMnemonic () {
return fs.readFile(options.mnemonicPath, 'utf8')
.then(mnemonic => computeSeed(mnemonic))
}
function computeSeed (seed) {
const masterSeed = mnemonicHelpers.toEntropyBuffer(seed)
return hkdf(masterSeed, 32, { salt: 'lamassu-server-salt', info: 'wallet-seed' })
}
function defaultHdNode (masterSeed) {
if (!masterSeed) throw new Error('No master seed!')
const key = hdkey.fromMasterSeed(masterSeed)
return key.derivePath(defaultPrefixPath)
}
run(address)