diff options
37 files changed, 1385 insertions, 286 deletions
@@ -129,7 +129,7 @@ "one-var": [2, { "initialized": "never" }], "operator-linebreak": [1, "after", { "overrides": { "?": "before", ":": "before" } }], "padded-blocks": [1, "never"], - "quotes": [2, "single", "avoid-escape"], + "quotes": [2, "single", {"avoidEscape": true, "allowTemplateLiterals": true}], "semi": [2, "never"], "semi-spacing": [2, { "before": false, "after": true }], "space-before-blocks": [1, "always"], diff --git a/.gitignore b/.gitignore index 14b823c82..0b649d486 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ dist - node_modules temp .tmp @@ -7,7 +6,6 @@ temp app/bower_components test/bower_components package - .DS_Store builds/ notes.txt @@ -90,6 +90,10 @@ You can also test with a continuously watching process, via `npm run watch`. You can run the linter by itself with `gulp lint`. +#### Writing Browser Tests + +To write tests that will be run in the browser using QUnit, add your test files to `test/integration/lib`. + ### Deploying the UI You must be authorized already on the MetaMask plugin. diff --git a/app/scripts/background.js b/app/scripts/background.js index 652acc113..f05760ac3 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -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 diff --git a/app/scripts/keyring-controller.js b/app/scripts/keyring-controller.js new file mode 100644 index 000000000..28c920d22 --- /dev/null +++ b/app/scripts/keyring-controller.js @@ -0,0 +1,431 @@ +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.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, // AUDIT this.configManager.getConfirmed(), + 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(), + keyringTypes: this.keyringTypes.map((krt) => krt.type()), + identities: this.identities, + network: this.network, + } + } + + setStore(ethStore) { + this.ethStore = ethStore + } + + createNewVault(password, entropy, cb) { + const salt = this.encryptor.generateSalt() + this.configManager.setSalt(salt) + this.loadKey(password) + .then((key) => { + return this.encryptor.encryptWithKey(key, []) + }) + .then((encryptedString) => { + this.configManager.setVault(encryptedString) + cb(null, this.getState()) + }) + .catch((err) => { + cb(err) + }) + } + + submitPassword(password, cb) { + this.loadKey(password) + .then((key) => { + return this.unlockKeyrings(key) + }) + .then(() => { + cb(null, this.getState()) + }) + .catch((err) => { + cb(err) + }) + } + + loadKey(password) { + 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.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) { + 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) { + this.key = null + this.keyrings = [] + cb() + } + + exportAccount(address, cb) { + cb(null, '0xPrivateKey') + } + + 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 noop () {} diff --git a/app/scripts/keyrings/simple.js b/app/scripts/keyrings/simple.js new file mode 100644 index 000000000..9e832f274 --- /dev/null +++ b/app/scripts/keyrings/simple.js @@ -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) + } + +} + diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js index cced32670..ae4a84082 100644 --- a/app/scripts/lib/config-manager.js +++ b/app/scripts/lib/config-manager.js @@ -110,6 +110,27 @@ ConfigManager.prototype.setWallet = function (wallet) { this.setData(data) } +ConfigManager.prototype.setVault = function (encryptedString) { + var data = this.getData() + data.vault = encryptedString + this.setData(data) +} + +ConfigManager.prototype.getVault = function () { + var data = this.getData() + return ('vault' in data) && data.vault +} + +ConfigManager.prototype.getKeychains = function () { + return this.migrator.getData().keychains || [] +} + +ConfigManager.prototype.setKeychains = function (keychains) { + var data = this.migrator.getData() + data.keychains = keychains + this.setData(data) +} + ConfigManager.prototype.getSelectedAccount = function () { var config = this.getConfig() return config.selectedAccount @@ -249,6 +270,17 @@ ConfigManager.prototype.setNicknameForWallet = function (account, nickname) { // observable +ConfigManager.prototype.getSalt = function () { + var data = this.getData() + return ('salt' in data) && data.salt +} + +ConfigManager.prototype.setSalt = function(salt) { + var data = this.getData() + data.salt = salt + this.setData(data) +} + ConfigManager.prototype.subscribe = function (fn) { this._subs.push(fn) var unsubscribe = this.unsubscribe.bind(this, fn) diff --git a/app/scripts/lib/encryptor.js b/app/scripts/lib/encryptor.js new file mode 100644 index 000000000..832e6d528 --- /dev/null +++ b/app/scripts/lib/encryptor.js @@ -0,0 +1,146 @@ +var ethUtil = require('ethereumjs-util') + +module.exports = { + + // Simple encryption methods: + encrypt, + decrypt, + + // More advanced encryption methods: + keyFromPassword, + encryptWithKey, + decryptWithKey, + + // Buffer <-> String methods + convertArrayBufferViewtoString, + convertStringToArrayBufferView, + + // Buffer <-> Hex string methods + serializeBufferForStorage, + serializeBufferFromStorage, + + // Buffer <-> base64 string methods + encodeBufferToBase64, + decodeBase64ToBuffer, + + generateSalt, +} + +// Takes a Pojo, returns encrypted text. +function encrypt (password, dataObj) { + return keyFromPassword(password) + .then(function (passwordDerivedKey) { + return encryptWithKey(passwordDerivedKey, dataObj) + }) +} + +function encryptWithKey (key, dataObj) { + var data = JSON.stringify(dataObj) + var dataBuffer = convertStringToArrayBufferView(data) + var vector = global.crypto.getRandomValues(new Uint8Array(16)) + + return global.crypto.subtle.encrypt({ + name: 'AES-GCM', + iv: vector, + }, key, dataBuffer).then(function(buf){ + var buffer = new Uint8Array(buf) + var vectorStr = encodeBufferToBase64(vector) + var vaultStr = encodeBufferToBase64(buffer) + return `${vaultStr}\\${vectorStr}` + }) +} + +// Takes encrypted text, returns the restored Pojo. +function decrypt (password, text) { + return keyFromPassword(password) + .then(function (key) { + return decryptWithKey(key, text) + }) +} + +function decryptWithKey (key, text) { + const parts = text.split('\\') + const encryptedData = decodeBase64ToBuffer(parts[0]) + const vector = decodeBase64ToBuffer(parts[1]) + return crypto.subtle.decrypt({name: 'AES-GCM', iv: vector}, key, encryptedData) + .then(function(result){ + const decryptedData = new Uint8Array(result) + const decryptedStr = convertArrayBufferViewtoString(decryptedData) + const decryptedObj = JSON.parse(decryptedStr) + return decryptedObj + }) +} + +function convertStringToArrayBufferView (str) { + var bytes = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i) + } + + return bytes +} + +function convertArrayBufferViewtoString (buffer) { + var str = '' + for (var i = 0; i < buffer.byteLength; i++) { + str += String.fromCharCode(buffer[i]) + } + + return str +} + +function keyFromPassword (password) { + var passBuffer = convertStringToArrayBufferView(password) + return global.crypto.subtle.digest('SHA-256', passBuffer) + .then(function (passHash){ + return global.crypto.subtle.importKey('raw', passHash, {name: 'AES-GCM'}, false, ['encrypt', 'decrypt']) + }) +} + +function serializeBufferFromStorage (str) { + str = ethUtil.stripHexPrefix(str) + var buf = new Uint8Array(str.length / 2) + for (var i = 0; i < str.length; i += 2) { + var seg = str.substr(i, 2) + buf[i / 2] = parseInt(seg, 16) + } + return buf +} + +// Should return a string, ready for storage, in hex format. +function serializeBufferForStorage (buffer) { + var result = '0x' + var len = buffer.length || buffer.byteLength + for (var i = 0; i < len; i++) { + result += unprefixedHex(buffer[i]) + } + return result +} + +function unprefixedHex (num) { + var hex = num.toString(16) + while (hex.length < 2) { + hex = '0' + hex + } + return hex +} + +function encodeBufferToBase64 (buf) { + var b64encoded = btoa(String.fromCharCode.apply(null, buf)) + return b64encoded +} + +function decodeBase64ToBuffer (base64) { + var buf = new Uint8Array(atob(base64).split('') + .map(function(c) { + return c.charCodeAt(0) + })) + 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 +} diff --git a/app/scripts/lib/idStore.js b/app/scripts/lib/idStore.js index 9d0ca7f19..416b65b85 100644 --- a/app/scripts/lib/idStore.js +++ b/app/scripts/lib/idStore.js @@ -114,7 +114,6 @@ IdentityStore.prototype.getState = function () { conversionRate: configManager.getConversionRate(), conversionDate: configManager.getConversionDate(), gasMultiplier: configManager.getGasMultiplier(), - })) } diff --git a/app/scripts/lib/sig-util.js b/app/scripts/lib/sig-util.js new file mode 100644 index 000000000..f8748f535 --- /dev/null +++ b/app/scripts/lib/sig-util.js @@ -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 +} diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 8b593d820..c0da7cdaa 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -1,7 +1,7 @@ const extend = require('xtend') const EthStore = require('eth-store') const MetaMaskProvider = require('web3-provider-engine/zero.js') -const IdentityStore = require('./lib/idStore') +const KeyringController = require('./keyring-controller') const messageManager = require('./lib/message-manager') const HostStore = require('./lib/remote-store.js').HostStore const Web3 = require('web3') @@ -11,15 +11,17 @@ const extension = require('./lib/extension') module.exports = class MetamaskController { constructor (opts) { + this.state = { network: 'loading' } 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() @@ -30,19 +32,19 @@ module.exports = class MetamaskController { this.checkTOSChange() this.scheduleConversionInterval() - } getState () { 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()) }, @@ -57,22 +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), - recoverFromSeed: idStore.recoverFromSeed.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), - clearSeedWordCache: idStore.clearSeedWordCache.bind(idStore), - exportAccount: idStore.exportAccount.bind(idStore), - revealAccount: idStore.revealAccount.bind(idStore), - saveAccountLabel: idStore.saveAccountLabel.bind(idStore), - tryPassword: idStore.tryPassword.bind(idStore), - recoverSeed: idStore.recoverSeed.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 @@ -134,38 +133,38 @@ 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() }, } var provider = MetaMaskProvider(providerOpts) var web3 = new Web3(provider) - idStore.web3 = web3 - idStore.getNetwork() + this.web3 = web3 + keyringController.web3 = web3 provider.on('block', this.processBlock.bind(this)) - provider.on('error', idStore.getNetwork.bind(idStore)) + provider.on('error', this.getNetwork.bind(this)) return provider } @@ -173,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()) ) @@ -183,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, } @@ -211,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) @@ -231,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) @@ -242,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) } @@ -262,8 +263,8 @@ module.exports = class MetamaskController { verifyNetwork () { // Check network when restoring connectivity: - if (this.idStore._currentState.network === 'loading') { - this.idStore.getNetwork() + if (this.state.network === 'loading') { + this.getNetwork() } } @@ -346,13 +347,13 @@ module.exports = class MetamaskController { setRpcTarget (rpcTarget) { this.configManager.setRpcTarget(rpcTarget) extension.runtime.reload() - this.idStore.getNetwork() + this.getNetwork() } setProviderType (type) { this.configManager.setProviderType(type) extension.runtime.reload() - this.idStore.getNetwork() + this.getNetwork() } useEtherscanProvider () { @@ -363,7 +364,7 @@ module.exports = class MetamaskController { buyEth (address, amount) { if (!amount) amount = '5' - var network = this.idStore._currentState.network + var network = this.state.network var url = `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH` if (network === '2') { @@ -379,6 +380,25 @@ module.exports = class MetamaskController { this.configManager.createShapeShiftTx(depositAddress, depositType) } + getNetwork(err) { + if (err) { + this.state.network = 'loading' + this.sendUpdate() + } + + this.web3.version.getNetwork((err, network) => { + if (err) { + this.state.network = 'loading' + return this.sendUpdate() + } + if (global.METAMASK_DEBUG) { + console.log('web3.getNetwork returned ' + network) + } + this.state.network = network + this.sendUpdate() + }) + } + setGasMultiplier (gasMultiplier, cb) { try { this.configManager.setGasMultiplier(gasMultiplier) diff --git a/docs/multi_vault_planning.md b/docs/multi_vault_planning.md new file mode 100644 index 000000000..fdde2bc50 --- /dev/null +++ b/docs/multi_vault_planning.md @@ -0,0 +1,188 @@ +https://hackmd.io/JwIwDMDGKQZgtAFgKZjEgbARhPAhgKxZbwAcA7LAWOQCaKEgFA==?edit + +Subscribablez(initState) + .subscribe() + .emitUpdate(newState) + //.getState() + + +var initState = fromDisk() +ReduxStore(reducer, initState) +.reduce(action) -> .emitUpdate() + +ReduxStore.subscribe(toDisk) + + +### KeyChainManager / idStore 2.0 (maybe just in MetaMaskController) + keychains: [] + getAllAccounts(cb) + getAllKeychainViewStates(cb) -> returns [ KeyChainViewState] + +#### Old idStore external methods, for feature parity: + +- init(configManager) +- setStore(ethStore) +- getState() +- getSelectedAddres() +- setSelectedAddress() +- createNewVault() +- recoverFromSeed() +- submitPassword() +- approveTransaction() +- cancelTransaction() +- addUnconfirmedMessage(msgParams, cb) +- signMessage() +- cancelMessage() +- setLocked() +- clearSeedWordCache() +- exportAccount() +- revealAccount() +- saveAccountLabel() +- tryPassword() +- recoverSeed() +- getNetwork() + +##### Of those methods + +Where they should end up: + +##### MetaMaskController + +- getNetwork() + +##### KeyChainManager + +- init(configManager) +- setStore(ethStore) +- getState() // Deprecate for unidirectional flow +- on('update', cb) +- createNewVault(password) +- getSelectedAddres() +- setSelectedAddress() +- submitPassword() +- tryPassword() +- approveTransaction() +- cancelTransaction() +- signMessage() +- cancelMessage() +- setLocked() +- exportAccount() + +##### Bip44 KeyChain + +- getState() // Deprecate for unidirectional flow +- on('update', cb) + +If we adopt a ReactStore style unidirectional action dispatching data flow, these methods will be unified under a `dispatch` method, and rather than having a cb will emit an update to the UI: + +- createNewKeyChain(entropy) +- recoverFromSeed() +- approveTransaction() +- signMessage() +- clearSeedWordCache() +- exportAccount() +- revealAccount() +- saveAccountLabel() +- recoverSeed() + +Additional methods, new to this: +- serialize() + - Returns pojo with optional `secret` key whose contents will be encrypted with the users' password and salt when written to disk. + - The isolation of secrets is to preserve performance when decrypting user data. +- deserialize(pojo) + +### KeyChain (ReduxStore?) + // attributes + @name + + signTx(txParams, cb) + signMsg(msg, cb) + + getAddressList(cb) + + getViewState(cb) -> returns KeyChainViewState + + serialize(cb) -> obj + deserialize(obj) + + dispatch({ type: <str>, value: <pojo> }) + + +### KeyChainViewState + // The serialized, renderable keychain data + accountList: [], + typeName: 'uPort', + iconAddress: 'uport.gif', + internal: {} // Subclass-defined metadata + +### KeyChainReactComponent + // takes a KeyChainViewState + + // Subclasses of this: + - KeyChainListItemComponent + - KeyChainInitComponent - Maybe part of the List Item + - KeyChainAccountHeaderComponent + - KeyChainConfirmationComponent + // Account list item, tx confirmation extra data (like a QR code), + // Maybe an options screen, init screen, + + how to send actions? + emitAction(keychains.<id>.didInit) + + +gimmeRemoteKeychain((err, remoteKeychain)=> + +) + + + + + +KeyChainReactComponent({ + keychain +}) + +Keychain: + methods:{}, + cachedAccountList: [], + name: '', + + +CoinbaseKeychain + getAccountList + + +CoinbaseKeychainComponent + isLoading = true + keychain.getAccountList(()=>{ + isLoading=false + accountList=accounts + }) + + + + + +KeyChainViewState { + attributes: { + //mandatory: + accountList: [], + typeName: 'uPort', + iconAddress: 'uport.gif', + + internal: { + // keychain-specific metadata + proxyAddresses: { + 0xReal: '0xProxy' + } + }, + }, + methods: { + // arbitrary, internal + } +} + +## A note on the security of arbitrary action dispatchers + +Since keychains will be dispatching actions that are then passed through the background process to be routed, we should not trust or require them to include their own keychain ID as a prefix to their action, but we should tack it on ourselves, so that no action dispatched by a KeyChainComponent ever reaches any KeyChain other than its own. + diff --git a/ui/app/first-time/create-vault-complete.js b/keychains/bip44/create-vault-complete.js index 2b5413955..2b5413955 100644 --- a/ui/app/first-time/create-vault-complete.js +++ b/keychains/bip44/create-vault-complete.js diff --git a/ui/app/recover-seed/confirmation.js b/keychains/bip44/recover-seed/confirmation.js index 55b18025f..55b18025f 100644 --- a/ui/app/recover-seed/confirmation.js +++ b/keychains/bip44/recover-seed/confirmation.js diff --git a/ui/app/first-time/restore-vault.js b/keychains/bip44/restore-vault.js index 4c1f21008..4c1f21008 100644 --- a/ui/app/first-time/restore-vault.js +++ b/keychains/bip44/restore-vault.js diff --git a/mock-dev.js b/mock-dev.js index 99b846e51..99aec9a65 100644 --- a/mock-dev.js +++ b/mock-dev.js @@ -107,7 +107,7 @@ function getOldStyleData () { return result } -actions._setAccountManager(controller.getApi()) +actions._setBackgroundConnection(controller.getApi()) actions.update = function(stateName) { selectedView = stateName updateQueryParams(stateName) diff --git a/package.json b/package.json index 2af0aebfc..bb472a8fe 100644 --- a/package.json +++ b/package.json @@ -4,9 +4,10 @@ "public": false, "private": true, "scripts": { - "start": "gulp dev", + "start": "npm run dev", "lint": "gulp lint", - "dev": "gulp dev", + "buildCiUnits": "node test/integration/index.js", + "dev": "gulp dev --debug", "dist": "gulp dist --disableLiveReload", "test": "npm run fastTest && npm run ci && npm run lint", "fastTest": "mocha --require test/helper.js --compilers js:babel-register --recursive \"test/unit/**/*.js\"", @@ -15,7 +16,7 @@ "mock": "beefy mock-dev.js:bundle.js --live --open --index=./development/index.html --cwd ./", "buildMock": "browserify ./mock-dev.js -o ./development/bundle.js", "testem": "npm run buildMock && testem", - "ci": "npm run buildMock && testem ci -P 2", + "ci": "npm run buildMock && npm run buildCiUnits && testem ci -P 2", "announce": "node development/announcer.js" }, "browserify": { @@ -46,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", diff --git a/test/integration/index.html b/test/integration/index.html index 6de40b046..ad4b4eb14 100644 --- a/test/integration/index.html +++ b/test/integration/index.html @@ -12,7 +12,7 @@ <script src="https://code.jquery.com/qunit/qunit-2.0.0.js"></script> <script src="./jquery-3.1.0.min.js"></script> <script src="helpers.js"></script> - <script src="tests.js"></script> + <script src="bundle.js"></script> <script src="/testem.js"></script> <iframe src="/development/index.html" height="500px" width="360px"> diff --git a/test/integration/index.js b/test/integration/index.js new file mode 100644 index 000000000..ff6d1baf8 --- /dev/null +++ b/test/integration/index.js @@ -0,0 +1,21 @@ +var fs = require('fs') +var path = require('path') +var browserify = require('browserify'); +var tests = fs.readdirSync(path.join(__dirname, 'lib')) +var bundlePath = path.join(__dirname, 'bundle.js') + +var b = browserify(); + +// Remove old bundle +try { + fs.unlinkSync(bundlePath) +} catch (e) {} + +var writeStream = fs.createWriteStream(bundlePath) + +tests.forEach(function(fileName) { + b.add(path.join(__dirname, 'lib', fileName)) +}) + +b.bundle().pipe(writeStream); + diff --git a/test/integration/lib/encryptor-test.js b/test/integration/lib/encryptor-test.js new file mode 100644 index 000000000..1c8a7605a --- /dev/null +++ b/test/integration/lib/encryptor-test.js @@ -0,0 +1,45 @@ +var encryptor = require('../../../app/scripts/lib/encryptor') + +QUnit.test('encryptor:serializeBufferForStorage', function (assert) { + assert.expect(1) + var buf = new Buffer(2) + buf[0] = 16 + buf[1] = 1 + + var output = encryptor.serializeBufferForStorage(buf) + + var expect = '0x1001' + assert.equal(expect, output) +}) + +QUnit.test('encryptor:serializeBufferFromStorage', function (assert) { + assert.expect(2) + var input = '0x1001' + var output = encryptor.serializeBufferFromStorage(input) + + assert.equal(output[0], 16) + assert.equal(output[1], 1) +}) + +QUnit.test('encryptor:encrypt & decrypt', function(assert) { + var done = assert.async(); + var password, data, encrypted + + password = 'a sample passw0rd' + data = { foo: 'data to encrypt' } + + encryptor.encrypt(password, data) + .then(function(encryptedStr) { + assert.equal(typeof encryptedStr, 'string', 'returns a string') + return encryptor.decrypt(password, encryptedStr) + }) + .then(function (decryptedObj) { + assert.deepEqual(decryptedObj, data, 'decrypted what was encrypted') + done() + }) + .catch(function(reason) { + assert.ifError(reason, 'threw an error') + done(reason) + }) + +}) diff --git a/test/integration/tests.js b/test/integration/lib/first-time.js index 92111b05b..af9b94e24 100644 --- a/test/integration/tests.js +++ b/test/integration/lib/first-time.js @@ -15,10 +15,11 @@ QUnit.test('agree to terms', function (assert) { assert.equal(title, 'MetaMask', 'title screen') var buttons = app.find('button') - assert.equal(buttons.length, 2, 'two buttons: create and restore') + assert.equal(buttons.length, 1, 'one button: create new vault') done() }) // Wait for view to transition: }) + diff --git a/test/lib/mock-encryptor.js b/test/lib/mock-encryptor.js new file mode 100644 index 000000000..09bbf7ad5 --- /dev/null +++ b/test/lib/mock-encryptor.js @@ -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!' + }, + +} diff --git a/test/lib/mock-simple-keychain.js b/test/lib/mock-simple-keychain.js new file mode 100644 index 000000000..615b3e537 --- /dev/null +++ b/test/lib/mock-simple-keychain.js @@ -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) + } + +} diff --git a/test/unit/actions/restore_vault_test.js b/test/unit/actions/restore_vault_test.js deleted file mode 100644 index 609f5429e..000000000 --- a/test/unit/actions/restore_vault_test.js +++ /dev/null @@ -1,60 +0,0 @@ -var jsdom = require('mocha-jsdom') -var assert = require('assert') -var freeze = require('deep-freeze-strict') -var path = require('path') -var sinon = require('sinon') - -var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js')) -var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js')) - -describe('#recoverFromSeed(password, seed)', function() { - - beforeEach(function() { - // sinon allows stubbing methods that are easily verified - this.sinon = sinon.sandbox.create() - }) - - afterEach(function() { - // sinon requires cleanup otherwise it will overwrite context - this.sinon.restore() - }) - - // stub out account manager - actions._setAccountManager({ - recoverFromSeed(pw, seed, cb) { - cb(null, { - identities: { - foo: 'bar' - } - }) - }, - }) - - it('sets metamask.isUnlocked to true', function() { - var initialState = { - metamask: { - isUnlocked: false, - isInitialized: false, - } - } - freeze(initialState) - - const restorePhrase = 'invite heavy among daring outdoor dice jelly coil stable note seat vicious' - const password = 'foo' - const dispatchFunc = actions.recoverFromSeed(password, restorePhrase) - - var dispatchStub = this.sinon.stub() - dispatchStub.withArgs({ TYPE: actions.unlockMetamask() }).onCall(0) - dispatchStub.withArgs({ TYPE: actions.showAccountsPage() }).onCall(1) - - var action - var resultingState = initialState - dispatchFunc((newAction) => { - action = newAction - resultingState = reducers(resultingState, action) - }) - - assert.equal(resultingState.metamask.isUnlocked, true, 'was unlocked') - assert.equal(resultingState.metamask.isInitialized, true, 'was initialized') - }); -}); diff --git a/test/unit/actions/tx_test.js b/test/unit/actions/tx_test.js index c08a8aa26..1f06b1120 100644 --- a/test/unit/actions/tx_test.js +++ b/test/unit/actions/tx_test.js @@ -46,7 +46,7 @@ describe('tx confirmation screen', function() { describe('cancelTx', function() { before(function(done) { - actions._setAccountManager({ + actions._setBackgroundConnection({ approveTransaction(txId, cb) { cb('An error!') }, cancelTransaction(txId) { /* noop */ }, clearSeedWordCache(cb) { cb() }, @@ -75,7 +75,7 @@ describe('tx confirmation screen', function() { before(function(done) { alert = () => {/* noop */} - actions._setAccountManager({ + actions._setBackgroundConnection({ approveTransaction(txId, cb) { cb({message: 'An error!'}) }, }) @@ -96,7 +96,7 @@ describe('tx confirmation screen', function() { describe('when there is success', function() { it('should complete tx and go home', function() { - actions._setAccountManager({ + actions._setBackgroundConnection({ approveTransaction(txId, cb) { cb() }, }) @@ -135,7 +135,7 @@ describe('tx confirmation screen', function() { } freeze(initialState) - actions._setAccountManager({ + actions._setBackgroundConnection({ approveTransaction(txId, cb) { cb() }, }) diff --git a/test/unit/keyring-controller-test.js b/test/unit/keyring-controller-test.js new file mode 100644 index 000000000..e216b0960 --- /dev/null +++ b/test/unit/keyring-controller-test.js @@ -0,0 +1,83 @@ +var assert = require('assert') +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 () { + 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() + }) + + }) + +}) + + + + + diff --git a/test/unit/keyrings/simple-test.js b/test/unit/keyrings/simple-test.js new file mode 100644 index 000000000..ba000a7a8 --- /dev/null +++ b/test/unit/keyrings/simple-test.js @@ -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) + }) + }) +}) diff --git a/testem.yml b/testem.yml index 7923a2929..2cf40f7f4 100644 --- a/testem.yml +++ b/testem.yml @@ -6,4 +6,5 @@ launch_in_ci: - Firefox framework: - qunit +before_tests: "npm run buildCiUnits" test_page: "test/integration/index.html" @@ -41,7 +41,7 @@ function updateQueryParams(newView) { } const actions = { - _setAccountManager(){}, + _setBackgroundConnection(){}, update: function(stateName) { selectedView = stateName updateQueryParams(stateName) diff --git a/ui/app/accounts/index.js b/ui/app/accounts/index.js index 7551c498e..92054f24d 100644 --- a/ui/app/accounts/index.js +++ b/ui/app/accounts/index.js @@ -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 () { diff --git a/ui/app/actions.js b/ui/app/actions.js index 1f0d8fc78..525ceca54 100644 --- a/ui/app/actions.js +++ b/ui/app/actions.js @@ -1,4 +1,6 @@ var actions = { + _setBackgroundConnection: _setBackgroundConnection, + GO_HOME: 'GO_HOME', goHome: goHome, // menu state @@ -16,10 +18,6 @@ var actions = { SHOW_INIT_MENU: 'SHOW_INIT_MENU', SHOW_NEW_VAULT_SEED: 'SHOW_NEW_VAULT_SEED', SHOW_INFO_PAGE: 'SHOW_INFO_PAGE', - RECOVER_FROM_SEED: 'RECOVER_FROM_SEED', - CLEAR_SEED_WORD_CACHE: 'CLEAR_SEED_WORD_CACHE', - clearSeedWordCache: clearSeedWordCache, - recoverFromSeed: recoverFromSeed, unlockMetamask: unlockMetamask, unlockFailed: unlockFailed, showCreateVault: showCreateVault, @@ -27,12 +25,9 @@ var actions = { showInitializeMenu: showInitializeMenu, createNewVault: createNewVault, createNewVaultInProgress: createNewVaultInProgress, + addNewKeyring: addNewKeyring, showNewVaultSeed: showNewVaultSeed, showInfoPage: showInfoPage, - // seed recovery actions - REVEAL_SEED_CONFIRMATION: 'REVEAL_SEED_CONFIRMATION', - revealSeedConfirmation: revealSeedConfirmation, - requestRevealSeed: requestRevealSeed, // unlock screen UNLOCK_IN_PROGRESS: 'UNLOCK_IN_PROGRESS', UNLOCK_FAILED: 'UNLOCK_FAILED', @@ -53,8 +48,6 @@ var actions = { SHOW_ACCOUNTS_PAGE: 'SHOW_ACCOUNTS_PAGE', SHOW_CONF_TX_PAGE: 'SHOW_CONF_TX_PAGE', SHOW_CONF_MSG_PAGE: 'SHOW_CONF_MSG_PAGE', - REVEAL_ACCOUNT: 'REVEAL_ACCOUNT', - revealAccount: revealAccount, SET_CURRENT_FIAT: 'SET_CURRENT_FIAT', setCurrentFiat: setCurrentFiat, // account detail screen @@ -95,7 +88,6 @@ var actions = { backToAccountDetail: backToAccountDetail, showAccountsPage: showAccountsPage, showConfTxPage: showConfTxPage, - confirmSeedWords: confirmSeedWords, // config screen SHOW_CONFIG_PAGE: 'SHOW_CONFIG_PAGE', SET_RPC_TARGET: 'SET_RPC_TARGET', @@ -105,8 +97,6 @@ var actions = { showConfigPage: showConfigPage, setRpcTarget: setRpcTarget, setProviderType: setProviderType, - // hacky - need a way to get a reference to account manager - _setAccountManager: _setAccountManager, // loading overlay SHOW_LOADING: 'SHOW_LOADING_INDICATION', HIDE_LOADING: 'HIDE_LOADING_INDICATION', @@ -143,13 +133,18 @@ var actions = { RECOVERY_IN_PROGRESS: 'RECOVERY_IN_PROGRESS', BACK_TO_UNLOCK_VIEW: 'BACK_TO_UNLOCK_VIEW', backToUnlockView: backToUnlockView, + // SHOWING KEYCHAIN + SHOW_NEW_KEYCHAIN: 'SHOW_NEW_KEYCHAIN', + showNewKeychain: showNewKeychain, + + } module.exports = actions -var _accountManager = null -function _setAccountManager (accountManager) { - _accountManager = accountManager +var background = null +function _setBackgroundConnection(backgroundConnection) { + background = backgroundConnection } function goHome () { @@ -164,11 +159,16 @@ function tryUnlockMetamask (password) { return (dispatch) => { dispatch(actions.showLoadingIndication()) dispatch(actions.unlockInProgress()) - _accountManager.submitPassword(password, (err, selectedAccount) => { + background.submitPassword(password, (err, newState) => { dispatch(actions.hideLoadingIndication()) if (err) { dispatch(actions.unlockFailed()) } else { + dispatch(this.updateMetamaskState(newState)) + let selectedAccount + try { + selectedAccount = newState.metamask.selectedAccount + } catch (e) {} dispatch(actions.unlockMetamask(selectedAccount)) } }) @@ -178,45 +178,27 @@ function tryUnlockMetamask (password) { function createNewVault (password, entropy) { return (dispatch) => { dispatch(actions.createNewVaultInProgress()) - _accountManager.createNewVault(password, entropy, (err, result) => { + background.createNewVault(password, entropy, (err, newState) => { if (err) { return dispatch(actions.showWarning(err.message)) } - dispatch(actions.showNewVaultSeed(result)) - }) - } -} - -function revealSeedConfirmation () { - return { - type: this.REVEAL_SEED_CONFIRMATION, - } -} - -function requestRevealSeed (password) { - return (dispatch) => { - dispatch(actions.showLoadingIndication()) - _accountManager.tryPassword(password, (err, seed) => { - dispatch(actions.hideLoadingIndication()) - if (err) return dispatch(actions.displayWarning(err.message)) - _accountManager.recoverSeed((err, seed) => { - if (err) return dispatch(actions.displayWarning(err.message)) - dispatch(actions.showNewVaultSeed(seed)) - }) + dispatch(this.updateMetamaskState(newState)) + dispatch(this.showAccountsPage()) + dispatch(this.hideLoadingIndication()) }) } } -function recoverFromSeed (password, seed) { +function addNewKeyring (type, opts) { return (dispatch) => { - // dispatch(actions.createNewVaultInProgress()) dispatch(actions.showLoadingIndication()) - _accountManager.recoverFromSeed(password, seed, (err, metamaskState) => { - dispatch(actions.hideLoadingIndication()) - if (err) return dispatch(actions.displayWarning(err.message)) - - var account = Object.keys(metamaskState.identities)[0] - dispatch(actions.unlockMetamask(account)) + background.addNewKeyring(type, opts, (err, newState) => { + dispatch(this.hideLoadingIndication()) + if (err) { + return dispatch(actions.showWarning(err)) + } + dispatch(this.updateMetamaskState(newState)) + dispatch(this.showAccountsPage()) }) } } @@ -229,27 +211,14 @@ function showInfoPage () { function setSelectedAddress (address) { return (dispatch) => { - _accountManager.setSelectedAddress(address) - } -} - -function revealAccount () { - return (dispatch) => { - dispatch(actions.showLoadingIndication()) - _accountManager.revealAccount((err) => { - dispatch(actions.hideLoadingIndication()) - if (err) return dispatch(actions.displayWarning(err.message)) - dispatch({ - type: actions.REVEAL_ACCOUNT, - }) - }) + background.setSelectedAddress(address) } } function setCurrentFiat (fiat) { return (dispatch) => { dispatch(this.showLoadingIndication()) - _accountManager.setCurrentFiat(fiat, (data, err) => { + background.setCurrentFiat(fiat, (data, err) => { dispatch(this.hideLoadingIndication()) dispatch({ type: this.SET_CURRENT_FIAT, @@ -267,7 +236,7 @@ function signMsg (msgData) { return (dispatch) => { dispatch(actions.showLoadingIndication()) - _accountManager.signMessage(msgData, (err) => { + background.signMessage(msgData, (err) => { dispatch(actions.hideLoadingIndication()) if (err) return dispatch(actions.displayWarning(err.message)) @@ -278,7 +247,7 @@ function signMsg (msgData) { function signTx (txData) { return (dispatch) => { - _accountManager.setGasMultiplier(txData.gasMultiplier, (err) => { + background.setGasMultiplier(txData.gasMultiplier, (err) => { if (err) return dispatch(actions.displayWarning(err.message)) web3.eth.sendTransaction(txData, (err, data) => { dispatch(actions.hideLoadingIndication()) @@ -293,7 +262,7 @@ function signTx (txData) { function sendTx (txData) { return (dispatch) => { - _accountManager.approveTransaction(txData.id, (err) => { + background.approveTransaction(txData.id, (err) => { if (err) { alert(err.message) dispatch(actions.txError(err)) @@ -319,12 +288,12 @@ function txError (err) { } function cancelMsg (msgData) { - _accountManager.cancelMessage(msgData.id) + background.cancelMessage(msgData.id) return actions.completedTx(msgData.id) } function cancelTx (txData) { - _accountManager.cancelTransaction(txData.id) + background.cancelTransaction(txData.id) return actions.completedTx(txData.id) } @@ -353,7 +322,7 @@ function showInitializeMenu () { function agreeToDisclaimer () { return (dispatch) => { dispatch(this.showLoadingIndication()) - _accountManager.agreeToDisclaimer((err) => { + background.agreeToDisclaimer((err) => { if (err) { return dispatch(actions.showWarning(err.message)) } @@ -385,6 +354,12 @@ function backToUnlockView () { } } +function showNewKeychain () { + return { + type: actions.SHOW_NEW_KEYCHAIN, + } +} + // // unlock screen // @@ -417,7 +392,7 @@ function updateMetamaskState (newState) { function lockMetamask () { return (dispatch) => { - _accountManager.setLocked((err) => { + background.setLocked((err) => { dispatch(actions.hideLoadingIndication()) if (err) { return dispatch(actions.showWarning(err.message)) @@ -433,7 +408,7 @@ function lockMetamask () { function showAccountDetail (address) { return (dispatch) => { dispatch(actions.showLoadingIndication()) - _accountManager.setSelectedAddress(address, (err, address) => { + background.setSelectedAddress(address, (err, address) => { dispatch(actions.hideLoadingIndication()) if (err) { return dispatch(actions.showWarning(err.message)) @@ -453,27 +428,6 @@ function backToAccountDetail (address) { value: address, } } -function clearSeedWordCache (account) { - return { - type: actions.CLEAR_SEED_WORD_CACHE, - value: account, - } -} - -function confirmSeedWords () { - return (dispatch) => { - dispatch(actions.showLoadingIndication()) - _accountManager.clearSeedWordCache((err, account) => { - dispatch(actions.hideLoadingIndication()) - if (err) { - return dispatch(actions.showWarning(err.message)) - } - - console.log('Seed word cache cleared. ' + account) - dispatch(actions.showAccountDetail(account)) - }) - } -} function showAccountsPage () { return { @@ -525,7 +479,7 @@ function goBackToInitView () { // function setRpcTarget (newRpc) { - _accountManager.setRpcTarget(newRpc) + background.setRpcTarget(newRpc) return { type: actions.SET_RPC_TARGET, value: newRpc, @@ -533,7 +487,7 @@ function setRpcTarget (newRpc) { } function setProviderType (type) { - _accountManager.setProviderType(type) + background.setProviderType(type) return { type: actions.SET_PROVIDER_TYPE, value: type, @@ -541,7 +495,7 @@ function setProviderType (type) { } function useEtherscanProvider () { - _accountManager.useEtherscanProvider() + background.useEtherscanProvider() return { type: actions.USE_ETHERSCAN_PROVIDER, } @@ -600,7 +554,7 @@ function exportAccount (address) { return function (dispatch) { dispatch(self.showLoadingIndication()) - _accountManager.exportAccount(address, function (err, result) { + background.exportAccount(address, function (err, result) { dispatch(self.hideLoadingIndication()) if (err) { @@ -623,7 +577,7 @@ function showPrivateKey (key) { function saveAccountLabel (account, label) { return (dispatch) => { dispatch(actions.showLoadingIndication()) - _accountManager.saveAccountLabel(account, label, (err) => { + background.saveAccountLabel(account, label, (err) => { dispatch(actions.hideLoadingIndication()) if (err) { return dispatch(actions.showWarning(err.message)) @@ -644,7 +598,7 @@ function showSendPage () { function agreeToEthWarning () { return (dispatch) => { - _accountManager.agreeToEthWarning((err) => { + background.agreeToEthWarning((err) => { if (err) { return dispatch(actions.showEthWarning(err.message)) } @@ -663,7 +617,7 @@ function showEthWarning () { function buyEth (address, amount) { return (dispatch) => { - _accountManager.buyEth(address, amount) + background.buyEth(address, amount) dispatch({ type: actions.BUY_ETH, }) @@ -741,7 +695,7 @@ function coinShiftRquest (data, marketData) { if (response.error) return dispatch(actions.showWarning(response.error)) var message = ` Deposit your ${response.depositType} to the address bellow:` - _accountManager.createShapeShiftTx(response.deposit, response.depositType) + background.createShapeShiftTx(response.deposit, response.depositType) dispatch(actions.showQrView(response.deposit, [message].concat(marketData))) }) } diff --git a/ui/app/app.js b/ui/app/app.js index 71e0637d0..a1004b74b 100644 --- a/ui/app/app.js +++ b/ui/app/app.js @@ -8,8 +8,7 @@ const ReactCSSTransitionGroup = require('react-addons-css-transition-group') const DisclaimerScreen = require('./first-time/disclaimer') const InitializeMenuScreen = require('./first-time/init-menu') const CreateVaultScreen = require('./first-time/create-vault') -const CreateVaultCompleteScreen = require('./first-time/create-vault-complete') -const RestoreVaultScreen = require('./first-time/restore-vault') +const NewKeyChainScreen = require('./new-keychain') // unlock const UnlockScreen = require('./unlock') // accounts @@ -19,7 +18,6 @@ const SendTransactionScreen = require('./send') const ConfirmTxScreen = require('./conf-tx') // other views const ConfigScreen = require('./config') -const RevealSeedConfirmation = require('./recover-seed/confirmation') const InfoScreen = require('./info') const LoadingIndicator = require('./components/loading') const SandwichExpando = require('sandwich-expando') @@ -402,24 +400,14 @@ App.prototype.renderPrimary = function () { return h(DisclaimerScreen, {key: 'disclaimerScreen'}) } - if (props.seedWords) { - return h(CreateVaultCompleteScreen, {key: 'createVaultComplete'}) - } - // show initialize screen if (!props.isInitialized || props.forgottenPassword) { + // show current view switch (props.currentView.name) { - case 'createVault': return h(CreateVaultScreen, {key: 'createVault'}) - case 'restoreVault': - return h(RestoreVaultScreen, {key: 'restoreVault'}) - - case 'createVaultComplete': - return h(CreateVaultCompleteScreen, {key: 'createVaultComplete'}) - default: return h(InitializeMenuScreen, {key: 'menuScreenInit'}) @@ -445,22 +433,24 @@ App.prototype.renderPrimary = function () { case 'sendTransaction': return h(SendTransactionScreen, {key: 'send-transaction'}) + case 'newKeychain': + return h(NewKeyChainScreen, {key: 'new-keychain'}) + case 'confTx': return h(ConfirmTxScreen, {key: 'confirm-tx'}) case 'config': return h(ConfigScreen, {key: 'config'}) - case 'reveal-seed-conf': - return h(RevealSeedConfirmation, {key: 'reveal-seed-conf'}) - case 'info': return h(InfoScreen, {key: 'info'}) case 'createVault': return h(CreateVaultScreen, {key: 'createVault'}) + case 'buyEth': return h(BuyView, {key: 'buyEthView'}) + case 'qr': return h('div', { style: { @@ -511,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, { diff --git a/ui/app/config.js b/ui/app/config.js index e09a38cd8..d4730e558 100644 --- a/ui/app/config.js +++ b/ui/app/config.js @@ -77,22 +77,6 @@ ConfigScreen.prototype.render = function () { currentConversionInformation(metamaskState, state), h('hr.horizontal-line'), - h('div', { - style: { - marginTop: '20px', - }, - }, [ - h('button', { - style: { - alignSelf: 'center', - }, - onClick (event) { - event.preventDefault() - state.dispatch(actions.revealSeedConfirmation()) - }, - }, 'Reveal Seed Words'), - ]), - ]), ]), ]) diff --git a/ui/app/first-time/init-menu.js b/ui/app/first-time/init-menu.js index 94a9d3df6..4fdade469 100644 --- a/ui/app/first-time/init-menu.js +++ b/ui/app/first-time/init-menu.js @@ -61,35 +61,19 @@ InitializeMenuScreen.prototype.renderMenu = function () { }, }, 'Create New Vault'), + /* h('.flex-row.flex-center.flex-grow', [ h('hr'), - h('div', 'OR'), + h('div', 'Advanced (Eventually?)'), h('hr'), ]), + */ - h('button.primary', { - onClick: this.showRestoreVault.bind(this), - style: { - margin: 12, - }, - }, 'Restore Existing Vault'), ]) ) } -// InitializeMenuScreen.prototype.splitWor = function() { -// this.props.dispatch(actions.showInitializeMenu()) -// } - -InitializeMenuScreen.prototype.showInitializeMenu = function () { - this.props.dispatch(actions.showInitializeMenu()) -} - InitializeMenuScreen.prototype.showCreateVault = function () { this.props.dispatch(actions.showCreateVault()) } -InitializeMenuScreen.prototype.showRestoreVault = function () { - this.props.dispatch(actions.showRestoreVault()) -} - diff --git a/ui/app/new-keychain.js b/ui/app/new-keychain.js new file mode 100644 index 000000000..cc9633166 --- /dev/null +++ b/ui/app/new-keychain.js @@ -0,0 +1,29 @@ +const inherits = require('util').inherits +const Component = require('react').Component +const h = require('react-hyperscript') +const connect = require('react-redux').connect + +module.exports = connect(mapStateToProps)(NewKeychain) + +function mapStateToProps (state) { + return {} +} + +inherits(NewKeychain, Component) +function NewKeychain () { + Component.call(this) +} + +NewKeychain.prototype.render = function () { + // const props = this.props + + return ( + h('div', { + style: { + background: 'blue', + }, + }, [ + h('h1', `Here's a list!!!!`), + ]) + ) +} diff --git a/ui/app/reducers/app.js b/ui/app/reducers/app.js index c2ac099a6..5b3f44d68 100644 --- a/ui/app/reducers/app.js +++ b/ui/app/reducers/app.js @@ -119,6 +119,15 @@ function reduceApp (state, action) { warning: null, }) + case actions.SHOW_NEW_KEYCHAIN: + return extend(appState, { + currentView: { + name: 'newKeychain', + context: appState.currentView.context, + }, + transForward: true, + }) + // unlock case actions.UNLOCK_METAMASK: @@ -540,4 +549,3 @@ function indexForPending (state, txId) { }) return idx } - diff --git a/ui/index.js b/ui/index.js index a6905b639..dedfd8c8c 100644 --- a/ui/index.js +++ b/ui/index.js @@ -8,7 +8,7 @@ module.exports = launchApp function launchApp (opts) { var accountManager = opts.accountManager - actions._setAccountManager(accountManager) + actions._setBackgroundConnection(accountManager) // check if we are unlocked first accountManager.getState(function (err, metamaskState) { |