1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/app/scripts/keyring-controller.js

568 lines
15 KiB
JavaScript
Raw Normal View History

const async = require('async')
2016-10-21 01:44:31 +02:00
const ethUtil = require('ethereumjs-util')
const ethBinToOps = require('eth-bin-to-ops')
const EthQuery = require('eth-query')
const bip39 = require('bip39')
const Transaction = require('ethereumjs-tx')
const EventEmitter = require('events').EventEmitter
2016-10-19 23:55:08 +02:00
const normalize = require('./lib/sig-util').normalize
const encryptor = require('./lib/encryptor')
const messageManager = require('./lib/message-manager')
2016-10-31 17:47:20 +01:00
const autoFaucet = require('./lib/auto-faucet')
const IdStoreMigrator = require('./lib/idStore-migrator')
const BN = ethUtil.BN
2016-10-21 01:44:31 +02:00
// Keyrings:
const SimpleKeyring = require('./keyrings/simple')
const HdKeyring = require('./keyrings/hd')
2016-10-21 01:44:31 +02:00
const keyringTypes = [
SimpleKeyring,
HdKeyring,
2016-10-21 01:44:31 +02:00
]
2016-10-12 00:09:22 +02:00
const createId = require('./lib/random-id')
module.exports = class KeyringController extends EventEmitter {
2016-10-12 00:09:22 +02:00
constructor (opts) {
super()
2016-10-12 00:09:22 +02:00
this.configManager = opts.configManager
this.ethStore = opts.ethStore
this.encryptor = encryptor
this.keyringTypes = keyringTypes
2016-10-21 01:44:31 +02:00
this.keyrings = []
2016-10-21 02:24:03 +02:00
this.identities = {} // Essentially a name hash
this._unconfTxCbs = {}
this._unconfMsgCbs = {}
2016-11-11 04:07:12 +01:00
this.getNetwork = opts.getNetwork
// TEMPORARY UNTIL FULL DEPRECATION:
this.idStoreMigrator = new IdStoreMigrator({
configManager: this.configManager,
})
2016-10-12 00:09:22 +02:00
}
2016-11-11 19:26:12 +01:00
getState () {
const configManager = this.configManager
const address = configManager.getSelectedAccount()
const wallet = configManager.getWallet() // old style vault
const vault = configManager.getVault() // new style vault
2016-10-19 23:55:08 +02:00
return {
seedWords: this.configManager.getSeedWords(),
isInitialized: (!!wallet || !!vault),
2016-10-19 23:55:08 +02:00
isUnlocked: !!this.key,
isDisclaimerConfirmed: this.configManager.getConfirmedDisclaimer(), // AUDIT this.configManager.getConfirmedDisclaimer(),
2016-10-19 23:55:08 +02:00
unconfTxs: this.configManager.unconfirmedTxs(),
transactions: this.configManager.getTxList(),
unconfMsgs: messageManager.unconfirmedMsgs(),
messages: messageManager.getMsgList(),
selectedAddress: address,
selectedAccount: address,
2016-10-19 23:55:08 +02:00
shapeShiftTxList: this.configManager.getShapeShiftTxList(),
currentFiat: this.configManager.getCurrentFiat(),
conversionRate: this.configManager.getConversionRate(),
conversionDate: this.configManager.getConversionDate(),
keyringTypes: this.keyringTypes.map((krt) => krt.type()),
2016-10-21 01:44:31 +02:00
identities: this.identities,
2016-10-19 23:55:08 +02:00
}
}
2016-11-11 19:26:12 +01:00
setStore (ethStore) {
this.ethStore = ethStore
}
2016-11-11 19:26:12 +01:00
createNewVaultAndKeychain (password, entropy, cb) {
2016-11-03 19:34:57 +01:00
this.createNewVault(password, entropy, (err) => {
if (err) return cb(err)
this.createFirstKeyTree(password, cb)
})
}
2016-11-11 19:26:12 +01:00
createNewVaultAndRestore (password, seed, cb) {
if (typeof password !== 'string') {
return cb('Password must be text.')
}
if (!bip39.validateMnemonic(seed)) {
return cb('Seed phrase is invalid.')
}
this.clearKeyrings()
this.createNewVault(password, '', (err) => {
if (err) return cb(err)
this.addNewKeyring('HD Key Tree', {
mnemonic: seed,
numberOfAccounts: 1,
}, (err) => {
if (err) return cb(err)
const firstKeyring = this.keyrings[0]
const accounts = firstKeyring.getAccounts()
const firstAccount = accounts[0]
2016-11-03 21:44:29 +01:00
const hexAccount = normalize(firstAccount)
this.configManager.setSelectedAccount(hexAccount)
this.setupAccounts(accounts)
2016-11-03 19:34:57 +01:00
this.emit('update')
cb()
})
})
}
2016-11-11 19:26:12 +01:00
migrateAndGetKey (password) {
let key
const shouldMigrate = !!this.configManager.getWallet() && !this.configManager.getVault()
return this.loadKey(password)
.then((derivedKey) => {
key = derivedKey
2016-11-03 00:18:47 +01:00
this.key = key
return this.idStoreMigrator.oldSeedForPassword(password)
})
.then((serialized) => {
if (serialized && shouldMigrate) {
2016-11-03 19:34:57 +01:00
const keyring = this.restoreKeyring(serialized)
this.keyrings.push(keyring)
this.configManager.setSelectedAccount(keyring.getAccounts()[0])
return this.persistAllKeyrings()
.then(() => { return key })
}
return key
})
}
2016-11-11 19:26:12 +01:00
createNewVault (password, entropy, cb) {
const configManager = this.configManager
const salt = this.encryptor.generateSalt()
configManager.setSalt(salt)
2016-11-03 00:18:47 +01:00
return this.migrateAndGetKey(password)
.then(() => {
return this.persistAllKeyrings()
})
2016-11-03 19:34:57 +01:00
.then(() => {
cb()
2016-10-19 23:55:08 +02:00
})
.catch((err) => {
cb(err)
})
}
2016-11-11 19:26:12 +01:00
createFirstKeyTree (password, cb) {
this.clearKeyrings()
this.addNewKeyring('HD Key Tree', {numberOfAccounts: 1}, (err) => {
2016-11-15 20:07:15 +01:00
const accounts = this.keyrings[0].getAccounts()
2016-11-03 19:34:57 +01:00
const firstAccount = accounts[0]
2016-11-03 21:44:29 +01:00
const hexAccount = normalize(firstAccount)
2016-11-03 19:34:57 +01:00
this.configManager.setSelectedAccount(firstAccount)
2016-11-15 20:07:15 +01:00
this.placeSeedWords()
autoFaucet(hexAccount)
2016-11-03 19:34:57 +01:00
this.setupAccounts(accounts)
this.persistAllKeyrings()
2016-11-03 21:44:29 +01:00
.then(() => {
cb(err)
2016-11-03 21:44:29 +01:00
})
.catch((reason) => {
cb(reason)
})
})
}
2016-11-15 20:07:15 +01:00
placeSeedWords () {
2016-11-02 06:19:04 +01:00
const firstKeyring = this.keyrings[0]
const seedWords = firstKeyring.serialize().mnemonic
this.configManager.setSeedWords(seedWords)
}
2016-11-11 19:26:12 +01:00
submitPassword (password, cb) {
this.migrateAndGetKey(password)
2016-10-20 19:28:45 +02:00
.then((key) => {
2016-10-21 01:44:31 +02:00
return this.unlockKeyrings(key)
})
2016-11-03 21:44:29 +01:00
.then((keyrings) => {
this.keyrings = keyrings
this.setupAccounts()
this.emit('update')
cb(null, this.getState())
2016-10-20 19:28:45 +02:00
})
.catch((err) => {
console.error(err)
2016-10-20 19:28:45 +02:00
cb(err)
})
}
2016-11-11 19:26:12 +01:00
loadKey (password) {
const salt = this.configManager.getSalt() || this.encryptor.generateSalt()
return this.encryptor.keyFromPassword(password + salt)
2016-10-20 19:28:45 +02:00
.then((key) => {
this.key = key
this.configManager.setSalt(salt)
2016-10-20 19:28:45 +02:00
return key
})
}
2016-11-11 19:26:12 +01:00
addNewKeyring (type, opts, cb) {
2016-10-21 01:44:31 +02:00
const Keyring = this.getKeyringClassForType(type)
const keyring = new Keyring(opts)
const accounts = keyring.getAccounts()
2016-10-21 01:44:31 +02:00
2016-10-21 02:24:03 +02:00
this.keyrings.push(keyring)
this.setupAccounts(accounts)
2016-10-21 01:44:31 +02:00
this.persistAllKeyrings()
.then(() => {
cb()
2016-10-21 01:44:31 +02:00
})
.catch((reason) => {
cb(reason)
})
}
2016-11-11 19:26:12 +01:00
addNewAccount (keyRingNum = 0, cb) {
const ring = this.keyrings[keyRingNum]
const accounts = ring.addAccounts(1)
this.setupAccounts(accounts)
this.persistAllKeyrings()
.then(() => {
cb()
})
.catch((reason) => {
cb(reason)
})
}
2016-11-11 19:26:12 +01:00
setupAccounts (accounts) {
2016-11-03 21:44:29 +01:00
var arr = accounts || this.getAccounts()
arr.forEach((account) => {
2016-11-15 20:07:15 +01:00
this.getBalanceAndNickname(account)
})
}
2016-10-21 01:44:31 +02:00
// Takes an account address and an iterator representing
2016-10-21 02:24:03 +02:00
// the current number of named accounts.
2016-11-15 20:07:15 +01:00
getBalanceAndNickname (account) {
2016-11-03 21:44:29 +01:00
const address = normalize(account)
2016-10-21 02:24:03 +02:00
this.ethStore.addAccount(address)
this.createNickname(address)
}
2016-11-11 19:26:12 +01:00
createNickname (address) {
2016-11-03 21:44:29 +01:00
const hexAddress = normalize(address)
var i = Object.keys(this.identities).length
2016-10-21 02:24:03 +02:00
const oldNickname = this.configManager.nicknameForWallet(address)
const name = oldNickname || `Account ${++i}`
2016-11-03 21:44:29 +01:00
this.identities[hexAddress] = {
address: hexAddress,
2016-10-21 02:24:03 +02:00
name,
2016-10-21 01:44:31 +02:00
}
2016-11-03 21:44:29 +01:00
return this.saveAccountLabel(hexAddress, name)
2016-10-21 01:44:31 +02:00
}
saveAccountLabel (account, label, cb) {
2016-11-03 21:44:29 +01:00
const address = normalize(account)
2016-10-21 01:44:31 +02:00
const configManager = this.configManager
2016-10-21 02:24:03 +02:00
configManager.setNicknameForWallet(address, label)
2016-11-03 21:44:29 +01:00
this.identities[address].name = label
2016-10-21 01:44:31 +02:00
if (cb) {
cb(null, label)
} else {
return label
2016-10-21 01:44:31 +02:00
}
}
2016-11-11 19:26:12 +01:00
persistAllKeyrings () {
const serialized = this.keyrings.map((keyring) => {
2016-10-21 02:24:03 +02:00
return {
type: keyring.type,
data: keyring.serialize(),
2016-10-21 02:24:03 +02:00
}
})
return this.encryptor.encryptWithKey(this.key, serialized)
2016-10-21 01:44:31 +02:00
.then((encryptedString) => {
this.configManager.setVault(encryptedString)
return true
})
}
2016-11-11 19:26:12 +01:00
unlockKeyrings (key) {
2016-10-21 01:44:31 +02:00
const encryptedVault = this.configManager.getVault()
return this.encryptor.decryptWithKey(key, encryptedVault)
2016-10-21 01:44:31 +02:00
.then((vault) => {
2016-11-03 21:44:29 +01:00
vault.forEach(this.restoreKeyring.bind(this))
2016-10-21 01:44:31 +02:00
return this.keyrings
})
}
2016-11-11 19:26:12 +01:00
restoreKeyring (serialized) {
2016-10-21 02:24:03 +02:00
const { type, data } = serialized
2016-10-21 01:44:31 +02:00
const Keyring = this.getKeyringClassForType(type)
2016-10-21 02:24:03 +02:00
const keyring = new Keyring()
keyring.deserialize(data)
2016-11-03 19:34:57 +01:00
const accounts = keyring.getAccounts()
this.setupAccounts(accounts)
2016-10-21 02:24:03 +02:00
this.keyrings.push(keyring)
2016-10-21 01:44:31 +02:00
return keyring
}
2016-11-11 19:26:12 +01:00
getKeyringClassForType (type) {
const Keyring = this.keyringTypes.reduce((res, kr) => {
2016-10-21 01:44:31 +02:00
if (kr.type() === type) {
return kr
} else {
return res
}
})
return Keyring
}
2016-11-11 19:26:12 +01:00
getAccounts () {
2016-10-21 02:24:03 +02:00
const keyrings = this.keyrings || []
return keyrings.map(kr => kr.getAccounts())
2016-10-21 01:44:31 +02:00
.reduce((res, arr) => {
return res.concat(arr)
}, [])
}
2016-11-11 19:26:12 +01:00
setSelectedAddress (address, cb) {
2016-11-03 21:44:29 +01:00
var addr = normalize(address)
this.configManager.setSelectedAccount(addr)
cb(null, addr)
}
2016-11-11 19:26:12 +01:00
addUnconfirmedTransaction (txParams, onTxDoneCb, cb) {
var self = this
const configManager = this.configManager
// create txData obj with parameters and meta data
var time = (new Date()).getTime()
var txId = createId()
txParams.metamaskId = txId
2016-11-11 04:07:12 +01:00
txParams.metamaskNetworkId = this.getNetwork()
var txData = {
id: txId,
txParams: txParams,
time: time,
status: 'unconfirmed',
gasMultiplier: configManager.getGasMultiplier() || 1,
2016-11-11 04:07:12 +01:00
metamaskNetworkId: this.getNetwork(),
}
// keep the onTxDoneCb around for after approval/denial (requires user interaction)
// This onTxDoneCb fires completion to the Dapp's write operation.
this._unconfTxCbs[txId] = onTxDoneCb
var provider = this.ethStore._query.currentProvider
var query = new EthQuery(provider)
// calculate metadata for tx
async.parallel([
analyzeForDelegateCall,
estimateGas,
], didComplete)
// perform static analyis on the target contract code
2016-11-11 19:26:12 +01:00
function analyzeForDelegateCall (cb) {
if (txParams.to) {
query.getCode(txParams.to, function (err, result) {
if (err) return cb(err)
var code = ethUtil.toBuffer(result)
if (code !== '0x') {
var ops = ethBinToOps(code)
var containsDelegateCall = ops.some((op) => op.name === 'DELEGATECALL')
txData.containsDelegateCall = containsDelegateCall
cb()
} else {
cb()
}
})
} else {
cb()
}
}
2016-11-11 19:26:12 +01:00
function estimateGas (cb) {
query.estimateGas(txParams, function (err, result) {
if (err) return cb(err)
txData.estimatedGas = self.addGasBuffer(result)
cb()
})
}
function didComplete (err) {
if (err) return cb(err)
configManager.addTx(txData)
// signal update
self.emit('update')
// signal completion of add tx
cb(null, txData)
}
}
2016-11-11 19:26:12 +01:00
addUnconfirmedMessage (msgParams, cb) {
// create txData obj with parameters and meta data
var time = (new Date()).getTime()
var msgId = createId()
var msgData = {
id: msgId,
msgParams: msgParams,
time: time,
status: 'unconfirmed',
}
messageManager.addMsg(msgData)
console.log('addUnconfirmedMessage:', msgData)
// keep the cb around for after approval (requires user interaction)
// This cb fires completion to the Dapp's write operation.
this._unconfMsgCbs[msgId] = cb
// signal update
this.emit('update')
return msgId
}
2016-11-11 19:26:12 +01:00
approveTransaction (txId, cb) {
const configManager = this.configManager
var approvalCb = this._unconfTxCbs[txId] || noop
// accept tx
cb()
approvalCb(null, true)
// clean up
configManager.confirmTx(txId)
delete this._unconfTxCbs[txId]
this.emit('update')
}
2016-11-11 19:26:12 +01:00
cancelTransaction (txId, cb) {
const configManager = this.configManager
var approvalCb = this._unconfTxCbs[txId] || noop
// reject tx
approvalCb(null, false)
// clean up
configManager.rejectTx(txId)
delete this._unconfTxCbs[txId]
if (cb && typeof cb === 'function') {
cb()
}
}
2016-11-11 19:26:12 +01:00
signTransaction (txParams, cb) {
try {
2016-11-03 21:44:29 +01:00
const address = normalize(txParams.from)
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
2016-11-03 21:44:29 +01:00
txParams.to = normalize(txParams.to)
txParams.from = normalize(txParams.from)
txParams.value = normalize(txParams.value)
txParams.data = normalize(txParams.data)
txParams.gasLimit = normalize(txParams.gasLimit || txParams.gas)
txParams.nonce = normalize(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)
}
}
2016-11-11 19:26:12 +01:00
signMessage (msgParams, cb) {
try {
const keyring = this.getKeyringForAccount(msgParams.from)
2016-11-03 21:44:29 +01:00
const address = normalize(msgParams.from)
const rawSig = keyring.signMessage(address, msgParams.data)
cb(null, rawSig)
} catch (e) {
cb(e)
}
}
2016-11-11 19:26:12 +01:00
getKeyringForAccount (address) {
2016-11-03 21:44:29 +01:00
const hexed = normalize(address)
return this.keyrings.find((ring) => {
return ring.getAccounts()
2016-11-03 21:44:29 +01:00
.map(normalize)
.includes(hexed)
})
}
2016-11-11 19:26:12 +01:00
cancelMessage (msgId, cb) {
if (cb && typeof cb === 'function') {
cb()
}
}
2016-11-11 19:26:12 +01:00
setLocked (cb) {
2016-10-21 20:10:36 +02:00
this.key = null
this.keyrings = []
this.emit('update')
cb()
}
2016-11-11 19:26:12 +01:00
exportAccount (address, cb) {
2016-11-03 23:40:23 +01:00
try {
const keyring = this.getKeyringForAccount(address)
const privateKey = keyring.exportAccount(normalize(address))
cb(null, privateKey)
} catch (e) {
cb(e)
}
}
2016-11-11 19:26:12 +01:00
addGasBuffer (gas) {
2016-11-07 21:00:14 +01:00
const gasBuffer = new BN('100000', 10)
const bnGas = new BN(ethUtil.stripHexPrefix(gas), 16)
const correct = bnGas.add(gasBuffer)
return ethUtil.addHexPrefix(correct.toString(16))
}
2016-11-11 19:26:12 +01:00
clearSeedWordCache (cb) {
this.configManager.setSeedWords(null)
cb(null, this.configManager.getSelectedAccount())
}
2016-11-11 19:26:12 +01:00
clearKeyrings () {
let accounts
try {
accounts = Object.keys(this.ethStore._currentState.accounts)
} catch (e) {
accounts = []
}
accounts.forEach((address) => {
this.ethStore.removeAccount(address)
})
this.keyrings = []
this.identities = {}
this.configManager.setSelectedAccount()
}
2016-10-12 00:09:22 +02:00
}
function noop () {}