diff options
28 files changed, 812 insertions, 182 deletions
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/keyring-controller.js b/app/scripts/keyring-controller.js new file mode 100644 index 000000000..db7e5e61e --- /dev/null +++ b/app/scripts/keyring-controller.js @@ -0,0 +1,134 @@ +const EventEmitter = require('events').EventEmitter +const encryptor = require('./lib/encryptor') +const messageManager = require('./lib/message-manager') + + +module.exports = class KeyringController extends EventEmitter { + + constructor (opts) { + super() + this.configManager = opts.configManager + this.ethStore = opts.ethStore + this.keyChains = [] + } + + keyFromPassword(password, callback) { + deriveKeyFromPassword(password, callback); + } + + // Takes a pw and callback, returns a password-dervied key + getKeyForPassword(password, callback) { + let salt = this.configManager.getSalt() + + if (!salt) { + salt = generateSalt(32) + this.configManager.setSalt(salt) + } + + var logN = 14 + var r = 8 + var dkLen = 32 + var interruptStep = 200 + + var cb = function(derKey) { + try { + var ui8arr = (new Uint8Array(derKey)) + this.pwDerivedKey = ui8arr + callback(null, ui8arr) + } catch (err) { + callback(err) + } + } + + scrypt(password, salt, logN, r, dkLen, interruptStep, cb, null) + } + + getState() { + return { + isInitialized: !!this.key, + isUnlocked: !!this.key, + isConfirmed: true, // 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(), + } + } + + setStore(ethStore) { + this.ethStore = ethStore + } + + createNewVault(password, entropy, cb) { + encryptor.keyFromPassword(password) + .then((key) => { + this.key = key + return encryptor.encryptWithKey(key, {}) + }) + .then((encryptedString) => { + this.configManager.setVault(encryptedString) + cb(null, []) + }) + .catch((err) => { + cb(err) + }) + } + + + + submitPassword(password, cb) { + cb() + } + + setSelectedAddress(address, cb) { + this.selectedAddress = address + cb(null, address) + } + + approveTransaction(txId, cb) { + cb() + } + + cancelTransaction(txId, cb) { + if (cb && typeof cb === 'function') { + cb() + } + } + + signMessage(msgParams, cb) { + cb() + } + + cancelMessage(msgId, cb) { + if (cb && typeof cb === 'function') { + cb() + } + } + + setLocked(cb) { + cb() + } + + exportAccount(address, cb) { + cb(null, '0xPrivateKey') + } + + saveAccountLabel(account, label, cb) { + cb(/* null, label */) + } + + tryPassword(password, cb) { + cb() + } + +} + +function generateSalt (byteCount) { + return bitcore.crypto.Random.getRandomBuffer(byteCount || 32).toString('base64') +} diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js index cced32670..d12304c46 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..91d6ed5ce --- /dev/null +++ b/app/scripts/lib/encryptor.js @@ -0,0 +1,119 @@ +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, +} + +// 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 = serializeBufferForStorage(vector) + return serializeBufferForStorage(buffer) + 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('0x') + const encryptedData = serializeBufferFromStorage(parts[1]) + const vector = serializeBufferFromStorage(parts[2]) + 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 +} diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 8b593d820..92551d633 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 IdentityStore = require('./keyring-controller') const messageManager = require('./lib/message-manager') const HostStore = require('./lib/remote-store.js').HostStore const Web3 = require('web3') @@ -11,6 +11,7 @@ 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) @@ -20,6 +21,7 @@ module.exports = class MetamaskController { this.provider = this.initializeProvider(opts) this.ethStore = new EthStore(this.provider) this.idStore.setStore(this.ethStore) + this.getNetwork() this.messageManager = messageManager this.publicConfigStore = this.initPublicConfigStore() @@ -30,11 +32,11 @@ module.exports = class MetamaskController { this.checkTOSChange() this.scheduleConversionInterval() - } getState () { return extend( + this.state, this.ethStore.getState(), this.idStore.getState(), this.configManager.getConfig() @@ -59,7 +61,6 @@ module.exports = class MetamaskController { // 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), @@ -67,12 +68,9 @@ module.exports = class MetamaskController { 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), // coinbase buyEth: this.buyEth.bind(this), // shapeshift @@ -161,11 +159,11 @@ module.exports = class MetamaskController { var provider = MetaMaskProvider(providerOpts) var web3 = new Web3(provider) + this.web3 = web3 idStore.web3 = web3 - idStore.getNetwork() provider.on('block', this.processBlock.bind(this)) - provider.on('error', idStore.getNetwork.bind(idStore)) + provider.on('error', this.getNetwork.bind(this)) return provider } @@ -262,8 +260,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 +344,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 +361,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 +377,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..d3f364d69 100644 --- a/mock-dev.js +++ b/mock-dev.js @@ -107,7 +107,7 @@ function getOldStyleData () { return result } -actions._setAccountManager(controller.getApi()) +actions._setKeyringController(controller.getApi()) actions.update = function(stateName) { selectedView = stateName updateQueryParams(stateName) diff --git a/package.json b/package.json index 2af0aebfc..e29ef5185 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "scripts": { "start": "gulp 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": { 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..88ebed51b --- /dev/null +++ b/test/integration/lib/encryptor-test.js @@ -0,0 +1,44 @@ +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') + }) + +}) 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/unit/actions/restore_vault_test.js b/test/unit/actions/restore_vault_test.js index 609f5429e..7202abb70 100644 --- a/test/unit/actions/restore_vault_test.js +++ b/test/unit/actions/restore_vault_test.js @@ -20,7 +20,7 @@ describe('#recoverFromSeed(password, seed)', function() { }) // stub out account manager - actions._setAccountManager({ + actions._setKeyringController({ recoverFromSeed(pw, seed, cb) { cb(null, { identities: { diff --git a/test/unit/actions/tx_test.js b/test/unit/actions/tx_test.js index c08a8aa26..e365ee3a3 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._setKeyringController({ 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._setKeyringController({ 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._setKeyringController({ approveTransaction(txId, cb) { cb() }, }) @@ -135,7 +135,7 @@ describe('tx confirmation screen', function() { } freeze(initialState) - actions._setAccountManager({ + actions._setKeyringController({ 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..854ac5212 --- /dev/null +++ b/test/unit/keyring-controller-test.js @@ -0,0 +1,141 @@ +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') + +describe('KeyringController', function() { + + 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 + done() + }) + }) + + describe('#recoverFromSeed', function() { + let newAccounts = [] + + before(function() { + window.localStorage = {} // Hacking localStorage support into JSDom + + keyringController = new KeyringController({ + configManager: configManagerGen(), + ethStore: { + addAccount(acct) { newAccounts.push(ethUtil.addHexPrefix(acct)) }, + }, + }) + }) + + it('should return the expected keystore', function (done) { + + keyringController.recoverFromSeed(password, seedWords, (err) => { + assert.ifError(err) + + let newKeystore = keyringController._idmgmt.keyStore + assert.equal(newAccounts[0], accounts[0]) + done() + }) + }) + }) + }) + + describe('#recoverFromSeed BIP44 compliance', function() { + const salt = 'lightwalletSalt' + + let password = 'secret!' + let accounts = {} + let keyringController + + var assertions = [ + { + seed: 'picnic injury awful upper eagle junk alert toss flower renew silly vague', + account: '0x5d8de92c205279c10e5669f797b853ccef4f739a', + }, + { + seed: 'radar blur cabbage chef fix engine embark joy scheme fiction master release', + account: '0xe15d894becb0354c501ae69429b05143679f39e0', + }, + { + seed: 'phone coyote caught pattern found table wedding list tumble broccoli chief swing', + account: '0xb0e868f24bc7fec2bce2efc2b1c344d7569cd9d2', + }, + { + seed: 'recycle tag bird palace blue village anxiety census cook soldier example music', + account: '0xab34a45920afe4af212b96ec51232aaa6a33f663', + }, + { + seed: 'half glimpse tape cute harvest sweet bike voyage actual floor poet lazy', + account: '0x28e9044597b625ac4beda7250011670223de43b2', + }, + { + seed: 'flavor tiger carpet motor angry hungry document inquiry large critic usage liar', + account: '0xb571be96558940c4e9292e1999461aa7499fb6cd', + }, + ] + + before(function() { + window.localStorage = {} // Hacking localStorage support into JSDom + + keyringController = new KeyringController({ + configManager: configManagerGen(), + ethStore: { + addAccount(acct) { accounts[acct] = acct}, + del(acct) { delete accounts[acct] }, + }, + }) + }) + + it('should enforce seed compliance with TestRPC', function (done) { + this.timeout(10000) + const tests = assertions.map((assertion) => { + return function (cb) { + + keyringController.recoverFromSeed(password, assertion.seed, (err) => { + assert.ifError(err) + + var expected = assertion.account.toLowerCase() + var received = accounts[expected].toLowerCase() + assert.equal(received, expected) + + keyringController.tryPassword(password, function (err) { + + assert.ok(keyringController._isUnlocked(), 'should unlock the id store') + + keyringController.submitPassword(password, function(err, account) { + assert.ifError(err) + assert.equal(account, expected) + assert.equal(Object.keys(keyringController._getAddresses()).length, 1, 'only one account on restore') + cb() + }) + }) + }) + } + }) + + async.series(tests, function(err, results) { + assert.ifError(err) + done() + }) + }) + }) +}) 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(){}, + _setKeyringController(){}, update: function(stateName) { selectedView = stateName updateQueryParams(stateName) diff --git a/ui/app/actions.js b/ui/app/actions.js index 1f0d8fc78..a6601cd0e 100644 --- a/ui/app/actions.js +++ b/ui/app/actions.js @@ -16,10 +16,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, @@ -29,10 +25,6 @@ var actions = { createNewVaultInProgress: createNewVaultInProgress, 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 +45,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 +85,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', @@ -106,7 +95,7 @@ var actions = { setRpcTarget: setRpcTarget, setProviderType: setProviderType, // hacky - need a way to get a reference to account manager - _setAccountManager: _setAccountManager, + _setKeyringController: _setKeyringController, // loading overlay SHOW_LOADING: 'SHOW_LOADING_INDICATION', HIDE_LOADING: 'HIDE_LOADING_INDICATION', @@ -143,13 +132,17 @@ 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 _keyringController = null +function _setKeyringController (accountManager) { + _keyringController = accountManager } function goHome () { @@ -164,7 +157,7 @@ function tryUnlockMetamask (password) { return (dispatch) => { dispatch(actions.showLoadingIndication()) dispatch(actions.unlockInProgress()) - _accountManager.submitPassword(password, (err, selectedAccount) => { + _keyringController.submitPassword(password, (err, selectedAccount) => { dispatch(actions.hideLoadingIndication()) if (err) { dispatch(actions.unlockFailed()) @@ -178,45 +171,12 @@ function tryUnlockMetamask (password) { function createNewVault (password, entropy) { return (dispatch) => { dispatch(actions.createNewVaultInProgress()) - _accountManager.createNewVault(password, entropy, (err, result) => { + _keyringController.createNewVault(password, entropy, (err, result) => { 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)) - }) - }) - } -} - -function recoverFromSeed (password, seed) { - 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)) + dispatch(this.showAccountsPage()) + dispatch(this.hideLoadingIndication()) }) } } @@ -229,27 +189,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, - }) - }) + _keyringController.setSelectedAddress(address) } } function setCurrentFiat (fiat) { return (dispatch) => { dispatch(this.showLoadingIndication()) - _accountManager.setCurrentFiat(fiat, (data, err) => { + _keyringController.setCurrentFiat(fiat, (data, err) => { dispatch(this.hideLoadingIndication()) dispatch({ type: this.SET_CURRENT_FIAT, @@ -267,7 +214,7 @@ function signMsg (msgData) { return (dispatch) => { dispatch(actions.showLoadingIndication()) - _accountManager.signMessage(msgData, (err) => { + _keyringController.signMessage(msgData, (err) => { dispatch(actions.hideLoadingIndication()) if (err) return dispatch(actions.displayWarning(err.message)) @@ -293,7 +240,7 @@ function signTx (txData) { function sendTx (txData) { return (dispatch) => { - _accountManager.approveTransaction(txData.id, (err) => { + _keyringController.approveTransaction(txData.id, (err) => { if (err) { alert(err.message) dispatch(actions.txError(err)) @@ -319,12 +266,12 @@ function txError (err) { } function cancelMsg (msgData) { - _accountManager.cancelMessage(msgData.id) + _keyringController.cancelMessage(msgData.id) return actions.completedTx(msgData.id) } function cancelTx (txData) { - _accountManager.cancelTransaction(txData.id) + _keyringController.cancelTransaction(txData.id) return actions.completedTx(txData.id) } @@ -353,7 +300,7 @@ function showInitializeMenu () { function agreeToDisclaimer () { return (dispatch) => { dispatch(this.showLoadingIndication()) - _accountManager.agreeToDisclaimer((err) => { + _keyringController.agreeToDisclaimer((err) => { if (err) { return dispatch(actions.showWarning(err.message)) } @@ -385,6 +332,12 @@ function backToUnlockView () { } } +function showNewKeychain () { + return { + type: actions.SHOW_NEW_KEYCHAIN + } +} + // // unlock screen // @@ -417,7 +370,7 @@ function updateMetamaskState (newState) { function lockMetamask () { return (dispatch) => { - _accountManager.setLocked((err) => { + _keyringController.setLocked((err) => { dispatch(actions.hideLoadingIndication()) if (err) { return dispatch(actions.showWarning(err.message)) @@ -433,7 +386,7 @@ function lockMetamask () { function showAccountDetail (address) { return (dispatch) => { dispatch(actions.showLoadingIndication()) - _accountManager.setSelectedAddress(address, (err, address) => { + _keyringController.setSelectedAddress(address, (err, address) => { dispatch(actions.hideLoadingIndication()) if (err) { return dispatch(actions.showWarning(err.message)) @@ -453,27 +406,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 +457,7 @@ function goBackToInitView () { // function setRpcTarget (newRpc) { - _accountManager.setRpcTarget(newRpc) + _keyringController.setRpcTarget(newRpc) return { type: actions.SET_RPC_TARGET, value: newRpc, @@ -533,7 +465,7 @@ function setRpcTarget (newRpc) { } function setProviderType (type) { - _accountManager.setProviderType(type) + _keyringController.setProviderType(type) return { type: actions.SET_PROVIDER_TYPE, value: type, @@ -541,7 +473,7 @@ function setProviderType (type) { } function useEtherscanProvider () { - _accountManager.useEtherscanProvider() + _keyringController.useEtherscanProvider() return { type: actions.USE_ETHERSCAN_PROVIDER, } @@ -600,7 +532,7 @@ function exportAccount (address) { return function (dispatch) { dispatch(self.showLoadingIndication()) - _accountManager.exportAccount(address, function (err, result) { + _keyringController.exportAccount(address, function (err, result) { dispatch(self.hideLoadingIndication()) if (err) { @@ -623,7 +555,7 @@ function showPrivateKey (key) { function saveAccountLabel (account, label) { return (dispatch) => { dispatch(actions.showLoadingIndication()) - _accountManager.saveAccountLabel(account, label, (err) => { + _keyringController.saveAccountLabel(account, label, (err) => { dispatch(actions.hideLoadingIndication()) if (err) { return dispatch(actions.showWarning(err.message)) @@ -644,7 +576,7 @@ function showSendPage () { function agreeToEthWarning () { return (dispatch) => { - _accountManager.agreeToEthWarning((err) => { + _keyringController.agreeToEthWarning((err) => { if (err) { return dispatch(actions.showEthWarning(err.message)) } @@ -663,7 +595,7 @@ function showEthWarning () { function buyEth (address, amount) { return (dispatch) => { - _accountManager.buyEth(address, amount) + _keyringController.buyEth(address, amount) dispatch({ type: actions.BUY_ETH, }) @@ -741,7 +673,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) + _keyringController.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..7392e275d 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,10 +400,6 @@ 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 @@ -414,12 +408,6 @@ App.prototype.renderPrimary = function () { 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: { 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..9b733d0e7 100644 --- a/ui/app/first-time/init-menu.js +++ b/ui/app/first-time/init-menu.js @@ -63,33 +63,15 @@ InitializeMenuScreen.prototype.renderMenu = function () { 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..d6fefd0c7 --- /dev/null +++ b/ui/app/new-keychain.js @@ -0,0 +1,33 @@ +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!!!!`), + h('button', + { + onClick: () => this.props.dispatch(actions.goHome()) + }) + ]) + ) +} diff --git a/ui/app/reducers/app.js b/ui/app/reducers/app.js index c2ac099a6..2bfb2567a 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..f07a4006c 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._setKeyringController(accountManager) // check if we are unlocked first accountManager.getState(function (err, metamaskState) { |