From dec282f4fde4b3d1a286c587b64f171835d6ad6a Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Fri, 7 Oct 2016 15:17:35 -0700 Subject: [PATCH 001/100] Add multi-vault planning doc --- docs/multi_vault_planning.md | 175 +++++++++++++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 docs/multi_vault_planning.md diff --git a/docs/multi_vault_planning.md b/docs/multi_vault_planning.md new file mode 100644 index 000000000..dbd98e4a5 --- /dev/null +++ b/docs/multi_vault_planning.md @@ -0,0 +1,175 @@ +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() + +### KeyChain (ReduxStore?) + // attributes + @name + + signTx(txParams, cb) + signMsg(msg, cb) + + getAddressList(cb) + + getViewState(cb) -> returns KeyChainViewState + + serialize(cb) -> obj + deserialize(obj) + +### 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..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 + } +} + From f8b52a3895e0d093f7d831695b56f236a911fb0f Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Tue, 11 Oct 2016 15:06:09 -0700 Subject: [PATCH 002/100] Add to doc --- docs/multi_vault_planning.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/multi_vault_planning.md b/docs/multi_vault_planning.md index dbd98e4a5..fdde2bc50 100644 --- a/docs/multi_vault_planning.md +++ b/docs/multi_vault_planning.md @@ -85,6 +85,12 @@ If we adopt a ReactStore style unidirectional action dispatching data flow, thes - 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 @@ -99,6 +105,9 @@ If we adopt a ReactStore style unidirectional action dispatching data flow, thes serialize(cb) -> obj deserialize(obj) + dispatch({ type: , value: }) + + ### KeyChainViewState // The serialized, renderable keychain data accountList: [], @@ -173,3 +182,7 @@ KeyChainViewState { } } +## 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. + From ea1a934c7defe7e1b077b675ae9125118f1f3d87 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Tue, 11 Oct 2016 15:09:22 -0700 Subject: [PATCH 003/100] Add initial KeyringController files --- app/scripts/keyring-controller.js | 42 ++++++++ test/unit/keyring-controller-test.js | 141 +++++++++++++++++++++++++++ 2 files changed, 183 insertions(+) create mode 100644 app/scripts/keyring-controller.js create mode 100644 test/unit/keyring-controller-test.js diff --git a/app/scripts/keyring-controller.js b/app/scripts/keyring-controller.js new file mode 100644 index 000000000..b61242973 --- /dev/null +++ b/app/scripts/keyring-controller.js @@ -0,0 +1,42 @@ +const scrypt = require('scrypt-async') +const bitcore = require('bitcore-lib') +const configManager = require('./lib/config-manager') + +module.exports = class KeyringController { + + constructor (opts) { + this.configManager = opts.configManager + this.keyChains = [] + } + + getKeyForPassword(password, callback) { + let salt = this.configManager.getSalt() + + if (!salt) { + salt = generateSalt(32) + 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) + } + +} + +function generateSalt (byteCount) { + return bitcore.crypto.Random.getRandomBuffer(byteCount || 32).toString('base64') +} 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() + }) + }) + }) +}) From 5c9969e126b1da153d8b0f969fbb430d7a146b14 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 12 Oct 2016 16:31:15 -0700 Subject: [PATCH 004/100] Remove opinionated seed word code Completely breaking all account maangement, I have removed the opinionated seed-word code from the UI. Web3 injection still seems to work. --- .../bip44}/create-vault-complete.js | 0 .../bip44}/recover-seed/confirmation.js | 0 .../bip44}/restore-vault.js | 0 ui/app/actions.js | 66 +------------------ ui/app/app.js | 18 +---- ui/app/config.js | 16 ----- ui/app/first-time/init-menu.js | 20 +----- 7 files changed, 4 insertions(+), 116 deletions(-) rename {ui/app/first-time => keychains/bip44}/create-vault-complete.js (100%) rename {ui/app => keychains/bip44}/recover-seed/confirmation.js (100%) rename {ui/app/first-time => keychains/bip44}/restore-vault.js (100%) diff --git a/ui/app/first-time/create-vault-complete.js b/keychains/bip44/create-vault-complete.js similarity index 100% rename from ui/app/first-time/create-vault-complete.js rename to keychains/bip44/create-vault-complete.js diff --git a/ui/app/recover-seed/confirmation.js b/keychains/bip44/recover-seed/confirmation.js similarity index 100% rename from ui/app/recover-seed/confirmation.js rename to keychains/bip44/recover-seed/confirmation.js diff --git a/ui/app/first-time/restore-vault.js b/keychains/bip44/restore-vault.js similarity index 100% rename from ui/app/first-time/restore-vault.js rename to keychains/bip44/restore-vault.js diff --git a/ui/app/actions.js b/ui/app/actions.js index 0cce9065e..fb33b7bc2 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', @@ -95,7 +87,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', @@ -182,41 +173,7 @@ function createNewVault (password, entropy) { 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(actions.goHome()) }) } } @@ -451,27 +408,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 { diff --git a/ui/app/app.js b/ui/app/app.js index 71e0637d0..3266ced51 100644 --- a/ui/app/app.js +++ b/ui/app/app.js @@ -8,8 +8,6 @@ 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') // unlock const UnlockScreen = require('./unlock') // accounts @@ -19,7 +17,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 +399,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 +407,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'}) @@ -451,16 +438,15 @@ App.prototype.renderPrimary = function () { 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()) -} - From 93ed918caa668951a5b28fd9c7683b4f19b65220 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 12 Oct 2016 16:43:35 -0700 Subject: [PATCH 005/100] Remove additional deprecated action --- ui/app/actions.js | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/ui/app/actions.js b/ui/app/actions.js index fb33b7bc2..1b3fe00ad 100644 --- a/ui/app/actions.js +++ b/ui/app/actions.js @@ -45,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 @@ -190,19 +188,6 @@ function 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, - }) - }) - } -} - function setCurrentFiat (fiat) { return (dispatch) => { dispatch(this.showLoadingIndication()) From cd2c00a31873490c9129023abb35dd7983604b60 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 12 Oct 2016 16:43:48 -0700 Subject: [PATCH 006/100] Add minimal method signatures to new keyring controller --- app/scripts/keyring-controller.js | 62 +++++++++++++++++++++++++++++- app/scripts/metamask-controller.js | 44 ++++++++++++++------- ui/app/actions.js | 3 +- 3 files changed, 94 insertions(+), 15 deletions(-) diff --git a/app/scripts/keyring-controller.js b/app/scripts/keyring-controller.js index b61242973..d96b9c101 100644 --- a/app/scripts/keyring-controller.js +++ b/app/scripts/keyring-controller.js @@ -1,11 +1,14 @@ const scrypt = require('scrypt-async') const bitcore = require('bitcore-lib') const configManager = require('./lib/config-manager') +const EventEmitter = require('events').EventEmitter -module.exports = class KeyringController { +module.exports = class KeyringController extends EventEmitter { constructor (opts) { + super() this.configManager = opts.configManager + this.ethStore = opts.ethStore this.keyChains = [] } @@ -35,6 +38,63 @@ module.exports = class KeyringController { scrypt(password, salt, logN, r, dkLen, interruptStep, cb, null) } + getState() { + return {} + } + + setStore(ethStore) { + this.ethStore = ethStore + } + + createNewVault(password, entropy, cb) { + cb() + } + + 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) { diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 550531d6e..462c132e6 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() @@ -58,7 +60,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), @@ -66,12 +67,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 @@ -160,11 +158,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 } @@ -261,8 +259,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() } } @@ -345,13 +343,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 () { @@ -362,7 +360,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') { @@ -377,4 +375,24 @@ module.exports = class MetamaskController { createShapeShiftTx (depositAddress, depositType) { 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() + }) + } + } diff --git a/ui/app/actions.js b/ui/app/actions.js index 1b3fe00ad..4f3083707 100644 --- a/ui/app/actions.js +++ b/ui/app/actions.js @@ -171,7 +171,8 @@ function createNewVault (password, entropy) { if (err) { return dispatch(actions.showWarning(err.message)) } - dispatch(actions.goHome()) + dispatch(this.goHome()) + dispatch(this.hideLoadingIndication()) }) } } From cce8d9e3600e8ba0ced12013b0b208fff9f9c8a8 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 12 Oct 2016 20:03:14 -0700 Subject: [PATCH 007/100] Began adding browser-native encryptor module Added new Qunit build process that will browserify the contents of `test/integration/lib` into the QUnit browser, allowing much more modular testing, including unit testing of our modules in our target browsers. Made a basic unit test file of this form for the new encryptor module, which fails miserably because I've only just begun to work with it. I've started with this blog post as a starting point, and will be adjusting it to our needs from there: http://qnimate.com/passphrase-based-encryption-using-web-cryptography-api/ --- README.md | 4 + app/scripts/lib/encryptor.js | 51 +++++++++ package.json | 3 +- test/integration/bundle.js | 103 ++++++++++++++++++ test/integration/index.html | 2 +- test/integration/index.js | 21 ++++ test/integration/lib/encryptor-test.js | 17 +++ .../{tests.js => lib/first-time.js} | 3 +- 8 files changed, 201 insertions(+), 3 deletions(-) create mode 100644 app/scripts/lib/encryptor.js create mode 100644 test/integration/bundle.js create mode 100644 test/integration/index.js create mode 100644 test/integration/lib/encryptor-test.js rename test/integration/{tests.js => lib/first-time.js} (88%) diff --git a/README.md b/README.md index afdda4d97..09fb0079c 100644 --- a/README.md +++ b/README.md @@ -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/lib/encryptor.js b/app/scripts/lib/encryptor.js new file mode 100644 index 000000000..607825764 --- /dev/null +++ b/app/scripts/lib/encryptor.js @@ -0,0 +1,51 @@ +var vector = global.crypto.getRandomValues(new Uint8Array(16)) +var key = null + +module.exports = { + encrypt, + decrypt, + convertArrayBufferViewtoString, + keyFromPassword, +} + +// Takes a Pojo, returns encrypted text. +function encrypt (password, dataObj) { + var data = JSON.stringify(dataObj) + global.crypto.subtle.encrypt({name: 'AES-CBC', iv: vector}, key, convertStringToArrayBufferView(data)).then(function(result){ + const encryptedData = new Uint8Array(result) + return encryptedData + }, + function(e){ + console.log(e.message) + }) +} + +// Takes encrypted text, returns the restored Pojo. +function decrypt (password, text) { + +} + +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) { + global.crypto.subtle.digest({name: 'SHA-256'}, convertStringToArrayBufferView(password)).then(function(result){ + return global.crypto.subtle.importKey('raw', result, {name: 'AES-CBC'}, false, ['encrypt', 'decrypt']) + }) +} + diff --git a/package.json b/package.json index 273117f8a..a4f234735 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "lint": "gulp lint", "dev": "gulp dev", "dist": "gulp dist", + "buildCiUnits": "node test/integration/index.js", "test": "npm run fastTest && npm run ci && npm run lint", "fastTest": "mocha --require test/helper.js --compilers js:babel-register --recursive \"test/unit/**/*.js\"", "watch": "mocha watch --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/bundle.js b/test/integration/bundle.js new file mode 100644 index 000000000..5058259b1 --- /dev/null +++ b/test/integration/bundle.js @@ -0,0 +1,103 @@ +window.QUnit = QUnit; (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o - +