1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-22 11:22:43 +02:00
metamask-extension/test/unit/app/controllers/metamask-controller-test.js

911 lines
33 KiB
JavaScript
Raw Normal View History

import assert from 'assert'
import sinon from 'sinon'
import { cloneDeep } from 'lodash'
import nock from 'nock'
import ethUtil from 'ethereumjs-util'
import { obj as createThoughStream } from 'through2'
import blacklistJSON from 'eth-phishing-detect/src/config'
import firstTimeState from '../../localhostState'
import createTxMeta from '../../../lib/createTxMeta'
import EthQuery from 'eth-query'
2018-04-19 23:36:33 +02:00
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
const threeBoxSpies = {
init: sinon.stub(),
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
getThreeBoxSyncingState: sinon.stub().returns(true),
turnThreeBoxSyncingOn: sinon.stub(),
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
_registerUpdates: sinon.spy(),
}
import proxyquire from 'proxyquire'
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
class ThreeBoxControllerMock {
constructor () {
this.store = {
subscribe: () => {},
getState: () => ({}),
}
this.init = threeBoxSpies.init
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
this.getThreeBoxSyncingState = threeBoxSpies.getThreeBoxSyncingState
this.turnThreeBoxSyncingOn = threeBoxSpies.turnThreeBoxSyncingOn
this._registerUpdates = threeBoxSpies._registerUpdates
}
}
const ExtensionizerMock = {
runtime: {
id: 'fake-extension-id',
},
}
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
const MetaMaskController = proxyquire('../../../../app/scripts/metamask-controller', {
'./controllers/threebox': { default: ThreeBoxControllerMock },
'extensionizer': ExtensionizerMock,
}).default
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
2018-04-19 23:36:33 +02:00
const currentNetworkId = 42
const DEFAULT_LABEL = 'Account 1'
const DEFAULT_LABEL_2 = 'Account 2'
const TEST_SEED = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
const TEST_ADDRESS = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'
const TEST_ADDRESS_2 = '0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b'
const TEST_ADDRESS_3 = '0xeb9e64b93097bc15f01f13eae97015c57ab64823'
const TEST_SEED_ALT = 'setup olympic issue mobile velvet surge alcohol burger horse view reopen gentle'
const TEST_ADDRESS_ALT = '0xc42edfcc21ed14dda456aa0756c153f7985d8813'
2018-08-17 18:56:07 +02:00
const CUSTOM_RPC_URL = 'http://localhost:8545'
2017-05-04 23:35:10 +02:00
describe('MetaMaskController', function () {
2018-02-15 17:34:31 +01:00
let metamaskController
const sandbox = sinon.createSandbox()
2018-03-27 23:02:00 +02:00
const noop = () => {}
2017-05-04 23:35:10 +02:00
beforeEach(function () {
2018-02-15 17:34:31 +01:00
nock('https://api.infura.io')
.persist()
.get('/v2/blacklist')
.reply(200, blacklistJSON)
2018-03-27 23:02:00 +02:00
nock('https://api.infura.io')
.get('/v1/ticker/ethusd')
.reply(200, '{"base": "ETH", "quote": "USD", "bid": 288.45, "ask": 288.46, "volume": 112888.17569277, "exchange": "bitfinex", "total_volume": 272175.00106721005, "num_exchanges": 8, "timestamp": 1506444677}')
nock('https://api.infura.io')
.get('/v1/ticker/ethjpy')
.reply(200, '{"base": "ETH", "quote": "JPY", "bid": 32300.0, "ask": 32400.0, "volume": 247.4616071, "exchange": "kraken", "total_volume": 247.4616071, "num_exchanges": 1, "timestamp": 1506444676}')
2018-02-28 00:50:49 +01:00
nock('https://api.infura.io')
2018-02-15 17:34:31 +01:00
.persist()
2018-02-28 00:50:49 +01:00
.get(/.*/)
2018-02-15 17:34:31 +01:00
.reply(200)
nock('https://min-api.cryptocompare.com')
.persist()
.get(/.*/)
.reply(200, '{"JPY":12415.9}')
2018-02-15 17:34:31 +01:00
metamaskController = new MetaMaskController({
showUnapprovedTx: noop,
showUnconfirmedMessage: noop,
2018-02-15 17:34:31 +01:00
encryptor: {
encrypt: function (_, object) {
2018-02-15 17:34:31 +01:00
this.object = object
return Promise.resolve('mock-encrypted')
2018-02-15 17:34:31 +01:00
},
decrypt: function () {
return Promise.resolve(this.object)
},
},
initState: cloneDeep(firstTimeState),
platform: { showTransactionNotification: () => {} },
2018-02-15 17:34:31 +01:00
})
// disable diagnostics
metamaskController.diagnostics = null
// add sinon method spies
2018-02-15 17:34:31 +01:00
sandbox.spy(metamaskController.keyringController, 'createNewVaultAndKeychain')
sandbox.spy(metamaskController.keyringController, 'createNewVaultAndRestore')
})
2017-05-04 23:35:10 +02:00
afterEach(function () {
2018-02-15 17:34:31 +01:00
nock.cleanAll()
sandbox.restore()
})
describe('#getAccounts', function () {
it('returns first address when dapp calls web3.eth.getAccounts', async function () {
const password = 'a-fake-password'
await metamaskController.createNewVaultAndRestore(password, TEST_SEED)
metamaskController.networkController._baseProviderParams.getAccounts((err, res) => {
assert.ifError(err)
assert.equal(res.length, 1)
assert.equal(res[0], '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc')
})
})
})
describe('#importAccountWithStrategy', function () {
const importPrivkey = '4cfd3e90fc78b0f86bf7524722150bb8da9c60cd532564d7ff43f5716514f553'
beforeEach(async function () {
const password = 'a-fake-password'
await metamaskController.createNewVaultAndRestore(password, TEST_SEED)
await metamaskController.importAccountWithStrategy('Private Key', [ importPrivkey ])
})
it('adds private key to keyrings in KeyringController', async function () {
const simpleKeyrings = metamaskController.keyringController.getKeyringsByType('Simple Key Pair')
const privKeyBuffer = simpleKeyrings[0].wallets[0]._privKey
const pubKeyBuffer = simpleKeyrings[0].wallets[0]._pubKey
const addressBuffer = ethUtil.pubToAddress(pubKeyBuffer)
const privKey = ethUtil.bufferToHex(privKeyBuffer)
const pubKey = ethUtil.bufferToHex(addressBuffer)
assert.equal(privKey, ethUtil.addHexPrefix(importPrivkey))
assert.equal(pubKey, '0xe18035bf8712672935fdb4e5e431b1a0183d2dfc')
})
it('adds 1 account', async function () {
const keyringAccounts = await metamaskController.keyringController.getAccounts()
assert.equal(keyringAccounts[keyringAccounts.length - 1], '0xe18035bf8712672935fdb4e5e431b1a0183d2dfc')
})
})
describe('submitPassword', function () {
const password = 'password'
beforeEach(async function () {
await metamaskController.createNewVaultAndKeychain(password)
threeBoxSpies.init.reset()
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
threeBoxSpies.turnThreeBoxSyncingOn.reset()
})
it('removes any identities that do not correspond to known accounts.', async function () {
const fakeAddress = '0xbad0'
metamaskController.preferencesController.addAddresses([fakeAddress])
await metamaskController.submitPassword(password)
const identities = Object.keys(metamaskController.preferencesController.store.getState().identities)
const addresses = await metamaskController.keyringController.getAccounts()
identities.forEach((identity) => {
assert.ok(addresses.includes(identity), `addresses should include all IDs: ${identity}`)
})
addresses.forEach((address) => {
assert.ok(identities.includes(address), `identities should include all Addresses: ${address}`)
})
})
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
it('gets the address from threebox and creates a new 3box instance', async function () {
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
await metamaskController.submitPassword(password)
assert(threeBoxSpies.init.calledOnce)
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
assert(threeBoxSpies.turnThreeBoxSyncingOn.calledOnce)
})
})
2018-02-15 17:34:31 +01:00
describe('#getGasPrice', function () {
2018-03-27 23:02:00 +02:00
2018-02-15 17:34:31 +01:00
it('gives the 50th percentile lowest accepted gas price from recentBlocksController', async function () {
const realRecentBlocksController = metamaskController.recentBlocksController
metamaskController.recentBlocksController = {
store: {
getState: () => {
return {
recentBlocks: [
{ gasPrices: [ '0x3b9aca00', '0x174876e800'] },
{ gasPrices: [ '0x3b9aca00', '0x174876e800'] },
2019-12-03 21:50:55 +01:00
{ gasPrices: [ '0x174876e800', '0x174876e800' ] },
{ gasPrices: [ '0x174876e800', '0x174876e800' ] },
2018-02-15 17:34:31 +01:00
],
2018-01-09 00:16:08 +01:00
}
2018-02-15 17:34:31 +01:00
},
},
}
2018-01-09 00:16:08 +01:00
2018-02-15 17:34:31 +01:00
const gasPrice = metamaskController.getGasPrice()
assert.equal(gasPrice, '0x174876e800', 'accurately estimates 65th percentile accepted gas price')
2018-01-09 00:16:08 +01:00
2018-02-15 17:34:31 +01:00
metamaskController.recentBlocksController = realRecentBlocksController
2018-01-06 06:24:10 +01:00
})
2018-02-15 17:34:31 +01:00
})
2018-01-06 06:24:10 +01:00
2018-02-15 17:34:31 +01:00
describe('#createNewVaultAndKeychain', function () {
it('can only create new vault on keyringController once', async function () {
const selectStub = sandbox.stub(metamaskController, 'selectFirstIdentity')
2018-01-04 01:44:14 +01:00
2018-02-15 17:34:31 +01:00
const password = 'a-fake-password'
2018-02-15 17:34:31 +01:00
await metamaskController.createNewVaultAndKeychain(password)
await metamaskController.createNewVaultAndKeychain(password)
2017-11-20 23:44:12 +01:00
2018-02-15 17:34:31 +01:00
assert(metamaskController.keyringController.createNewVaultAndKeychain.calledOnce)
2018-02-15 17:34:31 +01:00
selectStub.reset()
})
2018-02-15 17:34:31 +01:00
})
describe('#createNewVaultAndRestore', function () {
it('should be able to call newVaultAndRestore despite a mistake.', async function () {
const password = 'what-what-what'
sandbox.stub(metamaskController, 'getBalance')
metamaskController.getBalance.callsFake(() => {
return Promise.resolve('0x0')
})
await metamaskController.createNewVaultAndRestore(password, TEST_SEED.slice(0, -1)).catch(() => null)
await metamaskController.createNewVaultAndRestore(password, TEST_SEED)
2018-01-04 01:44:14 +01:00
2018-02-15 17:34:31 +01:00
assert(metamaskController.keyringController.createNewVaultAndRestore.calledTwice)
2018-01-04 01:44:14 +01:00
})
it('should clear previous identities after vault restoration', async function () {
sandbox.stub(metamaskController, 'getBalance')
metamaskController.getBalance.callsFake(() => {
return Promise.resolve('0x0')
})
await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED)
assert.deepEqual(metamaskController.getState().identities, {
[TEST_ADDRESS]: { address: TEST_ADDRESS, name: DEFAULT_LABEL },
})
2018-05-21 23:57:57 +02:00
await metamaskController.preferencesController.setAccountLabel(TEST_ADDRESS, 'Account Foo')
assert.deepEqual(metamaskController.getState().identities, {
[TEST_ADDRESS]: { address: TEST_ADDRESS, name: 'Account Foo' },
})
await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT)
assert.deepEqual(metamaskController.getState().identities, {
[TEST_ADDRESS_ALT]: { address: TEST_ADDRESS_ALT, name: DEFAULT_LABEL },
})
})
it('should restore any consecutive accounts with balances', async function () {
sandbox.stub(metamaskController, 'getBalance')
metamaskController.getBalance.withArgs(TEST_ADDRESS).callsFake(() => {
return Promise.resolve('0x14ced5122ce0a000')
})
metamaskController.getBalance.withArgs(TEST_ADDRESS_2).callsFake(() => {
return Promise.resolve('0x0')
})
metamaskController.getBalance.withArgs(TEST_ADDRESS_3).callsFake(() => {
return Promise.resolve('0x14ced5122ce0a000')
})
await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED)
assert.deepEqual(metamaskController.getState().identities, {
[TEST_ADDRESS]: { address: TEST_ADDRESS, name: DEFAULT_LABEL },
[TEST_ADDRESS_2]: { address: TEST_ADDRESS_2, name: DEFAULT_LABEL_2 },
})
})
})
describe('#getBalance', function () {
it('should return the balance known by accountTracker', async function () {
const accounts = {}
const balance = '0x14ced5122ce0a000'
accounts[TEST_ADDRESS] = { balance: balance }
metamaskController.accountTracker.store.putState({ accounts: accounts })
const gotten = await metamaskController.getBalance(TEST_ADDRESS)
assert.equal(balance, gotten)
})
it('should ask the network for a balance when not known by accountTracker', async function () {
const accounts = {}
const balance = '0x14ced5122ce0a000'
const ethQuery = new EthQuery()
sinon.stub(ethQuery, 'getBalance').callsFake((_, callback) => {
callback(undefined, balance)
})
metamaskController.accountTracker.store.putState({ accounts: accounts })
const gotten = await metamaskController.getBalance(TEST_ADDRESS, ethQuery)
assert.equal(balance, gotten)
})
2017-05-04 23:35:10 +02:00
})
2018-03-27 23:02:00 +02:00
describe('#getApi', function () {
it('getState', function (done) {
let state
const getApi = metamaskController.getApi()
2018-03-27 23:02:00 +02:00
getApi.getState((err, res) => {
if (err) {
done(err)
} else {
state = res
}
})
assert.deepEqual(state, metamaskController.getState())
done()
})
})
describe('preferencesController', function () {
it('defaults useBlockie to false', function () {
assert.equal(metamaskController.preferencesController.store.getState().useBlockie, false)
})
it('setUseBlockie to true', function () {
2018-03-27 23:02:00 +02:00
metamaskController.setUseBlockie(true, noop)
assert.equal(metamaskController.preferencesController.store.getState().useBlockie, true)
})
})
describe('#selectFirstIdentity', function () {
let identities, address
beforeEach(function () {
address = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'
identities = {
2018-05-21 23:57:57 +02:00
'0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc': {
'address': address,
'name': 'Account 1',
},
'0xc42edfcc21ed14dda456aa0756c153f7985d8813': {
'address': '0xc42edfcc21ed14dda456aa0756c153f7985d8813',
'name': 'Account 2',
2018-03-27 23:02:00 +02:00
},
}
2018-05-21 23:57:57 +02:00
metamaskController.preferencesController.store.updateState({ identities })
metamaskController.selectFirstIdentity()
2018-03-27 23:02:00 +02:00
})
it('changes preferences controller select address', function () {
const preferenceControllerState = metamaskController.preferencesController.store.getState()
assert.equal(preferenceControllerState.selectedAddress, address)
})
it('changes metamask controller selected address', function () {
const metamaskState = metamaskController.getState()
assert.equal(metamaskState.selectedAddress, address)
})
})
describe('connectHardware', function () {
it('should throw if it receives an unknown device name', async function () {
try {
2018-08-14 09:42:23 +02:00
await metamaskController.connectHardware('Some random device name', 0, `m/44/0'/0'`)
} catch (e) {
2018-08-14 09:42:23 +02:00
assert.equal(e, 'Error: MetamaskController:getKeyringForDevice - Unknown device')
}
})
it('should add the Trezor Hardware keyring', async function () {
2018-07-17 07:17:18 +02:00
sinon.spy(metamaskController.keyringController, 'addNewKeyring')
await metamaskController.connectHardware('trezor', 0).catch(() => null)
const keyrings = await metamaskController.keyringController.getKeyringsByType(
'Trezor Hardware'
)
2018-07-17 07:17:18 +02:00
assert.equal(metamaskController.keyringController.addNewKeyring.getCall(0).args, 'Trezor Hardware')
assert.equal(keyrings.length, 1)
})
2018-08-14 09:42:23 +02:00
it('should add the Ledger Hardware keyring', async function () {
sinon.spy(metamaskController.keyringController, 'addNewKeyring')
await metamaskController.connectHardware('ledger', 0).catch(() => null)
2018-08-14 09:42:23 +02:00
const keyrings = await metamaskController.keyringController.getKeyringsByType(
'Ledger Hardware'
)
assert.equal(metamaskController.keyringController.addNewKeyring.getCall(0).args, 'Ledger Hardware')
assert.equal(keyrings.length, 1)
})
})
describe('checkHardwareStatus', function () {
it('should throw if it receives an unknown device name', async function () {
try {
2018-08-14 09:42:23 +02:00
await metamaskController.checkHardwareStatus('Some random device name', `m/44/0'/0'`)
} catch (e) {
2018-08-14 09:42:23 +02:00
assert.equal(e, 'Error: MetamaskController:getKeyringForDevice - Unknown device')
}
})
it('should be locked by default', async function () {
await metamaskController.connectHardware('trezor', 0).catch(() => null)
const status = await metamaskController.checkHardwareStatus('trezor')
assert.equal(status, false)
})
})
describe('forgetDevice', function () {
it('should throw if it receives an unknown device name', async function () {
try {
await metamaskController.forgetDevice('Some random device name')
} catch (e) {
2018-08-14 09:42:23 +02:00
assert.equal(e, 'Error: MetamaskController:getKeyringForDevice - Unknown device')
}
})
it('should wipe all the keyring info', async function () {
await metamaskController.connectHardware('trezor', 0).catch(() => null)
await metamaskController.forgetDevice('trezor')
const keyrings = await metamaskController.keyringController.getKeyringsByType(
'Trezor Hardware'
)
assert.deepEqual(keyrings[0].accounts, [])
assert.deepEqual(keyrings[0].page, 0)
assert.deepEqual(keyrings[0].isUnlocked(), false)
})
})
2018-08-14 09:42:23 +02:00
describe('unlockHardwareWalletAccount', function () {
2018-07-17 07:17:18 +02:00
let accountToUnlock
let windowOpenStub
let addNewAccountStub
let getAccountsStub
beforeEach(async function () {
accountToUnlock = 10
windowOpenStub = sinon.stub(window, 'open')
windowOpenStub.returns(noop)
addNewAccountStub = sinon.stub(metamaskController.keyringController, 'addNewAccount')
addNewAccountStub.returns({})
getAccountsStub = sinon.stub(metamaskController.keyringController, 'getAccounts')
// Need to return different address to mock the behavior of
// adding a new account from the keyring
getAccountsStub.onCall(0).returns(Promise.resolve(['0x1']))
getAccountsStub.onCall(1).returns(Promise.resolve(['0x2']))
getAccountsStub.onCall(2).returns(Promise.resolve(['0x3']))
getAccountsStub.onCall(3).returns(Promise.resolve(['0x4']))
sinon.spy(metamaskController.preferencesController, 'setAddresses')
sinon.spy(metamaskController.preferencesController, 'setSelectedAddress')
sinon.spy(metamaskController.preferencesController, 'setAccountLabel')
await metamaskController.connectHardware('trezor', 0, `m/44/0'/0'`).catch(() => null)
2018-08-15 03:19:01 +02:00
await metamaskController.unlockHardwareWalletAccount(accountToUnlock, 'trezor', `m/44/0'/0'`)
2018-07-17 07:17:18 +02:00
})
afterEach(function () {
window.open.restore()
2018-08-15 03:19:01 +02:00
metamaskController.keyringController.addNewAccount.restore()
metamaskController.keyringController.getAccounts.restore()
metamaskController.preferencesController.setAddresses.restore()
metamaskController.preferencesController.setSelectedAddress.restore()
metamaskController.preferencesController.setAccountLabel.restore()
2018-07-17 07:17:18 +02:00
})
2018-08-15 03:19:01 +02:00
it('should set unlockedAccount in the keyring', async function () {
const keyrings = await metamaskController.keyringController.getKeyringsByType(
'Trezor Hardware'
)
assert.equal(keyrings[0].unlockedAccount, accountToUnlock)
})
2018-07-17 07:17:18 +02:00
2018-08-15 03:19:01 +02:00
it('should call keyringController.addNewAccount', async function () {
2018-07-17 07:17:18 +02:00
assert(metamaskController.keyringController.addNewAccount.calledOnce)
})
it('should call keyringController.getAccounts ', async function () {
assert(metamaskController.keyringController.getAccounts.called)
})
it('should call preferencesController.setAddresses', async function () {
assert(metamaskController.preferencesController.setAddresses.calledOnce)
})
it('should call preferencesController.setSelectedAddress', async function () {
assert(metamaskController.preferencesController.setSelectedAddress.calledOnce)
})
it('should call preferencesController.setAccountLabel', async function () {
assert(metamaskController.preferencesController.setAccountLabel.calledOnce)
})
})
2018-03-27 23:02:00 +02:00
describe('#setCustomRpc', function () {
let rpcTarget
beforeEach(function () {
2018-08-17 18:56:07 +02:00
rpcTarget = metamaskController.setCustomRpc(CUSTOM_RPC_URL)
})
2018-03-27 23:02:00 +02:00
it('returns custom RPC that when called', async function () {
2018-08-17 18:56:07 +02:00
assert.equal(await rpcTarget, CUSTOM_RPC_URL)
2018-03-27 23:02:00 +02:00
})
it('changes the network controller rpc', function () {
const networkControllerState = metamaskController.networkController.store.getState()
2018-08-17 18:56:07 +02:00
assert.equal(networkControllerState.provider.rpcTarget, CUSTOM_RPC_URL)
2018-03-27 23:02:00 +02:00
})
})
describe('#setCurrentCurrency', function () {
let defaultMetaMaskCurrency
beforeEach(function () {
defaultMetaMaskCurrency = metamaskController.currencyRateController.state.currentCurrency
2018-03-27 23:02:00 +02:00
})
it('defaults to usd', function () {
assert.equal(defaultMetaMaskCurrency, 'usd')
})
it('sets currency to JPY', function () {
metamaskController.setCurrentCurrency('JPY', noop)
assert.equal(metamaskController.currencyRateController.state.currentCurrency, 'JPY')
2018-03-27 23:02:00 +02:00
})
})
describe('#addNewAccount', function () {
it('errors when an primary keyring is does not exist', async function () {
const addNewAccount = metamaskController.addNewAccount()
2018-03-27 23:02:00 +02:00
try {
await addNewAccount
assert.fail('should throw')
2018-03-27 23:02:00 +02:00
} catch (e) {
assert.equal(e.message, 'MetamaskController - No HD Key Tree found')
}
})
})
2018-04-11 17:34:35 +02:00
describe('#verifyseedPhrase', function () {
it('errors when no keying is provided', async function () {
try {
await metamaskController.verifySeedPhrase()
} catch (error) {
assert.equal(error.message, 'MetamaskController - No HD Key Tree found')
}
})
beforeEach(async function () {
await metamaskController.createNewVaultAndKeychain('password')
})
2018-04-19 23:36:33 +02:00
it('#addNewAccount', async function () {
await metamaskController.addNewAccount()
const getAccounts = await metamaskController.keyringController.getAccounts()
assert.equal(getAccounts.length, 2)
})
})
describe('#resetAccount', function () {
it('wipes transactions from only the correct network id and with the selected address', async function () {
2018-04-19 23:36:33 +02:00
const selectedAddressStub = sinon.stub(metamaskController.preferencesController, 'getSelectedAddress')
const getNetworkstub = sinon.stub(metamaskController.txController.txStateManager, 'getNetwork')
selectedAddressStub.returns('0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc')
getNetworkstub.returns(42)
metamaskController.txController.txStateManager._saveTxList([
2019-12-03 21:50:55 +01:00
createTxMeta({ id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: { from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' } }),
createTxMeta({ id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: { from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' } }),
2018-08-17 18:56:07 +02:00
createTxMeta({ id: 2, status: 'rejected', metamaskNetworkId: 32 }),
2019-12-03 21:50:55 +01:00
createTxMeta({ id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: { from: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4' } }),
2018-04-19 23:36:33 +02:00
])
await metamaskController.resetAccount()
assert.equal(metamaskController.txController.txStateManager.getTx(1), undefined)
})
2018-04-11 17:34:35 +02:00
})
2018-07-17 07:44:28 +02:00
describe('#removeAccount', function () {
let ret
const addressToRemove = '0x1'
beforeEach(async function () {
sinon.stub(metamaskController.preferencesController, 'removeAddress')
sinon.stub(metamaskController.accountTracker, 'removeAccount')
sinon.stub(metamaskController.keyringController, 'removeAccount')
ret = await metamaskController.removeAccount(addressToRemove)
})
afterEach(function () {
metamaskController.keyringController.removeAccount.restore()
metamaskController.accountTracker.removeAccount.restore()
metamaskController.preferencesController.removeAddress.restore()
})
it('should call preferencesController.removeAddress', async function () {
assert(metamaskController.preferencesController.removeAddress.calledWith(addressToRemove))
})
it('should call accountTracker.removeAccount', async function () {
2018-08-21 06:09:54 +02:00
assert(metamaskController.accountTracker.removeAccount.calledWith([addressToRemove]))
2018-07-17 07:44:28 +02:00
})
it('should call keyringController.removeAccount', async function () {
assert(metamaskController.keyringController.removeAccount.calledWith(addressToRemove))
})
it('should return address', async function () {
assert.equal(ret, '0x1')
})
})
describe('#setCurrentLocale', function () {
it('checks the default currentLocale', function () {
const preferenceCurrentLocale = metamaskController.preferencesController.store.getState().currentLocale
assert.equal(preferenceCurrentLocale, undefined)
})
it('sets current locale in preferences controller', function () {
metamaskController.setCurrentLocale('ja', noop)
const preferenceCurrentLocale = metamaskController.preferencesController.store.getState().currentLocale
assert.equal(preferenceCurrentLocale, 'ja')
})
})
describe('#newUnsignedMessage', function () {
let msgParams, metamaskMsgs, messages, msgId
2018-05-18 01:26:08 +02:00
const address = '0xc42edfcc21ed14dda456aa0756c153f7985d8813'
const data = '0x43727970746f6b697474696573'
beforeEach(async function () {
sandbox.stub(metamaskController, 'getBalance')
metamaskController.getBalance.callsFake(() => {
return Promise.resolve('0x0')
})
2018-05-18 01:26:08 +02:00
await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT)
msgParams = {
'from': address,
'data': data,
}
2018-08-17 18:56:07 +02:00
const promise = metamaskController.newUnsignedMessage(msgParams)
// handle the promise so it doesn't throw an unhandledRejection
promise.then(noop).catch(noop)
metamaskMsgs = metamaskController.messageManager.getUnapprovedMsgs()
messages = metamaskController.messageManager.messages
msgId = Object.keys(metamaskMsgs)[0]
2018-05-18 01:26:08 +02:00
messages[0].msgParams.metamaskId = parseInt(msgId)
})
it('persists address from msg params', function () {
assert.equal(metamaskMsgs[msgId].msgParams.from, address)
})
it('persists data from msg params', function () {
assert.equal(metamaskMsgs[msgId].msgParams.data, data)
})
it('sets the status to unapproved', function () {
assert.equal(metamaskMsgs[msgId].status, 'unapproved')
})
it('sets the type to eth_sign', function () {
assert.equal(metamaskMsgs[msgId].type, 'eth_sign')
})
it('rejects the message', function () {
const msgIdInt = parseInt(msgId)
metamaskController.cancelMessage(msgIdInt, noop)
assert.equal(messages[0].status, 'rejected')
})
2018-05-18 01:26:08 +02:00
it('errors when signing a message', async function () {
try {
await metamaskController.signMessage(messages[0].msgParams)
} catch (error) {
assert.equal(error.message, 'message length is invalid')
}
})
})
describe('#newUnsignedPersonalMessage', function () {
2018-05-18 01:26:08 +02:00
let msgParams, metamaskPersonalMsgs, personalMessages, msgId
2018-05-18 01:26:08 +02:00
const address = '0xc42edfcc21ed14dda456aa0756c153f7985d8813'
const data = '0x43727970746f6b697474696573'
2018-05-18 01:26:08 +02:00
beforeEach(async function () {
sandbox.stub(metamaskController, 'getBalance')
metamaskController.getBalance.callsFake(() => {
return Promise.resolve('0x0')
})
2018-05-18 01:26:08 +02:00
await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT)
msgParams = {
'from': address,
'data': data,
}
2018-08-17 18:56:07 +02:00
const promise = metamaskController.newUnsignedPersonalMessage(msgParams)
// handle the promise so it doesn't throw an unhandledRejection
promise.then(noop).catch(noop)
2018-05-18 01:26:08 +02:00
metamaskPersonalMsgs = metamaskController.personalMessageManager.getUnapprovedMsgs()
personalMessages = metamaskController.personalMessageManager.messages
msgId = Object.keys(metamaskPersonalMsgs)[0]
personalMessages[0].msgParams.metamaskId = parseInt(msgId)
})
it('errors with no from in msgParams', async function () {
const msgParams = {
'data': data,
}
try {
await metamaskController.newUnsignedPersonalMessage(msgParams)
assert.fail('should have thrown')
} catch (error) {
assert.equal(error.message, 'MetaMask Message Signature: from field is required.')
}
})
it('persists address from msg params', function () {
2018-05-18 01:26:08 +02:00
assert.equal(metamaskPersonalMsgs[msgId].msgParams.from, address)
})
it('persists data from msg params', function () {
2018-05-18 01:26:08 +02:00
assert.equal(metamaskPersonalMsgs[msgId].msgParams.data, data)
})
it('sets the status to unapproved', function () {
2018-05-18 01:26:08 +02:00
assert.equal(metamaskPersonalMsgs[msgId].status, 'unapproved')
})
it('sets the type to personal_sign', function () {
2018-05-18 01:26:08 +02:00
assert.equal(metamaskPersonalMsgs[msgId].type, 'personal_sign')
})
it('rejects the message', function () {
const msgIdInt = parseInt(msgId)
metamaskController.cancelPersonalMessage(msgIdInt, noop)
2018-05-18 01:26:08 +02:00
assert.equal(personalMessages[0].status, 'rejected')
})
it('errors when signing a message', async function () {
await metamaskController.signPersonalMessage(personalMessages[0].msgParams)
assert.equal(metamaskPersonalMsgs[msgId].status, 'signed')
assert.equal(metamaskPersonalMsgs[msgId].rawSig, '0x6a1b65e2b8ed53cf398a769fad24738f9fbe29841fe6854e226953542c4b6a173473cb152b6b1ae5f06d601d45dd699a129b0a8ca84e78b423031db5baa734741b')
})
})
describe('#setupUntrustedCommunication', function () {
it('sets up phishing stream for untrusted communication ', async function () {
const phishingMessageSender = {
url: 'http://myethereumwalletntw.com',
tab: {},
}
await metamaskController.phishingController.updatePhishingLists()
2018-08-17 18:56:07 +02:00
const { promise, resolve } = deferredPromise()
const streamTest = createThoughStream((chunk, _, cb) => {
if (chunk.name !== 'phishing') {
return cb()
}
assert.equal(chunk.data.hostname, (new URL(phishingMessageSender.url)).hostname)
2018-08-17 18:56:07 +02:00
resolve()
cb()
})
metamaskController.setupUntrustedCommunication(streamTest, phishingMessageSender)
2018-08-17 18:56:07 +02:00
await promise
streamTest.end()
})
})
describe('#setupTrustedCommunication', function () {
it('sets up controller dnode api for trusted communication', async function () {
const messageSender = {
url: 'http://mycrypto.com',
tab: {},
}
const { promise, resolve } = deferredPromise()
const streamTest = createThoughStream((chunk, _, cb) => {
assert.equal(chunk.name, 'controller')
resolve()
cb()
})
metamaskController.setupTrustedCommunication(streamTest, messageSender)
await promise
streamTest.end()
})
})
describe('#markPasswordForgotten', function () {
it('adds and sets forgottenPassword to config data to true', function () {
metamaskController.markPasswordForgotten(noop)
const state = metamaskController.getState()
assert.equal(state.forgottenPassword, true)
})
})
describe('#unMarkPasswordForgotten', function () {
it('adds and sets forgottenPassword to config data to false', function () {
metamaskController.unMarkPasswordForgotten(noop)
const state = metamaskController.getState()
assert.equal(state.forgottenPassword, false)
})
})
describe('#_onKeyringControllerUpdate', function () {
it('should do nothing if there are no keyrings in state', async function () {
const addAddresses = sinon.fake()
const syncWithAddresses = sinon.fake()
sandbox.replace(metamaskController, 'preferencesController', {
addAddresses,
})
sandbox.replace(metamaskController, 'accountTracker', {
syncWithAddresses,
})
const oldState = metamaskController.getState()
2019-12-03 21:50:55 +01:00
await metamaskController._onKeyringControllerUpdate({ keyrings: [] })
assert.ok(addAddresses.notCalled)
assert.ok(syncWithAddresses.notCalled)
assert.deepEqual(metamaskController.getState(), oldState)
})
it('should update selected address if keyrings was locked', async function () {
const addAddresses = sinon.fake()
const getSelectedAddress = sinon.fake.returns('0x42')
const setSelectedAddress = sinon.fake()
const syncWithAddresses = sinon.fake()
sandbox.replace(metamaskController, 'preferencesController', {
addAddresses,
getSelectedAddress,
setSelectedAddress,
})
sandbox.replace(metamaskController, 'accountTracker', {
syncWithAddresses,
})
const oldState = metamaskController.getState()
await metamaskController._onKeyringControllerUpdate({
isUnlocked: false,
keyrings: [{
accounts: ['0x1', '0x2'],
}],
})
assert.deepEqual(addAddresses.args, [[['0x1', '0x2']]])
assert.deepEqual(syncWithAddresses.args, [[['0x1', '0x2']]])
assert.deepEqual(setSelectedAddress.args, [['0x1']])
assert.deepEqual(metamaskController.getState(), oldState)
})
it('should NOT update selected address if already unlocked', async function () {
const addAddresses = sinon.fake()
const syncWithAddresses = sinon.fake()
sandbox.replace(metamaskController, 'preferencesController', {
addAddresses,
})
sandbox.replace(metamaskController, 'accountTracker', {
syncWithAddresses,
})
const oldState = metamaskController.getState()
await metamaskController._onKeyringControllerUpdate({
isUnlocked: true,
keyrings: [{
accounts: ['0x1', '0x2'],
}],
})
assert.deepEqual(addAddresses.args, [[['0x1', '0x2']]])
assert.deepEqual(syncWithAddresses.args, [[['0x1', '0x2']]])
assert.deepEqual(metamaskController.getState(), oldState)
})
})
2017-05-04 23:35:10 +02:00
})
2018-08-17 18:56:07 +02:00
function deferredPromise () {
let resolve
2020-02-15 21:34:12 +01:00
const promise = new Promise((_resolve) => {
resolve = _resolve
})
2018-08-17 18:56:07 +02:00
return { promise, resolve }
}