mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-23 01:39:44 +01:00
Merge branch 'i328-MultiVault' of github.com:MetaMask/metamask-plugin into i328-MultiVault
This commit is contained in:
commit
16e2f029d8
@ -21,7 +21,7 @@ const controller = new MetamaskController({
|
||||
setData,
|
||||
loadData,
|
||||
})
|
||||
const idStore = controller.idStore
|
||||
const keyringController = controller.keyringController
|
||||
|
||||
function triggerUi () {
|
||||
if (!popupIsOpen) notification.show()
|
||||
@ -82,7 +82,7 @@ function setupControllerConnection (stream) {
|
||||
// push updates to popup
|
||||
controller.ethStore.on('update', controller.sendUpdate.bind(controller))
|
||||
controller.listeners.push(remote)
|
||||
idStore.on('update', controller.sendUpdate.bind(controller))
|
||||
keyringController.on('update', controller.sendUpdate.bind(controller))
|
||||
|
||||
// teardown on disconnect
|
||||
eos(stream, () => {
|
||||
@ -96,9 +96,9 @@ function setupControllerConnection (stream) {
|
||||
// plugin badge text
|
||||
//
|
||||
|
||||
idStore.on('update', updateBadge)
|
||||
keyringController.on('update', updateBadge)
|
||||
|
||||
function updateBadge (state) {
|
||||
function updateBadge () {
|
||||
var label = ''
|
||||
var unconfTxs = controller.configManager.unconfirmedTxs()
|
||||
var unconfTxLen = Object.keys(unconfTxs).length
|
||||
|
@ -1,22 +1,44 @@
|
||||
const async = require('async')
|
||||
const EventEmitter = require('events').EventEmitter
|
||||
const encryptor = require('./lib/encryptor')
|
||||
const messageManager = require('./lib/message-manager')
|
||||
const ethUtil = require('ethereumjs-util')
|
||||
const ethBinToOps = require('eth-bin-to-ops')
|
||||
const EthQuery = require('eth-query')
|
||||
const BN = ethUtil.BN
|
||||
const Transaction = require('ethereumjs-tx')
|
||||
const createId = require('web3-provider-engine/util/random-id')
|
||||
|
||||
// Keyrings:
|
||||
const SimpleKeyring = require('./keyrings/simple')
|
||||
const keyringTypes = [
|
||||
SimpleKeyring,
|
||||
]
|
||||
|
||||
module.exports = class KeyringController extends EventEmitter {
|
||||
|
||||
constructor (opts) {
|
||||
super()
|
||||
this.web3 = opts.web3
|
||||
this.configManager = opts.configManager
|
||||
this.ethStore = opts.ethStore
|
||||
this.keyChains = []
|
||||
this.encryptor = encryptor
|
||||
this.keyringTypes = keyringTypes
|
||||
|
||||
this.keyrings = []
|
||||
this.identities = {} // Essentially a name hash
|
||||
|
||||
this._unconfTxCbs = {}
|
||||
this._unconfMsgCbs = {}
|
||||
|
||||
this.network = null
|
||||
}
|
||||
|
||||
getState() {
|
||||
return {
|
||||
isInitialized: !!this.configManager.getVault(),
|
||||
isUnlocked: !!this.key,
|
||||
isConfirmed: true, // this.configManager.getConfirmed(),
|
||||
isConfirmed: true, // AUDIT this.configManager.getConfirmed(),
|
||||
isEthConfirmed: this.configManager.getShouldntShowWarning(),
|
||||
unconfTxs: this.configManager.unconfirmedTxs(),
|
||||
transactions: this.configManager.getTxList(),
|
||||
@ -27,6 +49,9 @@ module.exports = class KeyringController extends EventEmitter {
|
||||
currentFiat: this.configManager.getCurrentFiat(),
|
||||
conversionRate: this.configManager.getConversionRate(),
|
||||
conversionDate: this.configManager.getConversionDate(),
|
||||
keyringTypes: this.keyringTypes.map((krt) => krt.type()),
|
||||
identities: this.identities,
|
||||
network: this.network,
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,11 +60,11 @@ module.exports = class KeyringController extends EventEmitter {
|
||||
}
|
||||
|
||||
createNewVault(password, entropy, cb) {
|
||||
const salt = generateSalt()
|
||||
const salt = this.encryptor.generateSalt()
|
||||
this.configManager.setSalt(salt)
|
||||
this.loadKey(password)
|
||||
.then((key) => {
|
||||
return encryptor.encryptWithKey(key, {})
|
||||
return this.encryptor.encryptWithKey(key, [])
|
||||
})
|
||||
.then((encryptedString) => {
|
||||
this.configManager.setVault(encryptedString)
|
||||
@ -53,6 +78,9 @@ module.exports = class KeyringController extends EventEmitter {
|
||||
submitPassword(password, cb) {
|
||||
this.loadKey(password)
|
||||
.then((key) => {
|
||||
return this.unlockKeyrings(key)
|
||||
})
|
||||
.then(() => {
|
||||
cb(null, this.getState())
|
||||
})
|
||||
.catch((err) => {
|
||||
@ -61,31 +89,295 @@ module.exports = class KeyringController extends EventEmitter {
|
||||
}
|
||||
|
||||
loadKey(password) {
|
||||
const salt = this.configManager.getSalt()
|
||||
return encryptor.keyFromPassword(password + salt)
|
||||
const salt = this.configManager.getSalt() || this.encryptor.generateSalt()
|
||||
return this.encryptor.keyFromPassword(password + salt)
|
||||
.then((key) => {
|
||||
this.key = key
|
||||
return key
|
||||
})
|
||||
}
|
||||
|
||||
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) => {
|
||||
this.loadBalanceAndNickname(account, i)
|
||||
})
|
||||
|
||||
this.keyrings.push(keyring)
|
||||
this.persistAllKeyrings()
|
||||
.then(() => {
|
||||
cb(this.getState())
|
||||
})
|
||||
.catch((reason) => {
|
||||
cb(reason)
|
||||
})
|
||||
}
|
||||
|
||||
// Takes an account address and an iterator representing
|
||||
// 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,
|
||||
}
|
||||
this.saveAccountLabel(address, name)
|
||||
}
|
||||
|
||||
saveAccountLabel (account, label, cb) {
|
||||
const address = ethUtil.addHexPrefix(account)
|
||||
const configManager = this.configManager
|
||||
configManager.setNicknameForWallet(address, label)
|
||||
if (cb) {
|
||||
cb(null, label)
|
||||
}
|
||||
}
|
||||
|
||||
persistAllKeyrings() {
|
||||
const serialized = this.keyrings.map((k) => {
|
||||
return {
|
||||
type: k.type,
|
||||
// keyring.serialize() must return a JSON-encodable object.
|
||||
data: k.serialize(),
|
||||
}
|
||||
})
|
||||
return this.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 this.encryptor.decryptWithKey(key, encryptedVault)
|
||||
.then((vault) => {
|
||||
this.keyrings = vault.map(this.restoreKeyring.bind(this, 0))
|
||||
return this.keyrings
|
||||
})
|
||||
}
|
||||
|
||||
restoreKeyring(i, serialized) {
|
||||
const { type, data } = serialized
|
||||
const Keyring = this.getKeyringClassForType(type)
|
||||
const keyring = new Keyring()
|
||||
keyring.deserialize(data)
|
||||
|
||||
keyring.getAccounts().forEach((account) => {
|
||||
this.loadBalanceAndNickname(account, i)
|
||||
})
|
||||
|
||||
return keyring
|
||||
}
|
||||
|
||||
getKeyringClassForType(type) {
|
||||
const Keyring = this.keyringTypes.reduce((res, kr) => {
|
||||
if (kr.type() === type) {
|
||||
return kr
|
||||
} else {
|
||||
return res
|
||||
}
|
||||
})
|
||||
return Keyring
|
||||
}
|
||||
|
||||
getAccounts() {
|
||||
const keyrings = this.keyrings || []
|
||||
return keyrings.map(kr => kr.getAccounts())
|
||||
.reduce((res, arr) => {
|
||||
return res.concat(arr)
|
||||
}, [])
|
||||
}
|
||||
|
||||
setSelectedAddress(address, cb) {
|
||||
this.selectedAddress = address
|
||||
this.configManager.setSelectedAccount(address)
|
||||
cb(null, address)
|
||||
}
|
||||
|
||||
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
|
||||
txParams.metamaskNetworkId = this.network
|
||||
var txData = {
|
||||
id: txId,
|
||||
txParams: txParams,
|
||||
time: time,
|
||||
status: 'unconfirmed',
|
||||
gasMultiplier: configManager.getGasMultiplier() || 1,
|
||||
}
|
||||
|
||||
console.log('addUnconfirmedTransaction:', txData)
|
||||
|
||||
// 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
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
@ -95,6 +387,8 @@ module.exports = class KeyringController extends EventEmitter {
|
||||
}
|
||||
|
||||
setLocked(cb) {
|
||||
this.key = null
|
||||
this.keyrings = []
|
||||
cb()
|
||||
}
|
||||
|
||||
@ -102,19 +396,36 @@ module.exports = class KeyringController extends EventEmitter {
|
||||
cb(null, '0xPrivateKey')
|
||||
}
|
||||
|
||||
saveAccountLabel(account, label, cb) {
|
||||
cb(/* null, label */)
|
||||
}
|
||||
|
||||
tryPassword(password, cb) {
|
||||
cb()
|
||||
}
|
||||
|
||||
getNetwork(err) {
|
||||
if (err) {
|
||||
this.network = 'loading'
|
||||
this.emit('update')
|
||||
}
|
||||
|
||||
this.web3.version.getNetwork((err, network) => {
|
||||
if (err) {
|
||||
this.network = 'loading'
|
||||
return this.emit('update')
|
||||
}
|
||||
if (global.METAMASK_DEBUG) {
|
||||
console.log('web3.getNetwork returned ' + network)
|
||||
}
|
||||
this.network = network
|
||||
this.emit('update')
|
||||
})
|
||||
}
|
||||
|
||||
addGasBuffer(gasHex) {
|
||||
var gas = new BN(gasHex, 16)
|
||||
var buffer = new BN('100000', 10)
|
||||
var result = gas.add(buffer)
|
||||
return ethUtil.addHexPrefix(result.toString(16))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function generateSalt (byteCount) {
|
||||
var view = new Uint8Array(32)
|
||||
global.crypto.getRandomValues(view)
|
||||
var b64encoded = btoa(String.fromCharCode.apply(null, view))
|
||||
return b64encoded
|
||||
}
|
||||
function noop () {}
|
||||
|
68
app/scripts/keyrings/simple.js
Normal file
68
app/scripts/keyrings/simple.js
Normal file
@ -0,0 +1,68 @@
|
||||
const EventEmitter = require('events').EventEmitter
|
||||
const Wallet = require('ethereumjs-wallet')
|
||||
const ethUtil = require('ethereumjs-util')
|
||||
const type = 'Simple Key Pair'
|
||||
const sigUtil = require('../lib/sig-util')
|
||||
|
||||
module.exports = class SimpleKeyring extends EventEmitter {
|
||||
|
||||
static type() {
|
||||
return type
|
||||
}
|
||||
|
||||
constructor(opts) {
|
||||
super()
|
||||
this.type = type
|
||||
this.opts = opts || {}
|
||||
this.wallets = []
|
||||
}
|
||||
|
||||
serialize() {
|
||||
return this.wallets.map(w => w.getPrivateKey().toString('hex'))
|
||||
}
|
||||
|
||||
deserialize(wallets = []) {
|
||||
this.wallets = wallets.map((w) => {
|
||||
var b = new Buffer(w, 'hex')
|
||||
const wallet = Wallet.fromPrivateKey(b)
|
||||
return wallet
|
||||
})
|
||||
}
|
||||
|
||||
addAccounts(n = 1) {
|
||||
var newWallets = []
|
||||
for (var i = 0; i < n; i++) {
|
||||
newWallets.push(Wallet.generate())
|
||||
}
|
||||
this.wallets = this.wallets.concat(newWallets)
|
||||
return newWallets.map(w => w.getAddress().toString('hex'))
|
||||
}
|
||||
|
||||
getAccounts() {
|
||||
return this.wallets.map(w => w.getAddress().toString('hex'))
|
||||
}
|
||||
|
||||
// tx is an instance of the ethereumjs-transaction class.
|
||||
signTransaction(address, tx) {
|
||||
const wallet = this.getWalletForAccount(address)
|
||||
var privKey = wallet.getPrivateKey()
|
||||
tx.sign(privKey)
|
||||
return tx
|
||||
}
|
||||
|
||||
// For eth_sign, we need to sign transactions:
|
||||
signMessage(withAccount, data) {
|
||||
const wallet = this.getWalletForAccount(withAccount)
|
||||
const message = ethUtil.removeHexPrefix(data)
|
||||
var privKey = wallet.getPrivateKey()
|
||||
var msgSig = ethUtil.ecsign(new Buffer(message, 'hex'), privKey)
|
||||
var rawMsgSig = ethUtil.bufferToHex(sigUtil.concatSig(msgSig.v, msgSig.r, msgSig.s))
|
||||
return rawMsgSig
|
||||
}
|
||||
|
||||
getWalletForAccount(account) {
|
||||
return this.wallets.find(w => w.getAddress().toString('hex') === account)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -22,6 +22,8 @@ module.exports = {
|
||||
// Buffer <-> base64 string methods
|
||||
encodeBufferToBase64,
|
||||
decodeBase64ToBuffer,
|
||||
|
||||
generateSalt,
|
||||
}
|
||||
|
||||
// Takes a Pojo, returns encrypted text.
|
||||
@ -135,3 +137,10 @@ function decodeBase64ToBuffer (base64) {
|
||||
}))
|
||||
return buf
|
||||
}
|
||||
|
||||
function generateSalt (byteCount = 32) {
|
||||
var view = new Uint8Array(byteCount)
|
||||
global.crypto.getRandomValues(view)
|
||||
var b64encoded = btoa(String.fromCharCode.apply(null, view))
|
||||
return b64encoded
|
||||
}
|
||||
|
@ -114,7 +114,6 @@ IdentityStore.prototype.getState = function () {
|
||||
conversionRate: configManager.getConversionRate(),
|
||||
conversionDate: configManager.getConversionDate(),
|
||||
gasMultiplier: configManager.getGasMultiplier(),
|
||||
|
||||
}))
|
||||
}
|
||||
|
||||
|
23
app/scripts/lib/sig-util.js
Normal file
23
app/scripts/lib/sig-util.js
Normal file
@ -0,0 +1,23 @@
|
||||
const ethUtil = require('ethereumjs-util')
|
||||
|
||||
module.exports = {
|
||||
|
||||
concatSig: function (v, r, s) {
|
||||
const rSig = ethUtil.fromSigned(r)
|
||||
const sSig = ethUtil.fromSigned(s)
|
||||
const vSig = ethUtil.bufferToInt(v)
|
||||
const rStr = padWithZeroes(ethUtil.toUnsigned(rSig).toString('hex'), 64)
|
||||
const sStr = padWithZeroes(ethUtil.toUnsigned(sSig).toString('hex'), 64)
|
||||
const vStr = ethUtil.stripHexPrefix(ethUtil.intToHex(vSig))
|
||||
return ethUtil.addHexPrefix(rStr.concat(sStr, vStr)).toString('hex')
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
function padWithZeroes (number, length) {
|
||||
var myString = '' + number
|
||||
while (myString.length < length) {
|
||||
myString = '0' + myString
|
||||
}
|
||||
return myString
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
const extend = require('xtend')
|
||||
const EthStore = require('eth-store')
|
||||
const MetaMaskProvider = require('web3-provider-engine/zero.js')
|
||||
const IdentityStore = require('./keyring-controller')
|
||||
const KeyringController = require('./keyring-controller')
|
||||
const messageManager = require('./lib/message-manager')
|
||||
const HostStore = require('./lib/remote-store.js').HostStore
|
||||
const Web3 = require('web3')
|
||||
@ -15,12 +15,12 @@ module.exports = class MetamaskController {
|
||||
this.opts = opts
|
||||
this.listeners = []
|
||||
this.configManager = new ConfigManager(opts)
|
||||
this.idStore = new IdentityStore({
|
||||
this.keyringController = new KeyringController({
|
||||
configManager: this.configManager,
|
||||
})
|
||||
this.provider = this.initializeProvider(opts)
|
||||
this.ethStore = new EthStore(this.provider)
|
||||
this.idStore.setStore(this.ethStore)
|
||||
this.keyringController.setStore(this.ethStore)
|
||||
this.getNetwork()
|
||||
this.messageManager = messageManager
|
||||
this.publicConfigStore = this.initPublicConfigStore()
|
||||
@ -38,13 +38,13 @@ module.exports = class MetamaskController {
|
||||
return extend(
|
||||
this.state,
|
||||
this.ethStore.getState(),
|
||||
this.idStore.getState(),
|
||||
this.keyringController.getState(),
|
||||
this.configManager.getConfig()
|
||||
)
|
||||
}
|
||||
|
||||
getApi () {
|
||||
const idStore = this.idStore
|
||||
const keyringController = this.keyringController
|
||||
|
||||
return {
|
||||
getState: (cb) => { cb(null, this.getState()) },
|
||||
@ -59,18 +59,19 @@ module.exports = class MetamaskController {
|
||||
checkTOSChange: this.checkTOSChange.bind(this),
|
||||
setGasMultiplier: this.setGasMultiplier.bind(this),
|
||||
|
||||
// forward directly to idStore
|
||||
createNewVault: idStore.createNewVault.bind(idStore),
|
||||
submitPassword: idStore.submitPassword.bind(idStore),
|
||||
setSelectedAddress: idStore.setSelectedAddress.bind(idStore),
|
||||
approveTransaction: idStore.approveTransaction.bind(idStore),
|
||||
cancelTransaction: idStore.cancelTransaction.bind(idStore),
|
||||
signMessage: idStore.signMessage.bind(idStore),
|
||||
cancelMessage: idStore.cancelMessage.bind(idStore),
|
||||
setLocked: idStore.setLocked.bind(idStore),
|
||||
exportAccount: idStore.exportAccount.bind(idStore),
|
||||
saveAccountLabel: idStore.saveAccountLabel.bind(idStore),
|
||||
tryPassword: idStore.tryPassword.bind(idStore),
|
||||
// forward directly to keyringController
|
||||
createNewVault: keyringController.createNewVault.bind(keyringController),
|
||||
addNewKeyring: keyringController.addNewKeyring.bind(keyringController),
|
||||
submitPassword: keyringController.submitPassword.bind(keyringController),
|
||||
setSelectedAddress: keyringController.setSelectedAddress.bind(keyringController),
|
||||
approveTransaction: keyringController.approveTransaction.bind(keyringController),
|
||||
cancelTransaction: keyringController.cancelTransaction.bind(keyringController),
|
||||
signMessage: keyringController.signMessage.bind(keyringController),
|
||||
cancelMessage: keyringController.cancelMessage.bind(keyringController),
|
||||
setLocked: keyringController.setLocked.bind(keyringController),
|
||||
exportAccount: keyringController.exportAccount.bind(keyringController),
|
||||
saveAccountLabel: keyringController.saveAccountLabel.bind(keyringController),
|
||||
tryPassword: keyringController.tryPassword.bind(keyringController),
|
||||
// coinbase
|
||||
buyEth: this.buyEth.bind(this),
|
||||
// shapeshift
|
||||
@ -132,27 +133,27 @@ module.exports = class MetamaskController {
|
||||
}
|
||||
|
||||
initializeProvider (opts) {
|
||||
const idStore = this.idStore
|
||||
const keyringController = this.keyringController
|
||||
|
||||
var providerOpts = {
|
||||
rpcUrl: this.configManager.getCurrentRpcAddress(),
|
||||
// account mgmt
|
||||
getAccounts: (cb) => {
|
||||
var selectedAddress = idStore.getSelectedAddress()
|
||||
var selectedAddress = this.configManager.getSelectedAccount()
|
||||
var result = selectedAddress ? [selectedAddress] : []
|
||||
cb(null, result)
|
||||
},
|
||||
// tx signing
|
||||
approveTransaction: this.newUnsignedTransaction.bind(this),
|
||||
signTransaction: (...args) => {
|
||||
idStore.signTransaction(...args)
|
||||
keyringController.signTransaction(...args)
|
||||
this.sendUpdate()
|
||||
},
|
||||
|
||||
// msg signing
|
||||
approveMessage: this.newUnsignedMessage.bind(this),
|
||||
signMessage: (...args) => {
|
||||
idStore.signMessage(...args)
|
||||
keyringController.signMessage(...args)
|
||||
this.sendUpdate()
|
||||
},
|
||||
}
|
||||
@ -160,7 +161,7 @@ module.exports = class MetamaskController {
|
||||
var provider = MetaMaskProvider(providerOpts)
|
||||
var web3 = new Web3(provider)
|
||||
this.web3 = web3
|
||||
idStore.web3 = web3
|
||||
keyringController.web3 = web3
|
||||
|
||||
provider.on('block', this.processBlock.bind(this))
|
||||
provider.on('error', this.getNetwork.bind(this))
|
||||
@ -171,7 +172,7 @@ module.exports = class MetamaskController {
|
||||
initPublicConfigStore () {
|
||||
// get init state
|
||||
var initPublicState = extend(
|
||||
idStoreToPublic(this.idStore.getState()),
|
||||
keyringControllerToPublic(this.keyringController.getState()),
|
||||
configToPublic(this.configManager.getConfig())
|
||||
)
|
||||
|
||||
@ -181,12 +182,14 @@ module.exports = class MetamaskController {
|
||||
this.configManager.subscribe(function (state) {
|
||||
storeSetFromObj(publicConfigStore, configToPublic(state))
|
||||
})
|
||||
this.idStore.on('update', function (state) {
|
||||
storeSetFromObj(publicConfigStore, idStoreToPublic(state))
|
||||
this.keyringController.on('update', () => {
|
||||
const state = this.keyringController.getState()
|
||||
storeSetFromObj(publicConfigStore, keyringControllerToPublic(state))
|
||||
this.sendUpdate()
|
||||
})
|
||||
|
||||
// idStore substate
|
||||
function idStoreToPublic (state) {
|
||||
// keyringController substate
|
||||
function keyringControllerToPublic (state) {
|
||||
return {
|
||||
selectedAddress: state.selectedAddress,
|
||||
}
|
||||
@ -209,12 +212,12 @@ module.exports = class MetamaskController {
|
||||
}
|
||||
|
||||
newUnsignedTransaction (txParams, onTxDoneCb) {
|
||||
const idStore = this.idStore
|
||||
const keyringController = this.keyringController
|
||||
|
||||
let err = this.enforceTxValidations(txParams)
|
||||
if (err) return onTxDoneCb(err)
|
||||
|
||||
idStore.addUnconfirmedTransaction(txParams, onTxDoneCb, (err, txData) => {
|
||||
keyringController.addUnconfirmedTransaction(txParams, onTxDoneCb, (err, txData) => {
|
||||
if (err) return onTxDoneCb(err)
|
||||
this.sendUpdate()
|
||||
this.opts.showUnconfirmedTx(txParams, txData, onTxDoneCb)
|
||||
@ -229,9 +232,9 @@ module.exports = class MetamaskController {
|
||||
}
|
||||
|
||||
newUnsignedMessage (msgParams, cb) {
|
||||
var state = this.idStore.getState()
|
||||
var state = this.keyringController.getState()
|
||||
if (!state.isUnlocked) {
|
||||
this.idStore.addUnconfirmedMessage(msgParams, cb)
|
||||
this.keyringController.addUnconfirmedMessage(msgParams, cb)
|
||||
this.opts.unlockAccountMessage()
|
||||
} else {
|
||||
this.addUnconfirmedMessage(msgParams, cb)
|
||||
@ -240,8 +243,8 @@ module.exports = class MetamaskController {
|
||||
}
|
||||
|
||||
addUnconfirmedMessage (msgParams, cb) {
|
||||
const idStore = this.idStore
|
||||
const msgId = idStore.addUnconfirmedMessage(msgParams, cb)
|
||||
const keyringController = this.keyringController
|
||||
const msgId = keyringController.addUnconfirmedMessage(msgParams, cb)
|
||||
this.opts.showUnconfirmedMessage(msgParams, msgId)
|
||||
}
|
||||
|
||||
|
@ -47,6 +47,7 @@
|
||||
"eth-store": "^1.1.0",
|
||||
"ethereumjs-tx": "^1.0.0",
|
||||
"ethereumjs-util": "^4.4.0",
|
||||
"ethereumjs-wallet": "^0.6.0",
|
||||
"express": "^4.14.0",
|
||||
"gulp-eslint": "^2.0.0",
|
||||
"hat": "0.0.3",
|
||||
|
32
test/lib/mock-encryptor.js
Normal file
32
test/lib/mock-encryptor.js
Normal file
@ -0,0 +1,32 @@
|
||||
var mockHex = '0xabcdef0123456789'
|
||||
var mockKey = new Buffer(32)
|
||||
let cacheVal
|
||||
|
||||
module.exports = {
|
||||
|
||||
encrypt(password, dataObj) {
|
||||
cacheVal = dataObj
|
||||
return Promise.resolve(mockHex)
|
||||
},
|
||||
|
||||
decrypt(password, text) {
|
||||
return Promise.resolve(cacheVal || {})
|
||||
},
|
||||
|
||||
encryptWithKey(key, dataObj) {
|
||||
return this.encrypt(key, dataObj)
|
||||
},
|
||||
|
||||
decryptWithKey(key, text) {
|
||||
return this.decrypt(key, text)
|
||||
},
|
||||
|
||||
keyFromPassword(password) {
|
||||
return Promise.resolve(mockKey)
|
||||
},
|
||||
|
||||
generateSalt() {
|
||||
return 'WHADDASALT!'
|
||||
},
|
||||
|
||||
}
|
38
test/lib/mock-simple-keychain.js
Normal file
38
test/lib/mock-simple-keychain.js
Normal file
@ -0,0 +1,38 @@
|
||||
var fakeWallet = {
|
||||
privKey: '0x123456788890abcdef',
|
||||
address: '0xfedcba0987654321',
|
||||
}
|
||||
const type = 'Simple Key Pair'
|
||||
|
||||
module.exports = class MockSimpleKeychain {
|
||||
|
||||
static type() { return type }
|
||||
|
||||
constructor(opts) {
|
||||
this.type = type
|
||||
this.opts = opts || {}
|
||||
this.wallets = []
|
||||
}
|
||||
|
||||
serialize() {
|
||||
return [ fakeWallet.privKey ]
|
||||
}
|
||||
|
||||
deserialize(data) {
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error('Simple keychain deserialize requires a privKey array.')
|
||||
}
|
||||
this.wallets = [ fakeWallet ]
|
||||
}
|
||||
|
||||
addAccounts(n = 1) {
|
||||
for(var i = 0; i < n; i++) {
|
||||
this.wallets.push(fakeWallet)
|
||||
}
|
||||
}
|
||||
|
||||
getAccounts() {
|
||||
return this.wallets.map(w => w.address)
|
||||
}
|
||||
|
||||
}
|
@ -3,33 +3,81 @@ var KeyringController = require('../../app/scripts/keyring-controller')
|
||||
var configManagerGen = require('../lib/mock-config-manager')
|
||||
const ethUtil = require('ethereumjs-util')
|
||||
const async = require('async')
|
||||
const mockEncryptor = require('../lib/mock-encryptor')
|
||||
const MockSimpleKeychain = require('../lib/mock-simple-keychain')
|
||||
const sinon = require('sinon')
|
||||
|
||||
describe('KeyringController', function() {
|
||||
|
||||
let keyringController
|
||||
let password = 'password123'
|
||||
let entropy = 'entripppppyy duuude'
|
||||
let seedWords
|
||||
let accounts = []
|
||||
let originalKeystore
|
||||
|
||||
beforeEach(function(done) {
|
||||
this.sinon = sinon.sandbox.create()
|
||||
window.localStorage = {} // Hacking localStorage support into JSDom
|
||||
|
||||
keyringController = new KeyringController({
|
||||
configManager: configManagerGen(),
|
||||
ethStore: {
|
||||
addAccount(acct) { accounts.push(ethUtil.addHexPrefix(acct)) },
|
||||
},
|
||||
})
|
||||
|
||||
// Stub out the browser crypto for a mock encryptor.
|
||||
// Browser crypto is tested in the integration test suite.
|
||||
keyringController.encryptor = mockEncryptor
|
||||
|
||||
keyringController.createNewVault(password, null, function (err, state) {
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(function() {
|
||||
// Cleanup mocks
|
||||
this.sinon.restore()
|
||||
})
|
||||
|
||||
describe('#createNewVault', function () {
|
||||
let keyringController
|
||||
let password = 'password123'
|
||||
let entropy = 'entripppppyy duuude'
|
||||
let seedWords
|
||||
let accounts = []
|
||||
let originalKeystore
|
||||
|
||||
before(function(done) {
|
||||
window.localStorage = {} // Hacking localStorage support into JSDom
|
||||
|
||||
keyringController = new KeyringController({
|
||||
configManager: configManagerGen(),
|
||||
ethStore: {
|
||||
addAccount(acct) { accounts.push(ethUtil.addHexPrefix(acct)) },
|
||||
},
|
||||
})
|
||||
|
||||
keyringController.createNewVault(password, entropy, (err, seeds) => {
|
||||
assert.ifError(err, 'createNewVault threw error')
|
||||
seedWords = seeds
|
||||
originalKeystore = keyringController._idmgmt.keyStore
|
||||
it('should set a vault on the configManager', function(done) {
|
||||
keyringController.configManager.setVault(null)
|
||||
assert(!keyringController.configManager.getVault(), 'no previous vault')
|
||||
keyringController.createNewVault(password, null, function (err, state) {
|
||||
assert.ifError(err)
|
||||
const vault = keyringController.configManager.getVault()
|
||||
assert(vault, 'vault created')
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('#restoreKeyring', function(done) {
|
||||
|
||||
it(`should pass a keyring's serialized data back to the correct type.`, function() {
|
||||
keyringController.keyringTypes = [ MockSimpleKeychain ]
|
||||
|
||||
const mockSerialized = {
|
||||
type: MockSimpleKeychain.type(),
|
||||
data: [ '0x123456null788890abcdef' ],
|
||||
}
|
||||
const mock = this.sinon.mock(keyringController)
|
||||
|
||||
mock.expects('loadBalanceAndNickname')
|
||||
.exactly(1)
|
||||
|
||||
var keyring = keyringController.restoreKeyring(0, mockSerialized)
|
||||
assert.equal(keyring.wallets.length, 1, 'one wallet restored')
|
||||
mock.verify()
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
83
test/unit/keyrings/simple-test.js
Normal file
83
test/unit/keyrings/simple-test.js
Normal file
@ -0,0 +1,83 @@
|
||||
const assert = require('assert')
|
||||
const extend = require('xtend')
|
||||
const SimpleKeyring = require('../../../app/scripts/keyrings/simple')
|
||||
const TYPE_STR = 'Simple Key Pair'
|
||||
|
||||
// Sample account:
|
||||
const privKeyHex = 'b8a9c05beeedb25df85f8d641538cbffedf67216048de9c678ee26260eb91952'
|
||||
|
||||
describe('simple-keyring', function() {
|
||||
|
||||
let keyring
|
||||
beforeEach(function() {
|
||||
keyring = new SimpleKeyring()
|
||||
})
|
||||
|
||||
describe('Keyring.type()', function() {
|
||||
it('is a class method that returns the type string.', function() {
|
||||
const type = SimpleKeyring.type()
|
||||
assert.equal(type, TYPE_STR)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#type', function() {
|
||||
it('returns the correct value', function() {
|
||||
const type = keyring.type
|
||||
assert.equal(type, TYPE_STR)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#serialize empty wallets.', function() {
|
||||
it('serializes an empty array', function() {
|
||||
const output = keyring.serialize()
|
||||
assert.deepEqual(output, [])
|
||||
})
|
||||
})
|
||||
|
||||
describe('#deserialize a private key', function() {
|
||||
it('serializes what it deserializes', function() {
|
||||
keyring.deserialize([privKeyHex])
|
||||
assert.equal(keyring.wallets.length, 1, 'has one wallet')
|
||||
|
||||
const serialized = keyring.serialize()
|
||||
assert.equal(serialized[0], privKeyHex)
|
||||
})
|
||||
})
|
||||
|
||||
describe('#addAccounts', function() {
|
||||
describe('with no arguments', function() {
|
||||
it('creates a single wallet', function() {
|
||||
keyring.addAccounts()
|
||||
assert.equal(keyring.wallets.length, 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('with a numeric argument', function() {
|
||||
it('creates that number of wallets', function() {
|
||||
keyring.addAccounts(3)
|
||||
assert.equal(keyring.wallets.length, 3)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('#getAccounts', function() {
|
||||
it('calls getAddress on each wallet', function() {
|
||||
|
||||
// Push a mock wallet
|
||||
const desiredOutput = 'foo'
|
||||
keyring.wallets.push({
|
||||
getAddress() {
|
||||
return {
|
||||
toString() {
|
||||
return desiredOutput
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const output = keyring.getAccounts()
|
||||
assert.equal(output[0], desiredOutput)
|
||||
assert.equal(output.length, 1)
|
||||
})
|
||||
})
|
||||
})
|
@ -87,7 +87,7 @@ AccountsScreen.prototype.render = function () {
|
||||
h('div.footer.hover-white.pointer', {
|
||||
key: 'reveal-account-bar',
|
||||
onClick: () => {
|
||||
this.onRevealAccount()
|
||||
this.addNewKeyring()
|
||||
},
|
||||
style: {
|
||||
display: 'flex',
|
||||
@ -146,8 +146,8 @@ AccountsScreen.prototype.onShowDetail = function (address, event) {
|
||||
this.props.dispatch(actions.showAccountDetail(address))
|
||||
}
|
||||
|
||||
AccountsScreen.prototype.onRevealAccount = function () {
|
||||
this.props.dispatch(actions.revealAccount())
|
||||
AccountsScreen.prototype.addNewKeyring = function () {
|
||||
this.props.dispatch(actions.addNewKeyring('Simple Key Pair'))
|
||||
}
|
||||
|
||||
AccountsScreen.prototype.goHome = function () {
|
||||
|
@ -25,6 +25,7 @@ var actions = {
|
||||
showInitializeMenu: showInitializeMenu,
|
||||
createNewVault: createNewVault,
|
||||
createNewVaultInProgress: createNewVaultInProgress,
|
||||
addNewKeyring: addNewKeyring,
|
||||
showNewVaultSeed: showNewVaultSeed,
|
||||
showInfoPage: showInfoPage,
|
||||
// unlock screen
|
||||
@ -136,6 +137,7 @@ var actions = {
|
||||
SHOW_NEW_KEYCHAIN: 'SHOW_NEW_KEYCHAIN',
|
||||
showNewKeychain: showNewKeychain,
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = actions
|
||||
@ -187,6 +189,20 @@ function createNewVault (password, entropy) {
|
||||
}
|
||||
}
|
||||
|
||||
function addNewKeyring (type, opts) {
|
||||
return (dispatch) => {
|
||||
dispatch(actions.showLoadingIndication())
|
||||
background.addNewKeyring(type, opts, (err, newState) => {
|
||||
dispatch(this.hideLoadingIndication())
|
||||
if (err) {
|
||||
return dispatch(actions.showWarning(err))
|
||||
}
|
||||
dispatch(this.updateMetamaskState(newState))
|
||||
dispatch(this.showAccountsPage())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function showInfoPage () {
|
||||
return {
|
||||
type: actions.SHOW_INFO_PAGE,
|
||||
|
@ -405,7 +405,6 @@ App.prototype.renderPrimary = function () {
|
||||
|
||||
// show current view
|
||||
switch (props.currentView.name) {
|
||||
|
||||
case 'createVault':
|
||||
return h(CreateVaultScreen, {key: 'createVault'})
|
||||
|
||||
@ -502,12 +501,7 @@ App.prototype.renderCustomOption = function (rpcTarget) {
|
||||
return null
|
||||
|
||||
case 'http://localhost:8545':
|
||||
return h(DropMenuItem, {
|
||||
label: 'Custom RPC',
|
||||
closeMenu: () => this.setState({ isNetworkMenuOpen: false }),
|
||||
action: () => this.props.dispatch(actions.showConfigPage()),
|
||||
icon: h('i.fa.fa-question-circle.fa-lg'),
|
||||
})
|
||||
return null
|
||||
|
||||
default:
|
||||
return h(DropMenuItem, {
|
||||
|
Loading…
Reference in New Issue
Block a user