nifty-wallet/app/scripts/keyring-controller.js

285 lines
7.5 KiB
JavaScript
Raw Normal View History

const EventEmitter = require('events').EventEmitter
2016-10-19 14:55:08 -07:00
const encryptor = require('./lib/encryptor')
const messageManager = require('./lib/message-manager')
2016-10-20 16:44:31 -07:00
const ethUtil = require('ethereumjs-util')
const BN = ethUtil.BN
const Transaction = require('ethereumjs-tx')
2016-10-19 14:55:08 -07:00
2016-10-20 16:44:31 -07:00
// Keyrings:
const SimpleKeyring = require('./keyrings/simple')
const keyringTypes = [
SimpleKeyring,
]
2016-10-11 15:09:22 -07:00
module.exports = class KeyringController extends EventEmitter {
2016-10-11 15:09:22 -07:00
constructor (opts) {
super()
2016-10-11 15:09:22 -07:00
this.configManager = opts.configManager
this.ethStore = opts.ethStore
2016-10-20 16:44:31 -07:00
this.keyrings = []
2016-10-20 17:24:03 -07:00
this.identities = {} // Essentially a name hash
2016-10-11 15:09:22 -07:00
}
getState() {
2016-10-19 14:55:08 -07:00
return {
2016-10-20 10:28:45 -07:00
isInitialized: !!this.configManager.getVault(),
2016-10-19 14:55:08 -07:00
isUnlocked: !!this.key,
2016-10-20 16:44:31 -07:00
isConfirmed: true, // AUDIT this.configManager.getConfirmed(),
2016-10-19 14:55:08 -07:00
isEthConfirmed: this.configManager.getShouldntShowWarning(),
unconfTxs: this.configManager.unconfirmedTxs(),
transactions: this.configManager.getTxList(),
unconfMsgs: messageManager.unconfirmedMsgs(),
messages: messageManager.getMsgList(),
selectedAddress: this.configManager.getSelectedAccount(),
shapeShiftTxList: this.configManager.getShapeShiftTxList(),
currentFiat: this.configManager.getCurrentFiat(),
conversionRate: this.configManager.getConversionRate(),
conversionDate: this.configManager.getConversionDate(),
2016-10-20 16:44:31 -07:00
keyringTypes: keyringTypes.map((krt) => krt.type()),
identities: this.identities,
2016-10-19 14:55:08 -07:00
}
}
setStore(ethStore) {
this.ethStore = ethStore
}
createNewVault(password, entropy, cb) {
2016-10-20 12:07:53 -07:00
const salt = generateSalt()
2016-10-20 11:33:18 -07:00
this.configManager.setSalt(salt)
2016-10-20 10:28:45 -07:00
this.loadKey(password)
2016-10-19 14:55:08 -07:00
.then((key) => {
2016-10-20 16:44:31 -07:00
return encryptor.encryptWithKey(key, [])
2016-10-19 14:55:08 -07:00
})
2016-10-20 11:33:18 -07:00
.then((encryptedString) => {
2016-10-19 14:55:08 -07:00
this.configManager.setVault(encryptedString)
cb(null, this.getState())
2016-10-19 14:55:08 -07:00
})
.catch((err) => {
cb(err)
})
}
submitPassword(password, cb) {
2016-10-20 10:28:45 -07:00
this.loadKey(password)
.then((key) => {
2016-10-20 16:44:31 -07:00
return this.unlockKeyrings(key)
})
2016-10-20 17:24:03 -07:00
.then(() => {
cb(null, this.getState())
2016-10-20 10:28:45 -07:00
})
.catch((err) => {
cb(err)
})
}
loadKey(password) {
2016-10-20 17:24:03 -07:00
const salt = this.configManager.getSalt() || generateSalt()
2016-10-20 11:33:18 -07:00
return encryptor.keyFromPassword(password + salt)
2016-10-20 10:28:45 -07:00
.then((key) => {
this.key = key
return key
})
}
2016-10-20 16:44:31 -07:00
addNewKeyring(type, opts, cb) {
const i = this.getAccounts().length
const Keyring = this.getKeyringClassForType(type)
const keyring = new Keyring(opts)
const accounts = keyring.addAccounts(1)
accounts.forEach((account) => {
2016-10-20 17:24:03 -07:00
this.loadBalanceAndNickname(account, i)
2016-10-20 16:44:31 -07:00
})
2016-10-20 17:24:03 -07:00
this.keyrings.push(keyring)
2016-10-20 16:44:31 -07:00
this.persistAllKeyrings()
.then(() => {
cb(this.getState())
})
.catch((reason) => {
cb(reason)
})
}
// Takes an account address and an iterator representing
2016-10-20 17:24:03 -07:00
// the current number of named accounts.
loadBalanceAndNickname(account, i) {
const address = ethUtil.addHexPrefix(account)
this.ethStore.addAccount(address)
const oldNickname = this.configManager.nicknameForWallet(address)
const name = oldNickname || `Account ${++i}`
this.identities[address] = {
address,
name,
2016-10-20 16:44:31 -07:00
}
2016-10-20 17:24:03 -07:00
this.saveAccountLabel(address, name)
2016-10-20 16:44:31 -07:00
}
saveAccountLabel (account, label, cb) {
2016-10-20 17:24:03 -07:00
const address = ethUtil.addHexPrefix(account)
2016-10-20 16:44:31 -07:00
const configManager = this.configManager
2016-10-20 17:24:03 -07:00
configManager.setNicknameForWallet(address, label)
2016-10-20 16:44:31 -07:00
if (cb) {
cb(null, label)
}
}
persistAllKeyrings() {
2016-10-20 17:24:03 -07:00
const serialized = this.keyrings.map((k) => {
return {
type: k.type,
// keyring.serialize() must return a JSON-encodable object.
data: k.serialize(),
}
})
2016-10-20 16:44:31 -07:00
return encryptor.encryptWithKey(this.key, serialized)
.then((encryptedString) => {
this.configManager.setVault(encryptedString)
return true
})
.catch((reason) => {
console.error('Failed to persist keyrings.', reason)
})
}
unlockKeyrings(key) {
const encryptedVault = this.configManager.getVault()
return encryptor.decryptWithKey(key, encryptedVault)
.then((vault) => {
2016-10-20 17:24:03 -07:00
this.keyrings = vault.map(this.restoreKeyring.bind(this, 0))
2016-10-20 16:44:31 -07:00
return this.keyrings
})
}
2016-10-20 17:24:03 -07:00
restoreKeyring(serialized, i) {
const { type, data } = serialized
2016-10-20 16:44:31 -07:00
const Keyring = this.getKeyringClassForType(type)
2016-10-20 17:24:03 -07:00
const keyring = new Keyring()
keyring.deserialize(data)
keyring.getAccounts().forEach((account) => {
this.loadBalanceAndNickname(account, i)
})
2016-10-20 16:44:31 -07:00
return keyring
}
getKeyringClassForType(type) {
const Keyring = keyringTypes.reduce((res, kr) => {
if (kr.type() === type) {
return kr
} else {
return res
}
})
return Keyring
}
getAccounts() {
2016-10-20 17:24:03 -07:00
const keyrings = this.keyrings || []
return keyrings.map(kr => kr.getAccounts())
2016-10-20 16:44:31 -07:00
.reduce((res, arr) => {
return res.concat(arr)
}, [])
}
setSelectedAddress(address, cb) {
2016-10-20 16:44:31 -07:00
this.configManager.setSelectedAccount(address)
cb(null, address)
}
approveTransaction(txId, cb) {
cb()
}
cancelTransaction(txId, cb) {
if (cb && typeof cb === 'function') {
cb()
}
}
signTransaction(txParams, cb) {
try {
const address = ethUtil.addHexPrefix(txParams.from.toLowercase())
const keyring = this.getKeyringForAccount(address)
// Handle gas pricing
var gasMultiplier = this.configManager.getGasMultiplier() || 1
var gasPrice = new BN(ethUtil.stripHexPrefix(txParams.gasPrice), 16)
gasPrice = gasPrice.mul(new BN(gasMultiplier * 100, 10)).div(new BN(100, 10))
txParams.gasPrice = ethUtil.intToHex(gasPrice.toNumber())
// normalize values
txParams.to = ethUtil.addHexPrefix(txParams.to.toLowerCase())
txParams.from = ethUtil.addHexPrefix(txParams.from.toLowerCase())
txParams.value = ethUtil.addHexPrefix(txParams.value)
txParams.data = ethUtil.addHexPrefix(txParams.data)
txParams.gasLimit = ethUtil.addHexPrefix(txParams.gasLimit || txParams.gas)
txParams.nonce = ethUtil.addHexPrefix(txParams.nonce)
let tx = new Transaction(txParams)
tx = keyring.signTransaction(address, tx)
// Add the tx hash to the persisted meta-tx object
var txHash = ethUtil.bufferToHex(tx.hash())
var metaTx = this.configManager.getTx(txParams.metamaskId)
metaTx.hash = txHash
this.configManager.updateTx(metaTx)
// return raw serialized tx
var rawTx = ethUtil.bufferToHex(tx.serialize())
cb(null, rawTx)
} catch (e) {
cb(e)
}
}
signMessage(msgParams, cb) {
try {
const keyring = this.getKeyringForAccount(msgParams.from)
const address = ethUtil.addHexPrefix(msgParams.from.toLowercase())
const rawSig = keyring.signMessage(address, msgParams.data)
cb(null, rawSig)
} catch (e) {
cb(e)
}
}
getKeyringForAccount(address) {
const hexed = ethUtil.addHexPrefix(address.toLowerCase())
return this.keyrings.find((ring) => {
return ring.getAccounts()
.map(acct => ethUtil.addHexPrefix(acct.toLowerCase()))
.includes(hexed)
})
}
cancelMessage(msgId, cb) {
if (cb && typeof cb === 'function') {
cb()
}
}
setLocked(cb) {
cb()
}
exportAccount(address, cb) {
cb(null, '0xPrivateKey')
}
tryPassword(password, cb) {
cb()
}
2016-10-11 15:09:22 -07:00
}
2016-10-20 17:24:03 -07:00
function generateSalt (byteCount = 32) {
var view = new Uint8Array(byteCount)
2016-10-20 11:33:18 -07:00
global.crypto.getRandomValues(view)
var b64encoded = btoa(String.fromCharCode.apply(null, view))
return b64encoded
2016-10-11 15:09:22 -07:00
}