1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00

Merge branch 'master' of github.com:MetaMask/metamask-extension into greenkeeper/initial

This commit is contained in:
kumavis 2017-08-03 15:05:32 -07:00
parent da7471e095
commit da16f39626
27 changed files with 611 additions and 351 deletions

5
.gitignore vendored
View File

@ -24,4 +24,7 @@ test/background.js
test/bundle.js test/bundle.js
test/test-bundle.js test/test-bundle.js
notes.txt notes.txt
.coveralls.yml
.nyc_output

View File

@ -2,11 +2,23 @@
## Current Master ## Current Master
- Continuously update blacklist for known phishing sites in background.
- Automatically detect suspicious URLs too similar to common phishing targets, and blacklist them.
## 3.9.2 2017-7-26
- Fix bugs that could sometimes result in failed transactions after switching networks.
- Include stack traces in txMeta's to better understand the life cycle of transactions
- Enhance blacklister functionality to include levenshtein logic. (credit to @sogoiii and @409H for their help!)
## 3.9.1 2017-7-19
- No longer automatically request 1 ropsten ether for the first account in a new vault. - No longer automatically request 1 ropsten ether for the first account in a new vault.
- Now redirects from known malicious sites faster. - Now redirects from known malicious sites faster.
- Added a link to our new support page to the help screen. - Added a link to our new support page to the help screen.
- Fixed bug where a new transaction would be shown over the current transaction, creating a possible timing attack against user confirmation. - Fixed bug where a new transaction would be shown over the current transaction, creating a possible timing attack against user confirmation.
- Fixed bug in nonce tracker where an incorrect nonce would be calculated. - Fixed bug in nonce tracker where an incorrect nonce would be calculated.
- Lowered minimum gas price to 1 Gwei.
## 3.9.0 2017-7-12 ## 3.9.0 2017-7-12

View File

@ -1,4 +1,8 @@
# MetaMask Plugin [![Build Status](https://circleci.com/gh/MetaMask/metamask-extension.svg?style=shield&circle-token=a1ddcf3cd38e29267f254c9c59d556d513e3a1fd)](https://circleci.com/gh/MetaMask/metamask-extension) # MetaMask Plugin [![Build Status](https://circleci.com/gh/MetaMask/metamask-extension.svg?style=shield&circle-token=a1ddcf3cd38e29267f254c9c59d556d513e3a1fd)](https://circleci.com/gh/MetaMask/metamask-extension) [![Coverage Status](https://coveralls.io/repos/github/MetaMask/metamask-extension/badge.svg?branch=master)](https://coveralls.io/github/MetaMask/metamask-extension?branch=master)
## Support
If you're a user seeking support, [here is our support site](http://metamask.consensyssupport.happyfox.com).
[![Greenkeeper badge](https://badges.greenkeeper.io/MetaMask/metamask-extension.svg)](https://greenkeeper.io/) [![Greenkeeper badge](https://badges.greenkeeper.io/MetaMask/metamask-extension.svg)](https://greenkeeper.io/)
@ -6,7 +10,13 @@
If you're a web dapp developer, we've got two types of guides for you: If you're a web dapp developer, we've got two types of guides for you:
- If you've never built a Dapp before, we've got a gentle introduction on [Developing Dapps with Truffle and MetaMask](https://blog.metamask.io/developing-for-metamask-with-truffle/). ### New Dapp Developers
- We recommend this [Learning Solidity](https://karl.tech/learning-solidity-part-1-deploy-a-contract/) tutorial series by Karl Floersch.
- We wrote a (slightly outdated now) gentle introduction on [Developing Dapps with Truffle and MetaMask](https://medium.com/metamask/developing-ethereum-dapps-with-truffle-and-metamask-aa8ad7e363ba).
### Current Dapp Developers
- If you have a Dapp, and you want to ensure compatibility, [here is our guide on building MetaMask-compatible Dapps](https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md) - If you have a Dapp, and you want to ensure compatibility, [here is our guide on building MetaMask-compatible Dapps](https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md)
## Building locally ## Building locally

View File

@ -1,7 +1,7 @@
{ {
"name": "MetaMask", "name": "MetaMask",
"short_name": "Metamask", "short_name": "Metamask",
"version": "3.9.0", "version": "3.9.2",
"manifest_version": 2, "manifest_version": 2,
"author": "https://metamask.io", "author": "https://metamask.io",
"description": "Ethereum Browser Extension", "description": "Ethereum Browser Extension",
@ -52,11 +52,6 @@
], ],
"run_at": "document_start", "run_at": "document_start",
"all_frames": true "all_frames": true
},
{
"run_at": "document_start",
"matches": ["http://*/*", "https://*/*"],
"js": ["scripts/blacklister.js"]
} }
], ],
"permissions": [ "permissions": [

View File

@ -90,12 +90,12 @@ function setupController (initState) {
extension.runtime.onConnect.addListener(connectRemote) extension.runtime.onConnect.addListener(connectRemote)
function connectRemote (remotePort) { function connectRemote (remotePort) {
var isMetaMaskInternalProcess = remotePort.name === 'popup' || remotePort.name === 'notification' const isMetaMaskInternalProcess = remotePort.name === 'popup' || remotePort.name === 'notification'
var portStream = new PortStream(remotePort) const portStream = new PortStream(remotePort)
if (isMetaMaskInternalProcess) { if (isMetaMaskInternalProcess) {
// communication with popup // communication with popup
popupIsOpen = popupIsOpen || (remotePort.name === 'popup') popupIsOpen = popupIsOpen || (remotePort.name === 'popup')
controller.setupTrustedCommunication(portStream, 'MetaMask', remotePort.name) controller.setupTrustedCommunication(portStream, 'MetaMask')
// record popup as closed // record popup as closed
if (remotePort.name === 'popup') { if (remotePort.name === 'popup') {
endOfStream(portStream, () => { endOfStream(portStream, () => {
@ -104,7 +104,7 @@ function setupController (initState) {
} }
} else { } else {
// communication with page // communication with page
var originDomain = urlUtil.parse(remotePort.sender.url).hostname const originDomain = urlUtil.parse(remotePort.sender.url).hostname
controller.setupUntrustedCommunication(portStream, originDomain) controller.setupUntrustedCommunication(portStream, originDomain)
} }
} }
@ -121,7 +121,7 @@ function setupController (initState) {
// plugin badge text // plugin badge text
function updateBadge () { function updateBadge () {
var label = '' var label = ''
var unapprovedTxCount = controller.txController.unapprovedTxCount var unapprovedTxCount = controller.txController.getUnapprovedTxCount()
var unapprovedMsgCount = controller.messageManager.unapprovedMsgCount var unapprovedMsgCount = controller.messageManager.unapprovedMsgCount
var unapprovedPersonalMsgs = controller.personalMessageManager.unapprovedPersonalMsgCount var unapprovedPersonalMsgs = controller.personalMessageManager.unapprovedPersonalMsgCount
var count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgs var count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgs

View File

@ -1,13 +0,0 @@
const blacklistedDomains = require('etheraddresslookup/blacklists/domains.json')
function detectBlacklistedDomain() {
var strCurrentTab = window.location.hostname
if (blacklistedDomains && blacklistedDomains.includes(strCurrentTab)) {
window.location.href = 'https://metamask.io/phishing.html'
}
}
window.addEventListener('load', function() {
detectBlacklistedDomain()
})

View File

@ -37,28 +37,33 @@ function setupInjection () {
function setupStreams () { function setupStreams () {
// setup communication to page and plugin // setup communication to page and plugin
var pageStream = new LocalMessageDuplexStream({ const pageStream = new LocalMessageDuplexStream({
name: 'contentscript', name: 'contentscript',
target: 'inpage', target: 'inpage',
}) })
pageStream.on('error', console.error) pageStream.on('error', console.error)
var pluginPort = extension.runtime.connect({name: 'contentscript'}) const pluginPort = extension.runtime.connect({ name: 'contentscript' })
var pluginStream = new PortStream(pluginPort) const pluginStream = new PortStream(pluginPort)
pluginStream.on('error', console.error) pluginStream.on('error', console.error)
// forward communication plugin->inpage // forward communication plugin->inpage
pageStream.pipe(pluginStream).pipe(pageStream) pageStream.pipe(pluginStream).pipe(pageStream)
// setup local multistream channels // setup local multistream channels
var mx = ObjectMultiplex() const mx = ObjectMultiplex()
mx.on('error', console.error) mx.on('error', console.error)
mx.pipe(pageStream).pipe(mx) mx.pipe(pageStream).pipe(mx)
mx.pipe(pluginStream).pipe(mx)
// connect ping stream // connect ping stream
var pongStream = new PongStream({ objectMode: true }) const pongStream = new PongStream({ objectMode: true })
pongStream.pipe(mx.createStream('pingpong')).pipe(pongStream) pongStream.pipe(mx.createStream('pingpong')).pipe(pongStream)
// ignore unused channels (handled by background) // connect phishing warning stream
const phishingStream = mx.createStream('phishing')
phishingStream.once('data', redirectToPhishingWarning)
// ignore unused channels (handled by background, inpage)
mx.ignoreStream('provider') mx.ignoreStream('provider')
mx.ignoreStream('publicConfig') mx.ignoreStream('publicConfig')
} }
@ -88,3 +93,8 @@ function suffixCheck () {
} }
return true return true
} }
function redirectToPhishingWarning () {
console.log('MetaMask - redirecting to phishing warning')
window.location.href = 'https://metamask.io/phishing.html'
}

View File

@ -0,0 +1,58 @@
const ObservableStore = require('obs-store')
const extend = require('xtend')
const PhishingDetector = require('eth-phishing-detect/src/detector')
// compute phishing lists
const PHISHING_DETECTION_CONFIG = require('eth-phishing-detect/src/config.json')
// every ten minutes
const POLLING_INTERVAL = 10 * 60 * 1000
class BlacklistController {
constructor (opts = {}) {
const initState = extend({
phishing: PHISHING_DETECTION_CONFIG,
}, opts.initState)
this.store = new ObservableStore(initState)
// phishing detector
this._phishingDetector = null
this._setupPhishingDetector(initState.phishing)
// polling references
this._phishingUpdateIntervalRef = null
}
//
// PUBLIC METHODS
//
checkForPhishing (hostname) {
if (!hostname) return false
const { result } = this._phishingDetector.check(hostname)
return result
}
async updatePhishingList () {
const response = await fetch('https://api.infura.io/v2/blacklist')
const phishing = await response.json()
this.store.updateState({ phishing })
this._setupPhishingDetector(phishing)
return phishing
}
scheduleUpdates () {
if (this._phishingUpdateIntervalRef) return
this._phishingUpdateIntervalRef = setInterval(() => {
this.updatePhishingList()
}, POLLING_INTERVAL)
}
//
// PRIVATE METHODS
//
_setupPhishingDetector (config) {
this._phishingDetector = new PhishingDetector(config)
}
}
module.exports = BlacklistController

View File

@ -2,7 +2,7 @@ const ObservableStore = require('obs-store')
const extend = require('xtend') const extend = require('xtend')
// every ten minutes // every ten minutes
const POLLING_INTERVAL = 300000 const POLLING_INTERVAL = 10 * 60 * 1000
class InfuraController { class InfuraController {

View File

@ -28,9 +28,9 @@ module.exports = class NetworkController extends EventEmitter {
this._provider = provider this._provider = provider
} }
initializeProvider (opts) { initializeProvider (opts, providerContructor = MetaMaskProvider) {
this.providerInit = opts this.providerInit = opts
this._provider = MetaMaskProvider(opts) this._provider = providerContructor(opts)
this._proxy = new Proxy(this._provider, { this._proxy = new Proxy(this._provider, {
get: (obj, name) => { get: (obj, name) => {
if (name === 'on') return this._on.bind(this) if (name === 'on') return this._on.bind(this)
@ -38,6 +38,7 @@ module.exports = class NetworkController extends EventEmitter {
}, },
set: (obj, name, value) => { set: (obj, name, value) => {
this._provider[name] = value this._provider[name] = value
return value
}, },
}) })
this.provider.on('block', this._logBlock.bind(this)) this.provider.on('block', this._logBlock.bind(this))

View File

@ -1,9 +1,9 @@
const EventEmitter = require('events') const EventEmitter = require('events')
const async = require('async')
const extend = require('xtend') const extend = require('xtend')
const clone = require('clone')
const ObservableStore = require('obs-store') const ObservableStore = require('obs-store')
const ethUtil = require('ethereumjs-util') const ethUtil = require('ethereumjs-util')
const pify = require('pify') const EthQuery = require('ethjs-query')
const TxProviderUtil = require('../lib/tx-utils') const TxProviderUtil = require('../lib/tx-utils')
const createId = require('../lib/random-id') const createId = require('../lib/random-id')
const NonceTracker = require('../lib/nonce-tracker') const NonceTracker = require('../lib/nonce-tracker')
@ -22,7 +22,6 @@ module.exports = class TransactionController extends EventEmitter {
this.blockTracker = opts.blockTracker this.blockTracker = opts.blockTracker
this.nonceTracker = new NonceTracker({ this.nonceTracker = new NonceTracker({
provider: this.provider, provider: this.provider,
blockTracker: this.provider._blockTracker,
getPendingTransactions: (address) => { getPendingTransactions: (address) => {
return this.getFilteredTxList({ return this.getFilteredTxList({
from: address, from: address,
@ -31,7 +30,7 @@ module.exports = class TransactionController extends EventEmitter {
}) })
}, },
}) })
this.query = opts.ethQuery this.query = new EthQuery(this.provider)
this.txProviderUtils = new TxProviderUtil(this.query) this.txProviderUtils = new TxProviderUtil(this.query)
this.blockTracker.on('rawBlock', this.checkForTxInBlock.bind(this)) this.blockTracker.on('rawBlock', this.checkForTxInBlock.bind(this))
// this is a little messy but until ethstore has been either // this is a little messy but until ethstore has been either
@ -60,13 +59,6 @@ module.exports = class TransactionController extends EventEmitter {
return this.preferencesStore.getState().selectedAddress return this.preferencesStore.getState().selectedAddress
} }
// Returns the tx list
getTxList () {
const network = this.getNetwork()
const fullTxList = this.getFullTxList()
return fullTxList.filter(txMeta => txMeta.metamaskNetworkId === network)
}
// Returns the number of txs for the current network. // Returns the number of txs for the current network.
getTxCount () { getTxCount () {
return this.getTxList().length return this.getTxList().length
@ -77,6 +69,56 @@ module.exports = class TransactionController extends EventEmitter {
return this.store.getState().transactions return this.store.getState().transactions
} }
getUnapprovedTxCount () {
return Object.keys(this.getUnapprovedTxList()).length
}
getPendingTxCount () {
return this.getTxsByMetaData('status', 'signed').length
}
// Returns the tx list
getTxList () {
const network = this.getNetwork()
const fullTxList = this.getFullTxList()
return this.getTxsByMetaData('metamaskNetworkId', network, fullTxList)
}
// gets tx by Id and returns it
getTx (txId) {
const txList = this.getTxList()
const txMeta = txList.find(txData => txData.id === txId)
return txMeta
}
getUnapprovedTxList () {
const txList = this.getTxList()
return txList.filter((txMeta) => txMeta.status === 'unapproved')
.reduce((result, tx) => {
result[tx.id] = tx
return result
}, {})
}
updateTx (txMeta) {
// create txMeta snapshot for history
const txMetaForHistory = clone(txMeta)
// dont include previous history in this snapshot
delete txMetaForHistory.history
// add snapshot to tx history
if (!txMeta.history) txMeta.history = []
txMeta.history.push(txMetaForHistory)
const txId = txMeta.id
const txList = this.getFullTxList()
const index = txList.findIndex(txData => txData.id === txId)
if (!txMeta.history) txMeta.history = []
txMeta.history.push(txMetaForHistory)
txList[index] = txMeta
this._saveTxList(txList)
this.emit('update')
}
// Adds a tx to the txlist // Adds a tx to the txlist
addTx (txMeta) { addTx (txMeta) {
const txCount = this.getTxCount() const txCount = this.getTxCount()
@ -90,7 +132,7 @@ module.exports = class TransactionController extends EventEmitter {
// or rejected tx's. // or rejected tx's.
// not tx's that are pending or unapproved // not tx's that are pending or unapproved
if (txCount > txHistoryLimit - 1) { if (txCount > txHistoryLimit - 1) {
var index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId)) const index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId))
fullTxList.splice(index, 1) fullTxList.splice(index, 1)
} }
fullTxList.push(txMeta) fullTxList.push(txMeta)
@ -108,79 +150,59 @@ module.exports = class TransactionController extends EventEmitter {
this.emit(`${txMeta.id}:unapproved`, txMeta) this.emit(`${txMeta.id}:unapproved`, txMeta)
} }
// gets tx by Id and returns it async newUnapprovedTransaction (txParams) {
getTx (txId, cb) { log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
var txList = this.getTxList() const txMeta = await this.addUnapprovedTransaction(txParams)
var txMeta = txList.find(txData => txData.id === txId) this.emit('newUnaprovedTx', txMeta)
return cb ? cb(txMeta) : txMeta // listen for tx completion (success, fail)
} return new Promise((resolve, reject) => {
this.once(`${txMeta.id}:finished`, (completedTx) => {
// switch (completedTx.status) {
updateTx (txMeta) { case 'submitted':
var txId = txMeta.id return resolve(completedTx.hash)
var txList = this.getFullTxList() case 'rejected':
var index = txList.findIndex(txData => txData.id === txId) return reject(new Error('MetaMask Tx Signature: User denied transaction signature.'))
txList[index] = txMeta default:
this._saveTxList(txList) return reject(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(completedTx.txParams)}`))
this.emit('update')
}
get unapprovedTxCount () {
return Object.keys(this.getUnapprovedTxList()).length
}
get pendingTxCount () {
return this.getTxsByMetaData('status', 'signed').length
}
addUnapprovedTransaction (txParams, done) {
let txMeta
async.waterfall([
// validate
(cb) => this.txProviderUtils.validateTxParams(txParams, cb),
// construct txMeta
(cb) => {
txMeta = {
id: createId(),
time: (new Date()).getTime(),
status: 'unapproved',
metamaskNetworkId: this.getNetwork(),
txParams: txParams,
} }
cb() })
}, })
// add default tx params
(cb) => this.addTxDefaults(txMeta, cb),
// save txMeta
(cb) => {
this.addTx(txMeta)
cb(null, txMeta)
},
], done)
} }
addTxDefaults (txMeta, cb) { async addUnapprovedTransaction (txParams) {
// validate
await this.txProviderUtils.validateTxParams(txParams)
// construct txMeta
const txMeta = {
id: createId(),
time: (new Date()).getTime(),
status: 'unapproved',
metamaskNetworkId: this.getNetwork(),
txParams: txParams,
history: [],
}
// add default tx params
await this.addTxDefaults(txMeta)
// save txMeta
this.addTx(txMeta)
return txMeta
}
async addTxDefaults (txMeta) {
const txParams = txMeta.txParams const txParams = txMeta.txParams
// ensure value // ensure value
txParams.value = txParams.value || '0x0' txParams.value = txParams.value || '0x0'
if (!txParams.gasPrice) { if (!txParams.gasPrice) {
this.query.gasPrice((err, gasPrice) => { const gasPrice = await this.query.gasPrice()
if (err) return cb(err) txParams.gasPrice = gasPrice
// set gasPrice
txParams.gasPrice = gasPrice
})
} }
// set gasLimit // set gasLimit
this.txProviderUtils.analyzeGasUsage(txMeta, cb) return await this.txProviderUtils.analyzeGasUsage(txMeta)
} }
getUnapprovedTxList () { async updateAndApproveTransaction (txMeta) {
var txList = this.getTxList() this.updateTx(txMeta)
return txList.filter((txMeta) => txMeta.status === 'unapproved') await this.approveTransaction(txMeta.id)
.reduce((result, tx) => {
result[tx.id] = tx
return result
}, {})
} }
async approveTransaction (txId) { async approveTransaction (txId) {
@ -191,8 +213,12 @@ module.exports = class TransactionController extends EventEmitter {
// get next nonce // get next nonce
const txMeta = this.getTx(txId) const txMeta = this.getTx(txId)
const fromAddress = txMeta.txParams.from const fromAddress = txMeta.txParams.from
// wait for a nonce
nonceLock = await this.nonceTracker.getNonceLock(fromAddress) nonceLock = await this.nonceTracker.getNonceLock(fromAddress)
// add nonce to txParams
txMeta.txParams.nonce = nonceLock.nextNonce txMeta.txParams.nonce = nonceLock.nextNonce
// add nonce debugging information to txMeta
txMeta.nonceDetails = nonceLock.nonceDetails
this.updateTx(txMeta) this.updateTx(txMeta)
// sign transaction // sign transaction
const rawTx = await this.signTransaction(txId) const rawTx = await this.signTransaction(txId)
@ -201,6 +227,7 @@ module.exports = class TransactionController extends EventEmitter {
nonceLock.releaseLock() nonceLock.releaseLock()
} catch (err) { } catch (err) {
this.setTxStatusFailed(txId, { this.setTxStatusFailed(txId, {
stack: err.stack || err.message,
errCode: err.errCode || err, errCode: err.errCode || err,
message: err.message || 'Transaction failed during approval', message: err.message || 'Transaction failed during approval',
}) })
@ -211,16 +238,33 @@ module.exports = class TransactionController extends EventEmitter {
} }
} }
cancelTransaction (txId, cb = warn) { async signTransaction (txId) {
this.setTxStatusRejected(txId) const txMeta = this.getTx(txId)
cb() const txParams = txMeta.txParams
const fromAddress = txParams.from
// add network/chain id
txParams.chainId = this.getChainId()
const ethTx = this.txProviderUtils.buildEthTxFromParams(txParams)
await this.signEthTx(ethTx, fromAddress)
this.setTxStatusSigned(txMeta.id)
const rawTx = ethUtil.bufferToHex(ethTx.serialize())
return rawTx
} }
async updateAndApproveTransaction (txMeta) { async publishTransaction (txId, rawTx) {
const txMeta = this.getTx(txId)
txMeta.rawTx = rawTx
this.updateTx(txMeta) this.updateTx(txMeta)
await this.approveTransaction(txMeta.id) const txHash = await this.txProviderUtils.publishTransaction(rawTx)
this.setTxHash(txId, txHash)
this.setTxStatusSubmitted(txId)
} }
async cancelTransaction (txId) {
this.setTxStatusRejected(txId)
}
getChainId () { getChainId () {
const networkState = this.networkStore.getState() const networkState = this.networkStore.getState()
const getChainId = parseInt(networkState) const getChainId = parseInt(networkState)
@ -231,30 +275,6 @@ module.exports = class TransactionController extends EventEmitter {
} }
} }
async signTransaction (txId) {
const txMeta = this.getTx(txId)
const txParams = txMeta.txParams
const fromAddress = txParams.from
// add network/chain id
txParams.chainId = this.getChainId()
const ethTx = this.txProviderUtils.buildEthTxFromParams(txParams)
const rawTx = await this.signEthTx(ethTx, fromAddress).then(() => {
this.setTxStatusSigned(txMeta.id)
return ethUtil.bufferToHex(ethTx.serialize())
})
return rawTx
}
async publishTransaction (txId, rawTx) {
const txMeta = this.getTx(txId)
txMeta.rawTx = rawTx
this.updateTx(txMeta)
await this.txProviderUtils.publishTransaction(rawTx).then((txHash) => {
this.setTxHash(txId, txHash)
this.setTxStatusSubmitted(txId)
})
}
// receives a txHash records the tx as signed // receives a txHash records the tx as signed
setTxHash (txId, txHash) { setTxHash (txId, txHash) {
// Add the tx hash to the persisted meta-tx object // Add the tx hash to the persisted meta-tx object
@ -265,7 +285,7 @@ module.exports = class TransactionController extends EventEmitter {
/* /*
Takes an object of fields to search for eg: Takes an object of fields to search for eg:
var thingsToLookFor = { let thingsToLookFor = {
to: '0x0..', to: '0x0..',
from: '0x0..', from: '0x0..',
status: 'signed', status: 'signed',
@ -288,7 +308,7 @@ module.exports = class TransactionController extends EventEmitter {
and that have been 'confirmed' and that have been 'confirmed'
*/ */
getFilteredTxList (opts) { getFilteredTxList (opts) {
var filteredTxList let filteredTxList
Object.keys(opts).forEach((key) => { Object.keys(opts).forEach((key) => {
filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList) filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList)
}) })
@ -349,7 +369,7 @@ module.exports = class TransactionController extends EventEmitter {
// merges txParams obj onto txData.txParams // merges txParams obj onto txData.txParams
// use extend to ensure that all fields are filled // use extend to ensure that all fields are filled
updateTxParams (txId, txParams) { updateTxParams (txId, txParams) {
var txMeta = this.getTx(txId) const txMeta = this.getTx(txId)
txMeta.txParams = extend(txMeta.txParams, txParams) txMeta.txParams = extend(txMeta.txParams, txParams)
this.updateTx(txMeta) this.updateTx(txMeta)
} }
@ -357,20 +377,19 @@ module.exports = class TransactionController extends EventEmitter {
// checks if a signed tx is in a block and // checks if a signed tx is in a block and
// if included sets the tx status as 'confirmed' // if included sets the tx status as 'confirmed'
checkForTxInBlock (block) { checkForTxInBlock (block) {
var signedTxList = this.getFilteredTxList({status: 'submitted'}) const signedTxList = this.getFilteredTxList({status: 'submitted'})
if (!signedTxList.length) return if (!signedTxList.length) return
signedTxList.forEach((txMeta) => { signedTxList.forEach((txMeta) => {
var txHash = txMeta.hash const txHash = txMeta.hash
var txId = txMeta.id const txId = txMeta.id
if (!txHash) { if (!txHash) {
const errReason = { const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.')
errCode: 'No hash was provided', noTxHashErr.name = 'NoTxHashError'
message: 'We had an error while submitting this transaction, please try again.', this.setTxStatusFailed(txId, noTxHashErr)
}
return this.setTxStatusFailed(txId, errReason)
} }
block.transactions.forEach((tx) => { block.transactions.forEach((tx) => {
if (tx.hash === txHash) this.setTxStatusConfirmed(txId) if (tx.hash === txHash) this.setTxStatusConfirmed(txId)
}) })
@ -388,44 +407,6 @@ module.exports = class TransactionController extends EventEmitter {
if (diff > 1) this._checkPendingTxs() if (diff > 1) this._checkPendingTxs()
} }
// PRIVATE METHODS
// Should find the tx in the tx list and
// update it.
// should set the status in txData
// - `'unapproved'` the user has not responded
// - `'rejected'` the user has responded no!
// - `'approved'` the user has approved the tx
// - `'signed'` the tx is signed
// - `'submitted'` the tx is sent to a server
// - `'confirmed'` the tx has been included in a block.
// - `'failed'` the tx failed for some reason, included on tx data.
_setTxStatus (txId, status) {
var txMeta = this.getTx(txId)
txMeta.status = status
this.emit(`${txMeta.id}:${status}`, txId)
if (status === 'submitted' || status === 'rejected') {
this.emit(`${txMeta.id}:finished`, txMeta)
}
this.updateTx(txMeta)
this.emit('updateBadge')
}
// Saves the new/updated txList.
// Function is intended only for internal use
_saveTxList (transactions) {
this.store.updateState({ transactions })
}
_updateMemstore () {
const unapprovedTxs = this.getUnapprovedTxList()
const selectedAddressTxList = this.getFilteredTxList({
from: this.getSelectedAddress(),
metamaskNetworkId: this.getNetwork(),
})
this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
}
resubmitPendingTxs () { resubmitPendingTxs () {
const pending = this.getTxsByMetaData('status', 'submitted') const pending = this.getTxsByMetaData('status', 'submitted')
// only try resubmitting if their are transactions to resubmit // only try resubmitting if their are transactions to resubmit
@ -452,13 +433,57 @@ module.exports = class TransactionController extends EventEmitter {
if (isKnownTx) return if (isKnownTx) return
// encountered real error - transition to error state // encountered real error - transition to error state
this.setTxStatusFailed(txMeta.id, { this.setTxStatusFailed(txMeta.id, {
stack: err.stack || err.message,
errCode: err.errCode || err, errCode: err.errCode || err,
message: err.message, message: err.message,
}) })
})) }))
} }
async _resubmitTx (txMeta, cb) {
/* _____________________________________
| |
| PRIVATE METHODS |
|______________________________________*/
// Should find the tx in the tx list and
// update it.
// should set the status in txData
// - `'unapproved'` the user has not responded
// - `'rejected'` the user has responded no!
// - `'approved'` the user has approved the tx
// - `'signed'` the tx is signed
// - `'submitted'` the tx is sent to a server
// - `'confirmed'` the tx has been included in a block.
// - `'failed'` the tx failed for some reason, included on tx data.
_setTxStatus (txId, status) {
const txMeta = this.getTx(txId)
txMeta.status = status
this.emit(`${txMeta.id}:${status}`, txId)
if (status === 'submitted' || status === 'rejected') {
this.emit(`${txMeta.id}:finished`, txMeta)
}
this.updateTx(txMeta)
this.emit('updateBadge')
}
// Saves the new/updated txList.
// Function is intended only for internal use
_saveTxList (transactions) {
this.store.updateState({ transactions })
}
_updateMemstore () {
const unapprovedTxs = this.getUnapprovedTxList()
const selectedAddressTxList = this.getFilteredTxList({
from: this.getSelectedAddress(),
metamaskNetworkId: this.getNetwork(),
})
this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
}
async _resubmitTx (txMeta) {
const address = txMeta.txParams.from const address = txMeta.txParams.from
const balance = this.ethStore.getState().accounts[address].balance const balance = this.ethStore.getState().accounts[address].balance
if (!('retryCount' in txMeta)) txMeta.retryCount = 0 if (!('retryCount' in txMeta)) txMeta.retryCount = 0
@ -466,18 +491,21 @@ module.exports = class TransactionController extends EventEmitter {
// if the value of the transaction is greater then the balance, fail. // if the value of the transaction is greater then the balance, fail.
if (!this.txProviderUtils.sufficientBalance(txMeta.txParams, balance)) { if (!this.txProviderUtils.sufficientBalance(txMeta.txParams, balance)) {
const message = 'Insufficient balance.' const message = 'Insufficient balance.'
this.setTxStatusFailed(txMeta.id, { message }) this.setTxStatusFailed(txMeta.id, {
cb() stack: '_resubmitTx: custom tx-controller error',
return log.error(message) message,
})
log.error(message)
return
} }
// Only auto-submit already-signed txs: // Only auto-submit already-signed txs:
if (!('rawTx' in txMeta)) return cb() if (!('rawTx' in txMeta)) return
// Increment a try counter. // Increment a try counter.
txMeta.retryCount++ txMeta.retryCount++
const rawTx = txMeta.rawTx const rawTx = txMeta.rawTx
return await this.txProviderUtils.publishTransaction(rawTx, cb) return await this.txProviderUtils.publishTransaction(rawTx)
} }
// checks the network for signed txs and // checks the network for signed txs and
@ -501,17 +529,14 @@ module.exports = class TransactionController extends EventEmitter {
// extra check in case there was an uncaught error during the // extra check in case there was an uncaught error during the
// signature and submission process // signature and submission process
if (!txHash) { if (!txHash) {
const errReason = { const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.')
errCode: 'No hash was provided', noTxHashErr.name = 'NoTxHashError'
message: 'We had an error while submitting this transaction, please try again.', this.setTxStatusFailed(txId, noTxHashErr)
}
this.setTxStatusFailed(txId, errReason)
return
} }
// get latest transaction status // get latest transaction status
let txParams let txParams
try { try {
txParams = await pify((cb) => this.query.getTransactionByHash(txHash, cb))() txParams = await this.query.getTransactionByHash(txHash)
if (!txParams) return if (!txParams) return
if (txParams.blockNumber) { if (txParams.blockNumber) {
this.setTxStatusConfirmed(txId) this.setTxStatusConfirmed(txId)
@ -524,12 +549,8 @@ module.exports = class TransactionController extends EventEmitter {
message: 'There was a problem loading this transaction.', message: 'There was a problem loading this transaction.',
} }
this.updateTx(txMeta) this.updateTx(txMeta)
log.error(err) throw err
} }
} }
} }
}
}
const warn = () => log.warn('warn was used no cb provided')

View File

@ -65,3 +65,4 @@ function restoreContextAfterImports () {
console.warn('MetaMask - global.define could not be overwritten.') console.warn('MetaMask - global.define could not be overwritten.')
} }
} }

View File

@ -26,6 +26,9 @@ function MetamaskInpageProvider (connectionStream) {
(err) => logStreamDisconnectWarning('MetaMask PublicConfigStore', err) (err) => logStreamDisconnectWarning('MetaMask PublicConfigStore', err)
) )
// ignore phishing warning message (handled elsewhere)
multiStream.ignoreStream('phishing')
// connect to async provider // connect to async provider
const asyncProvider = self.asyncProvider = new StreamProvider() const asyncProvider = self.asyncProvider = new StreamProvider()
pipe( pipe(

View File

@ -4,8 +4,8 @@ const Mutex = require('await-semaphore').Mutex
class NonceTracker { class NonceTracker {
constructor ({ blockTracker, provider, getPendingTransactions }) { constructor ({ provider, getPendingTransactions }) {
this.blockTracker = blockTracker this.provider = provider
this.ethQuery = new EthQuery(provider) this.ethQuery = new EthQuery(provider)
this.getPendingTransactions = getPendingTransactions this.getPendingTransactions = getPendingTransactions
this.lockMap = {} this.lockMap = {}
@ -31,21 +31,25 @@ class NonceTracker {
const currentBlock = await this._getCurrentBlock() const currentBlock = await this._getCurrentBlock()
const pendingTransactions = this.getPendingTransactions(address) const pendingTransactions = this.getPendingTransactions(address)
const pendingCount = pendingTransactions.length const pendingCount = pendingTransactions.length
assert(Number.isInteger(pendingCount), 'nonce-tracker - pendingCount is an integer') assert(Number.isInteger(pendingCount), `nonce-tracker - pendingCount is not an integer - got: (${typeof pendingCount}) "${pendingCount}"`)
const baseCountHex = await this._getTxCount(address, currentBlock) const baseCountHex = await this._getTxCount(address, currentBlock)
const baseCount = parseInt(baseCountHex, 16) const baseCount = parseInt(baseCountHex, 16)
assert(Number.isInteger(baseCount), 'nonce-tracker - baseCount is an integer') assert(Number.isInteger(baseCount), `nonce-tracker - baseCount is not an integer - got: (${typeof baseCount}) "${baseCount}"`)
const nextNonce = baseCount + pendingCount const nextNonce = baseCount + pendingCount
assert(Number.isInteger(nextNonce), 'nonce-tracker - nextNonce is an integer') assert(Number.isInteger(nextNonce), `nonce-tracker - nextNonce is not an integer - got: (${typeof nextNonce}) "${nextNonce}"`)
// return next nonce and release cb // collect the numbers used to calculate the nonce for debugging
return { nextNonce, releaseLock } const blockNumber = currentBlock.number
const nonceDetails = { blockNumber, baseCount, baseCountHex, pendingCount }
// return nonce and release cb
return { nextNonce, nonceDetails, releaseLock }
} }
async _getCurrentBlock () { async _getCurrentBlock () {
const currentBlock = this.blockTracker.getCurrentBlock() const blockTracker = this._getBlockTracker()
const currentBlock = blockTracker.getCurrentBlock()
if (currentBlock) return currentBlock if (currentBlock) return currentBlock
return await Promise((reject, resolve) => { return await Promise((reject, resolve) => {
this.blockTracker.once('latest', resolve) blockTracker.once('latest', resolve)
}) })
} }
@ -79,6 +83,12 @@ class NonceTracker {
return mutex return mutex
} }
// this is a hotfix for the fact that the blockTracker will
// change when the network changes
_getBlockTracker () {
return this.provider._blockTracker
}
} }
module.exports = NonceTracker module.exports = NonceTracker

View File

@ -5,12 +5,16 @@ module.exports = ObjectMultiplex
function ObjectMultiplex (opts) { function ObjectMultiplex (opts) {
opts = opts || {} opts = opts || {}
// create multiplexer // create multiplexer
var mx = through.obj(function (chunk, enc, cb) { const mx = through.obj(function (chunk, enc, cb) {
var name = chunk.name const name = chunk.name
var data = chunk.data const data = chunk.data
var substream = mx.streams[name] if (!name) {
console.warn(`ObjectMultiplex - Malformed chunk without name "${chunk}"`)
return cb()
}
const substream = mx.streams[name]
if (!substream) { if (!substream) {
console.warn(`orphaned data for stream "${name}"`) console.warn(`ObjectMultiplex - orphaned data for stream "${name}"`)
} else { } else {
if (substream.push) substream.push(data) if (substream.push) substream.push(data)
} }
@ -19,7 +23,7 @@ function ObjectMultiplex (opts) {
mx.streams = {} mx.streams = {}
// create substreams // create substreams
mx.createStream = function (name) { mx.createStream = function (name) {
var substream = mx.streams[name] = through.obj(function (chunk, enc, cb) { const substream = mx.streams[name] = through.obj(function (chunk, enc, cb) {
mx.push({ mx.push({
name: name, name: name,
data: chunk, data: chunk,

View File

@ -1,4 +1,3 @@
const async = require('async')
const ethUtil = require('ethereumjs-util') const ethUtil = require('ethereumjs-util')
const Transaction = require('ethereumjs-tx') const Transaction = require('ethereumjs-tx')
const normalize = require('eth-sig-util').normalize const normalize = require('eth-sig-util').normalize
@ -10,24 +9,19 @@ its passed ethquery
and used to do things like calculate gas of a tx. and used to do things like calculate gas of a tx.
*/ */
module.exports = class txProviderUtils { module.exports = class txProvideUtils {
constructor (ethQuery) { constructor (ethQuery) {
this.query = ethQuery this.query = ethQuery
} }
analyzeGasUsage (txMeta, cb) { async analyzeGasUsage (txMeta) {
var self = this const block = await this.query.getBlockByNumber('latest', true)
this.query.getBlockByNumber('latest', true, (err, block) => { const estimatedGasHex = await this.estimateTxGas(txMeta, block.gasLimit)
if (err) return cb(err) this.setTxGas(txMeta, block.gasLimit, estimatedGasHex)
async.waterfall([ return txMeta
self.estimateTxGas.bind(self, txMeta, block.gasLimit),
self.setTxGas.bind(self, txMeta, block.gasLimit),
], cb)
})
} }
estimateTxGas (txMeta, blockGasLimitHex, cb) { async estimateTxGas (txMeta, blockGasLimitHex) {
const txParams = txMeta.txParams const txParams = txMeta.txParams
// check if gasLimit is already specified // check if gasLimit is already specified
txMeta.gasLimitSpecified = Boolean(txParams.gas) txMeta.gasLimitSpecified = Boolean(txParams.gas)
@ -38,10 +32,10 @@ module.exports = class txProviderUtils {
txParams.gas = bnToHex(saferGasLimitBN) txParams.gas = bnToHex(saferGasLimitBN)
} }
// run tx, see if it will OOG // run tx, see if it will OOG
this.query.estimateGas(txParams, cb) return this.query.estimateGas(txParams)
} }
setTxGas (txMeta, blockGasLimitHex, estimatedGasHex, cb) { setTxGas (txMeta, blockGasLimitHex, estimatedGasHex) {
txMeta.estimatedGas = estimatedGasHex txMeta.estimatedGas = estimatedGasHex
const txParams = txMeta.txParams const txParams = txMeta.txParams
@ -49,14 +43,12 @@ module.exports = class txProviderUtils {
// use original specified amount // use original specified amount
if (txMeta.gasLimitSpecified) { if (txMeta.gasLimitSpecified) {
txMeta.estimatedGas = txParams.gas txMeta.estimatedGas = txParams.gas
cb()
return return
} }
// if gasLimit not originally specified, // if gasLimit not originally specified,
// try adding an additional gas buffer to our estimation for safety // try adding an additional gas buffer to our estimation for safety
const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex) const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex)
txParams.gas = recommendedGasHex txParams.gas = recommendedGasHex
cb()
return return
} }
@ -74,22 +66,6 @@ module.exports = class txProviderUtils {
return bnToHex(upperGasLimitBn) return bnToHex(upperGasLimitBn)
} }
fillInTxParams (txParams, cb) {
const fromAddress = txParams.from
const reqs = {}
if (isUndef(txParams.gas)) reqs.gas = (cb) => this.query.estimateGas(txParams, cb)
if (isUndef(txParams.gasPrice)) reqs.gasPrice = (cb) => this.query.gasPrice(cb)
if (isUndef(txParams.nonce)) reqs.nonce = (cb) => this.query.getTransactionCount(fromAddress, 'pending', cb)
async.parallel(reqs, function (err, result) {
if (err) return cb(err)
// write results to txParams obj
Object.assign(txParams, result)
cb()
})
}
// builds ethTx from txParams object // builds ethTx from txParams object
buildEthTxFromParams (txParams) { buildEthTxFromParams (txParams) {
// normalize values // normalize values
@ -106,20 +82,13 @@ module.exports = class txProviderUtils {
return ethTx return ethTx
} }
publishTransaction (rawTx) { async publishTransaction (rawTx) {
return new Promise((resolve, reject) => { return await this.query.sendRawTransaction(rawTx)
this.query.sendRawTransaction(rawTx, (err, ress) => {
if (err) reject(err)
else resolve(ress)
})
})
} }
validateTxParams (txParams, cb) { async validateTxParams (txParams) {
if (('value' in txParams) && txParams.value.indexOf('-') === 0) { if (('value' in txParams) && txParams.value.indexOf('-') === 0) {
cb(new Error(`Invalid transaction value of ${txParams.value} not a positive number.`)) throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`)
} else {
cb()
} }
} }
@ -137,10 +106,6 @@ module.exports = class txProviderUtils {
// util // util
function isUndef (value) {
return value === undefined
}
function bnToHex (inputBn) { function bnToHex (inputBn) {
return ethUtil.addHexPrefix(inputBn.toString(16)) return ethUtil.addHexPrefix(inputBn.toString(16))
} }

8
app/scripts/lib/util.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
getStack,
}
function getStack () {
const stack = new Error('Stack trace generator - not an error').stack
return stack
}

View File

@ -16,6 +16,7 @@ const NoticeController = require('./notice-controller')
const ShapeShiftController = require('./controllers/shapeshift') const ShapeShiftController = require('./controllers/shapeshift')
const AddressBookController = require('./controllers/address-book') const AddressBookController = require('./controllers/address-book')
const InfuraController = require('./controllers/infura') const InfuraController = require('./controllers/infura')
const BlacklistController = require('./controllers/blacklist')
const MessageManager = require('./lib/message-manager') const MessageManager = require('./lib/message-manager')
const PersonalMessageManager = require('./lib/personal-message-manager') const PersonalMessageManager = require('./lib/personal-message-manager')
const TransactionController = require('./controllers/transactions') const TransactionController = require('./controllers/transactions')
@ -69,6 +70,10 @@ module.exports = class MetamaskController extends EventEmitter {
}) })
this.infuraController.scheduleInfuraNetworkCheck() this.infuraController.scheduleInfuraNetworkCheck()
this.blacklistController = new BlacklistController({
initState: initState.BlacklistController,
})
this.blacklistController.scheduleUpdates()
// rpc provider // rpc provider
this.provider = this.initializeProvider() this.provider = this.initializeProvider()
@ -108,6 +113,7 @@ module.exports = class MetamaskController extends EventEmitter {
ethQuery: this.ethQuery, ethQuery: this.ethQuery,
ethStore: this.ethStore, ethStore: this.ethStore,
}) })
this.txController.on('newUnaprovedTx', opts.showUnapprovedTx.bind(opts))
// notices // notices
this.noticeController = new NoticeController({ this.noticeController = new NoticeController({
@ -151,6 +157,9 @@ module.exports = class MetamaskController extends EventEmitter {
this.networkController.store.subscribe((state) => { this.networkController.store.subscribe((state) => {
this.store.updateState({ NetworkController: state }) this.store.updateState({ NetworkController: state })
}) })
this.blacklistController.store.subscribe((state) => {
this.store.updateState({ BlacklistController: state })
})
this.infuraController.store.subscribe((state) => { this.infuraController.store.subscribe((state) => {
this.store.updateState({ InfuraController: state }) this.store.updateState({ InfuraController: state })
}) })
@ -195,7 +204,7 @@ module.exports = class MetamaskController extends EventEmitter {
cb(null, result) cb(null, result)
}, },
// tx signing // tx signing
processTransaction: (txParams, cb) => this.newUnapprovedTransaction(txParams, cb), processTransaction: nodeify(async (txParams) => await this.txController.newUnapprovedTransaction(txParams), this),
// old style msg signing // old style msg signing
processMessage: this.newUnsignedMessage.bind(this), processMessage: this.newUnsignedMessage.bind(this),
@ -308,7 +317,7 @@ module.exports = class MetamaskController extends EventEmitter {
exportAccount: nodeify(keyringController.exportAccount, keyringController), exportAccount: nodeify(keyringController.exportAccount, keyringController),
// txController // txController
cancelTransaction: txController.cancelTransaction.bind(txController), cancelTransaction: nodeify(txController.cancelTransaction, txController),
updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController), updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController),
// messageManager // messageManager
@ -326,8 +335,15 @@ module.exports = class MetamaskController extends EventEmitter {
} }
setupUntrustedCommunication (connectionStream, originDomain) { setupUntrustedCommunication (connectionStream, originDomain) {
// Check if new connection is blacklisted
if (this.blacklistController.checkForPhishing(originDomain)) {
console.log('MetaMask - sending phishing warning for', originDomain)
this.sendPhishingWarning(connectionStream, originDomain)
return
}
// setup multiplexing // setup multiplexing
var mx = setupMultiplex(connectionStream) const mx = setupMultiplex(connectionStream)
// connect features // connect features
this.setupProviderConnection(mx.createStream('provider'), originDomain) this.setupProviderConnection(mx.createStream('provider'), originDomain)
this.setupPublicConfig(mx.createStream('publicConfig')) this.setupPublicConfig(mx.createStream('publicConfig'))
@ -335,12 +351,18 @@ module.exports = class MetamaskController extends EventEmitter {
setupTrustedCommunication (connectionStream, originDomain) { setupTrustedCommunication (connectionStream, originDomain) {
// setup multiplexing // setup multiplexing
var mx = setupMultiplex(connectionStream) const mx = setupMultiplex(connectionStream)
// connect features // connect features
this.setupControllerConnection(mx.createStream('controller')) this.setupControllerConnection(mx.createStream('controller'))
this.setupProviderConnection(mx.createStream('provider'), originDomain) this.setupProviderConnection(mx.createStream('provider'), originDomain)
} }
sendPhishingWarning (connectionStream, hostname) {
const mx = setupMultiplex(connectionStream)
const phishingStream = mx.createStream('phishing')
phishingStream.write({ hostname })
}
setupControllerConnection (outStream) { setupControllerConnection (outStream) {
const api = this.getApi() const api = this.getApi()
const dnode = Dnode(api) const dnode = Dnode(api)
@ -440,27 +462,6 @@ module.exports = class MetamaskController extends EventEmitter {
// Identity Management // Identity Management
// //
newUnapprovedTransaction (txParams, cb) {
log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
const self = this
self.txController.addUnapprovedTransaction(txParams, (err, txMeta) => {
if (err) return cb(err)
self.sendUpdate()
self.opts.showUnapprovedTx(txMeta)
// listen for tx completion (success, fail)
self.txController.once(`${txMeta.id}:finished`, (completedTx) => {
switch (completedTx.status) {
case 'submitted':
return cb(null, completedTx.hash)
case 'rejected':
return cb(new Error('MetaMask Tx Signature: User denied transaction signature.'))
default:
return cb(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(completedTx.txParams)}`))
}
})
})
}
newUnsignedMessage (msgParams, cb) { newUnsignedMessage (msgParams, cb) {
const msgId = this.messageManager.addUnapprovedMessage(msgParams) const msgId = this.messageManager.addUnapprovedMessage(msgParams)
this.sendUpdate() this.sendUpdate()
@ -646,6 +647,4 @@ module.exports = class MetamaskController extends EventEmitter {
return Promise.resolve(rpcTarget) return Promise.resolve(rpcTarget)
}) })
} }
}
}

View File

@ -5,3 +5,6 @@ dependencies:
pre: pre:
- "npm i -g testem" - "npm i -g testem"
- "npm i -g mocha" - "npm i -g mocha"
test:
override:
- "npm run ci"

View File

@ -172,7 +172,6 @@ gulp.task('default', ['lint'], function () {
const jsFiles = [ const jsFiles = [
'inpage', 'inpage',
'contentscript', 'contentscript',
'blacklister',
'background', 'background',
'popup', 'popup',
] ]

View File

@ -7,12 +7,14 @@
"start": "npm run dev", "start": "npm run dev",
"dev": "gulp dev --debug", "dev": "gulp dev --debug",
"disc": "gulp disc --debug", "disc": "gulp disc --debug",
"clear": "rm -rf node_modules/eth-contract-metadata && rm -rf node_modules/etheraddresslookup", "clear": "rm -rf node_modules/eth-contract-metadata && rm -rf node_modules/eth-phishing-detect",
"dist": "npm run clear && npm install && gulp dist", "dist": "npm run clear && npm install && gulp dist",
"test": "npm run lint && npm run test-unit && npm run test-integration", "test": "npm run lint && npm run test-unit && npm run test-integration",
"test-unit": "METAMASK_ENV=test mocha --require test/helper.js --recursive \"test/unit/**/*.js\"", "test-unit": "METAMASK_ENV=test mocha --require test/helper.js --recursive \"test/unit/**/*.js\"",
"single-test": "METAMASK_ENV=test mocha --require test/helper.js", "single-test": "METAMASK_ENV=test mocha --require test/helper.js",
"test-integration": "npm run buildMock && npm run buildCiUnits && testem ci -P 2", "test-integration": "npm run buildMock && npm run buildCiUnits && testem ci -P 2",
"test-coverage": "nyc npm run test-unit && nyc report --reporter=text-lcov | coveralls",
"ci": "npm run lint && npm run test-coverage && npm run test-integration",
"lint": "gulp lint", "lint": "gulp lint",
"buildCiUnits": "node test/integration/index.js", "buildCiUnits": "node test/integration/index.js",
"watch": "mocha watch --recursive \"test/unit/**/*.js\"", "watch": "mocha watch --recursive \"test/unit/**/*.js\"",
@ -66,19 +68,21 @@
"eth-bin-to-ops": "^1.0.1", "eth-bin-to-ops": "^1.0.1",
"eth-contract-metadata": "^1.1.4", "eth-contract-metadata": "^1.1.4",
"eth-hd-keyring": "^1.1.1", "eth-hd-keyring": "^1.1.1",
"eth-phishing-detect": "^1.0.2",
"eth-query": "^2.1.2", "eth-query": "^2.1.2",
"eth-sig-util": "^1.1.1", "eth-sig-util": "^1.2.2",
"eth-simple-keyring": "^1.1.1", "eth-simple-keyring": "^1.1.1",
"eth-token-tracker": "^1.1.2", "eth-token-tracker": "^1.1.2",
"etheraddresslookup": "github:409H/EtherAddressLookup",
"ethereumjs-tx": "^1.3.0", "ethereumjs-tx": "^1.3.0",
"ethereumjs-util": "ethereumjs/ethereumjs-util#ac5d0908536b447083ea422b435da27f26615de9", "ethereumjs-util": "ethereumjs/ethereumjs-util#ac5d0908536b447083ea422b435da27f26615de9",
"ethereumjs-wallet": "^0.6.0", "ethereumjs-wallet": "^0.6.0",
"ethjs-ens": "^2.0.0", "ethjs-ens": "^2.0.0",
"ethjs-query": "^0.2.6",
"express": "^4.14.0", "express": "^4.14.0",
"extension-link-enabler": "^1.0.0", "extension-link-enabler": "^1.0.0",
"extensionizer": "^1.0.0", "extensionizer": "^1.0.0",
"gulp-eslint": "^4.0.0", "gulp-eslint": "^4.0.0",
"fast-levenshtein": "^2.0.6",
"hat": "0.0.3", "hat": "0.0.3",
"idb-global": "^2.1.0", "idb-global": "^2.1.0",
"identicon.js": "^2.3.1", "identicon.js": "^2.3.1",
@ -122,12 +126,11 @@
"semaphore": "^1.0.5", "semaphore": "^1.0.5",
"sw-stream": "^2.0.0", "sw-stream": "^2.0.0",
"textarea-caret": "^3.0.1", "textarea-caret": "^3.0.1",
"three.js": "^0.77.1",
"through2": "^2.0.1",
"valid-url": "^1.0.9", "valid-url": "^1.0.9",
"vreme": "^3.0.2", "vreme": "^3.0.2",
"web3": "0.20.1", "web3": "0.20.1",
"web3-provider-engine": "^13.2.8", "through2": "^2.0.3",
"web3-provider-engine": "^13.2.9",
"web3-stream-provider": "^3.0.1", "web3-stream-provider": "^3.0.1",
"xtend": "^4.0.1" "xtend": "^4.0.1"
}, },
@ -144,6 +147,7 @@
"brfs": "^1.4.3", "brfs": "^1.4.3",
"browserify": "^14.4.0", "browserify": "^14.4.0",
"chai": "^4.1.0", "chai": "^4.1.0",
"coveralls": "^2.13.1",
"deep-freeze-strict": "^1.1.1", "deep-freeze-strict": "^1.1.1",
"del": "^3.0.0", "del": "^3.0.0",
"envify": "^4.0.0", "envify": "^4.0.0",
@ -170,6 +174,7 @@
"mocha-jsdom": "^1.1.0", "mocha-jsdom": "^1.1.0",
"mocha-sinon": "^2.0.0", "mocha-sinon": "^2.0.0",
"nock": "^9.0.14", "nock": "^9.0.14",
"nyc": "^11.0.3",
"open": "0.0.5", "open": "0.0.5",
"prompt": "^1.0.0", "prompt": "^1.0.0",
"qs": "^6.2.0", "qs": "^6.2.0",

View File

@ -0,0 +1,41 @@
const assert = require('assert')
const BlacklistController = require('../../app/scripts/controllers/blacklist')
describe('blacklist controller', function () {
let blacklistController
before(() => {
blacklistController = new BlacklistController()
})
describe('checkForPhishing', function () {
it('should not flag whitelisted values', function () {
const result = blacklistController.checkForPhishing('www.metamask.io')
assert.equal(result, false)
})
it('should flag explicit values', function () {
const result = blacklistController.checkForPhishing('metamask.com')
assert.equal(result, true)
})
it('should flag levenshtein values', function () {
const result = blacklistController.checkForPhishing('metmask.io')
assert.equal(result, true)
})
it('should not flag not-even-close values', function () {
const result = blacklistController.checkForPhishing('example.com')
assert.equal(result, false)
})
it('should not flag the ropsten faucet domains', function () {
const result = blacklistController.checkForPhishing('faucet.metamask.io')
assert.equal(result, false)
})
it('should not flag the mascara domain', function () {
const result = blacklistController.checkForPhishing('zero.metamask.io')
assert.equal(result, false)
})
it('should not flag the mascara-faucet domain', function () {
const result = blacklistController.checkForPhishing('zero-faucet.metamask.io')
assert.equal(result, false)
})
})
})

View File

@ -3,6 +3,9 @@ const NetworkController = require('../../app/scripts/controllers/network')
describe('# Network Controller', function () { describe('# Network Controller', function () {
let networkController let networkController
const networkControllerProviderInit = {
getAccounts: () => {},
}
beforeEach(function () { beforeEach(function () {
networkController = new NetworkController({ networkController = new NetworkController({
@ -10,26 +13,13 @@ describe('# Network Controller', function () {
type: 'rinkeby', type: 'rinkeby',
}, },
}) })
// stub out provider
networkController._provider = new Proxy({}, {
get: (obj, name) => {
return () => {}
},
})
networkController.providerInit = {
getAccounts: () => {},
}
networkController.ethQuery = new Proxy({}, { networkController.initializeProvider(networkControllerProviderInit, dummyProviderConstructor)
get: (obj, name) => {
return () => {}
},
})
}) })
describe('network', function () { describe('network', function () {
describe('#provider', function () { describe('#provider', function () {
it('provider should be updatable without reassignment', function () { it('provider should be updatable without reassignment', function () {
networkController.initializeProvider(networkController.providerInit) networkController.initializeProvider(networkControllerProviderInit, dummyProviderConstructor)
const provider = networkController.provider const provider = networkController.provider
networkController._provider = {test: true} networkController._provider = {test: true}
assert.ok(provider.test) assert.ok(provider.test)
@ -75,3 +65,19 @@ describe('# Network Controller', function () {
}) })
}) })
}) })
function dummyProviderConstructor() {
return {
// provider
sendAsync: noop,
// block tracker
start: noop,
stop: noop,
on: noop,
addListener: noop,
once: noop,
removeAllListeners: noop,
}
}
function noop() {}

View File

@ -18,11 +18,13 @@ describe('Nonce Tracker', function () {
getPendingTransactions = () => pendingTxs getPendingTransactions = () => pendingTxs
provider = { sendAsync: (_, cb) => { cb(undefined, {result: '0x0'}) } } provider = {
nonceTracker = new NonceTracker({ sendAsync: (_, cb) => { cb(undefined, {result: '0x0'}) },
blockTracker: { _blockTracker: {
getCurrentBlock: () => '0x11b568', getCurrentBlock: () => '0x11b568',
}, },
}
nonceTracker = new NonceTracker({
provider, provider,
getPendingTransactions, getPendingTransactions,
}) })

View File

@ -1,11 +1,11 @@
const assert = require('assert') const assert = require('assert')
const ethUtil = require('ethereumjs-util') const ethUtil = require('ethereumjs-util')
const EthTx = require('ethereumjs-tx') const EthTx = require('ethereumjs-tx')
const EthQuery = require('eth-query')
const ObservableStore = require('obs-store') const ObservableStore = require('obs-store')
const clone = require('clone') const clone = require('clone')
const sinon = require('sinon') const sinon = require('sinon')
const TransactionController = require('../../app/scripts/controllers/transactions') const TransactionController = require('../../app/scripts/controllers/transactions')
const TxProvideUtils = require('../../app/scripts/lib/tx-utils')
const noop = () => true const noop = () => true
const currentNetworkId = 42 const currentNetworkId = 42
const otherNetworkId = 36 const otherNetworkId = 36
@ -20,7 +20,6 @@ describe('Transaction Controller', function () {
txHistoryLimit: 10, txHistoryLimit: 10,
blockTracker: { getCurrentBlock: noop, on: noop, once: noop }, blockTracker: { getCurrentBlock: noop, on: noop, once: noop },
provider: { sendAsync: noop }, provider: { sendAsync: noop },
ethQuery: new EthQuery({ sendAsync: noop }),
ethStore: { getState: noop }, ethStore: { getState: noop },
signTransaction: (ethTx) => new Promise((resolve) => { signTransaction: (ethTx) => new Promise((resolve) => {
ethTx.sign(privKey) ethTx.sign(privKey)
@ -28,24 +27,147 @@ describe('Transaction Controller', function () {
}), }),
}) })
txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop }) txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop })
txController.query = new Proxy({}, {
get: (queryStubResult, key) => {
if (key === 'stubResult') {
return function (method, ...args) {
queryStubResult[method] = args
}
} else {
const returnValues = queryStubResult[key]
return () => Promise.resolve(...returnValues)
}
},
})
txController.txProviderUtils = new TxProvideUtils(txController.query)
})
describe('#newUnapprovedTransaction', function () {
let stub, txMeta, txParams
beforeEach(function () {
txParams = {
'from':'0xc684832530fcbddae4b4230a47e991ddcec2831d',
'to':'0xc684832530fcbddae4b4230a47e991ddcec2831d',
},
txMeta = {
status: 'unapproved',
id: 1,
metamaskNetworkId: currentNetworkId,
txParams,
}
txController._saveTxList([txMeta])
stub = sinon.stub(txController, 'addUnapprovedTransaction').returns(Promise.resolve(txMeta))
})
afterEach(function () {
stub.restore()
})
it('should emit newUnaprovedTx event and pass txMeta as the first argument', function (done) {
txController.once('newUnaprovedTx', (txMetaFromEmit) => {
assert(txMetaFromEmit, 'txMeta is falsey')
assert.equal(txMetaFromEmit.id, 1, 'the right txMeta was passed')
done()
})
txController.newUnapprovedTransaction(txParams)
.catch(done)
})
it('should resolve when finished and status is submitted and resolve with the hash', function (done) {
txController.once('newUnaprovedTx', (txMetaFromEmit) => {
setTimeout(() => {
console.log('HELLLO')
txController.setTxHash(txMetaFromEmit.id, '0x0')
txController.setTxStatusSubmitted(txMetaFromEmit.id)
}, 10)
})
txController.newUnapprovedTransaction(txParams)
.then((hash) => {
assert(hash, 'newUnapprovedTransaction needs to return the hash')
done()
})
.catch(done)
})
it('should reject when finished and status is rejected', function (done) {
txController.once('newUnaprovedTx', (txMetaFromEmit) => {
setTimeout(() => {
console.log('HELLLO')
txController.setTxStatusRejected(txMetaFromEmit.id)
}, 10)
})
txController.newUnapprovedTransaction(txParams)
.catch((err) => {
if (err.message === 'MetaMask Tx Signature: User denied transaction signature.') done()
else done(err)
})
})
})
describe('#addUnapprovedTransaction', function () {
it('should add an unapproved transaction and return a valid txMeta', function (done) {
const addTxDefaultsStub = sinon.stub(txController, 'addTxDefaults').callsFake(() => Promise.resolve())
txController.addUnapprovedTransaction({})
.then((txMeta) => {
assert(('id' in txMeta), 'should have a id')
assert(('time' in txMeta), 'should have a time stamp')
assert(('metamaskNetworkId' in txMeta), 'should have a metamaskNetworkId')
assert(('txParams' in txMeta), 'should have a txParams')
assert(('history' in txMeta), 'should have a history')
const memTxMeta = txController.getTx(txMeta.id)
assert.deepEqual(txMeta, memTxMeta, `txMeta should be stored in txController after adding it\n expected: ${txMeta} \n got: ${memTxMeta}`)
addTxDefaultsStub.restore()
done()
}).catch(done)
})
})
describe('#addTxDefaults', function () {
it('should add the tx defaults if their are none', function (done) {
let txMeta = {
'txParams': {
'from':'0xc684832530fcbddae4b4230a47e991ddcec2831d',
'to':'0xc684832530fcbddae4b4230a47e991ddcec2831d',
},
}
txController.query.stubResult('gasPrice', '0x4a817c800')
txController.query.stubResult('getBlockByNumber', { gasLimit: '0x47b784' })
txController.query.stubResult('estimateGas', '0x5209')
txController.addTxDefaults(txMeta)
.then((txMetaWithDefaults) => {
assert(txMetaWithDefaults.txParams.value, '0x0','should have added 0x0 as the value')
assert(txMetaWithDefaults.txParams.gasPrice, 'should have added the gas price')
assert(txMetaWithDefaults.txParams.gas, 'should have added the gas field')
done()
})
.catch(done)
})
}) })
describe('#validateTxParams', function () { describe('#validateTxParams', function () {
it('returns null for positive values', function () { it('does not throw for positive values', function (done) {
var sample = { var sample = {
value: '0x01', value: '0x01',
} }
txController.txProviderUtils.validateTxParams(sample, (err) => { txController.txProviderUtils.validateTxParams(sample).then(() => {
assert.equal(err, null, 'no error') done()
}) }).catch(done)
}) })
it('returns error for negative values', function () { it('returns error for negative values', function (done) {
var sample = { var sample = {
value: '-0x01', value: '-0x01',
} }
txController.txProviderUtils.validateTxParams(sample, (err) => { txController.txProviderUtils.validateTxParams(sample)
.then(() => done('expected to thrown on negativity values but didn\'t'))
.catch((err) => {
assert.ok(err, 'error') assert.ok(err, 'error')
done()
}) })
}) })
}) })
@ -56,9 +178,6 @@ describe('Transaction Controller', function () {
assert.ok(Array.isArray(result)) assert.ok(Array.isArray(result))
assert.equal(result.length, 0) assert.equal(result.length, 0)
}) })
it('should also return transactions from local storage if any', function () {
})
}) })
describe('#addTx', function () { describe('#addTx', function () {
@ -276,16 +395,15 @@ describe('Transaction Controller', function () {
txController.addTx(txMeta) txController.addTx(txMeta)
const estimateStub = sinon.stub(txController.txProviderUtils.query, 'estimateGas') txController.query.stubResult('estimateGas', wrongValue)
.callsArgWithAsync(1, null, wrongValue) txController.query.stubResult('gasPrice', wrongValue)
const priceStub = sinon.stub(txController.txProviderUtils.query, 'gasPrice') const signStub = sinon.stub(txController, 'signTransaction').callsFake(() => Promise.resolve())
.callsArgWithAsync(0, null, wrongValue)
const pubStub = sinon.stub(txController, 'publishTransaction').callsFake(() => {
const signStub = sinon.stub(txController, 'signTransaction', () => Promise.resolve()) txController.setTxHash('1', originalValue)
txController.setTxStatusSubmitted('1')
const pubStub = sinon.stub(txController.txProviderUtils, 'publishTransaction', () => Promise.resolve(originalValue)) })
txController.approveTransaction(txMeta.id).then(() => { txController.approveTransaction(txMeta.id).then(() => {
const result = txController.getTx(txMeta.id) const result = txController.getTx(txMeta.id)
@ -294,9 +412,6 @@ describe('Transaction Controller', function () {
assert.equal(params.gas, originalValue, 'gas unmodified') assert.equal(params.gas, originalValue, 'gas unmodified')
assert.equal(params.gasPrice, originalValue, 'gas price unmodified') assert.equal(params.gasPrice, originalValue, 'gas price unmodified')
assert.equal(result.hash, originalValue, `hash was set \n got: ${result.hash} \n expected: ${originalValue}`) assert.equal(result.hash, originalValue, `hash was set \n got: ${result.hash} \n expected: ${originalValue}`)
estimateStub.restore()
priceStub.restore()
signStub.restore() signStub.restore()
pubStub.restore() pubStub.restore()
done() done()
@ -343,14 +458,17 @@ describe('Transaction Controller', function () {
// Adding the fake tx: // Adding the fake tx:
txController.addTx(clone(txMeta)) txController.addTx(clone(txMeta))
txController._resubmitTx(txMeta, function (err) { txController._resubmitTx(txMeta)
assert.ifError(err, 'should not throw an error') .then(() => {
const updatedMeta = txController.getTx(txMeta.id) const updatedMeta = txController.getTx(txMeta.id)
assert.notEqual(updatedMeta.status, txMeta.status, 'status changed.') assert.notEqual(updatedMeta.status, txMeta.status, 'status changed.')
assert.equal(updatedMeta.status, 'failed', 'tx set to failed.') assert.equal(updatedMeta.status, 'failed', 'tx set to failed.')
done() done()
}) })
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
}) })
}) })
}) })

View File

@ -15,7 +15,7 @@ const addressSummary = util.addressSummary
const nameForAddress = require('../../lib/contract-namer') const nameForAddress = require('../../lib/contract-namer')
const BNInput = require('./bn-as-decimal-input') const BNInput = require('./bn-as-decimal-input')
const MIN_GAS_PRICE_GWEI_BN = new BN(2) const MIN_GAS_PRICE_GWEI_BN = new BN(1)
const GWEI_FACTOR = new BN(1e9) const GWEI_FACTOR = new BN(1e9)
const MIN_GAS_PRICE_BN = MIN_GAS_PRICE_GWEI_BN.mul(GWEI_FACTOR) const MIN_GAS_PRICE_BN = MIN_GAS_PRICE_GWEI_BN.mul(GWEI_FACTOR)
const MIN_GAS_LIMIT_BN = new BN(21000) const MIN_GAS_LIMIT_BN = new BN(21000)

View File

@ -43,7 +43,6 @@ function rootReducer (state, action) {
window.logState = function () { window.logState = function () {
var stateString = JSON.stringify(window.METAMASK_CACHED_LOG_STATE, removeSeedWords, 2) var stateString = JSON.stringify(window.METAMASK_CACHED_LOG_STATE, removeSeedWords, 2)
console.log(stateString)
return stateString return stateString
} }