nifty-wallet/app/scripts/background.js

260 lines
6.9 KiB
JavaScript
Raw Normal View History

2016-01-15 02:03:42 -08:00
const Dnode = require('dnode')
2016-04-14 21:22:04 -07:00
const ObjectMultiplex = require('./lib/obj-multiplex')
2016-02-10 17:44:46 -08:00
const eos = require('end-of-stream')
2016-03-10 13:04:45 -08:00
const combineStreams = require('pumpify')
2016-02-10 17:44:46 -08:00
const extend = require('xtend')
const EthStore = require('eth-store')
2016-01-15 02:03:42 -08:00
const PortStream = require('./lib/port-stream.js')
2016-04-26 11:36:05 -07:00
const MetaMaskProvider = require('web3-provider-engine/zero.js')
2016-02-10 17:44:46 -08:00
const IdentityStore = require('./lib/idStore')
const createTxNotification = require('./lib/notifications.js').createTxNotification
const createMsgNotification = require('./lib/notifications.js').createMsgNotification
const configManager = require('./lib/config-manager-singleton')
const setupMultiplex = require('./lib/stream-utils.js').setupMultiplex
const HostStore = require('./lib/remote-store.js').HostStore
const Web3 = require('web3')
2015-12-18 22:05:16 -08:00
2016-02-10 17:44:46 -08:00
//
// connect to other contexts
//
2016-01-16 16:22:54 -08:00
chrome.runtime.onConnect.addListener(connectRemote)
2015-12-18 22:05:16 -08:00
function connectRemote(remotePort){
2016-01-15 02:03:42 -08:00
var isMetaMaskInternalProcess = (remotePort.name === 'popup')
2016-03-09 18:33:30 -08:00
var portStream = new PortStream(remotePort)
2016-01-15 02:03:42 -08:00
if (isMetaMaskInternalProcess) {
// communication with popup
setupTrustedCommunication(portStream)
2016-01-15 02:03:42 -08:00
} else {
// communication with page
setupUntrustedCommunication(portStream)
2016-01-15 02:03:42 -08:00
}
}
function setupUntrustedCommunication(connectionStream){
// setup multiplexing
var mx = setupMultiplex(connectionStream)
// connect features
setupProviderConnection(mx.createStream('provider'))
setupPublicConfig(mx.createStream('publicConfig'))
}
function setupTrustedCommunication(connectionStream){
// setup multiplexing
var mx = setupMultiplex(connectionStream)
// connect features
setupControllerConnection(mx.createStream('controller'))
setupProviderConnection(mx.createStream('provider'))
2016-02-10 17:44:46 -08:00
}
2016-01-17 01:27:25 -08:00
2016-02-10 17:44:46 -08:00
//
// state and network
//
2016-01-17 01:27:25 -08:00
2016-03-31 16:32:35 -07:00
var providerConfig = configManager.getProvider()
2016-02-10 17:44:46 -08:00
var idStore = new IdentityStore()
2016-03-31 16:32:35 -07:00
var providerOpts = {
rpcUrl: configManager.getCurrentRpcAddress(),
// account mgmt
2016-02-10 17:44:46 -08:00
getAccounts: function(cb){
var selectedAddress = idStore.getSelectedAddress()
var result = selectedAddress ? [selectedAddress] : []
cb(null, result)
},
// tx signing
2016-03-10 15:39:31 -08:00
approveTransaction: addUnconfirmedTx,
2016-02-20 12:13:18 -08:00
signTransaction: idStore.signTransaction.bind(idStore),
// msg signing
approveMessage: addUnconfirmedMsg,
signMessage: idStore.signMessage.bind(idStore),
2016-03-31 16:32:35 -07:00
}
var provider = MetaMaskProvider(providerOpts)
var web3 = new Web3(provider)
idStore.web3 = web3
idStore.getNetwork(3)
// log new blocks
2016-03-31 16:32:35 -07:00
provider.on('block', function(block){
console.log('BLOCK CHANGED:', '#'+block.number.toString('hex'), '0x'+block.hash.toString('hex'))
})
2016-03-31 16:32:35 -07:00
var ethStore = new EthStore(provider)
2016-02-10 17:44:46 -08:00
idStore.setStore(ethStore)
2016-01-15 02:03:42 -08:00
2016-02-10 17:44:46 -08:00
function getState(){
var state = extend(
ethStore.getState(),
idStore.getState(),
configManager.getConfig()
)
2016-02-10 17:44:46 -08:00
return state
}
//
// public store
//
// get init state
var initPublicState = extend(
idStoreToPublic(idStore.getState()),
configToPublic(configManager.getConfig())
)
var publicConfigStore = new HostStore(initPublicState)
// subscribe to changes
configManager.subscribe(function(state){
storeSetFromObj(publicConfigStore, configToPublic(state))
})
idStore.on('update', function(state){
storeSetFromObj(publicConfigStore, idStoreToPublic(state))
})
// idStore substate
function idStoreToPublic(state){
return {
selectedAddress: state.selectedAddress,
}
}
// config substate
function configToPublic(state){
return {
provider: state.provider,
}
}
// dump obj into store
function storeSetFromObj(store, obj){
Object.keys(obj).forEach(function(key){
store.set(key, obj[key])
})
}
2016-01-15 02:03:42 -08:00
// handle rpc requests
2016-03-09 18:33:30 -08:00
function onRpcRequest(remoteStream, payload){
2016-01-15 02:03:42 -08:00
// console.log('MetaMaskPlugin - incoming payload:', payload)
2016-03-31 16:32:35 -07:00
provider.sendAsync(payload, function onPayloadHandled(err, response){
2016-03-08 13:27:38 -08:00
// provider engine errors are included in response objects
2016-04-28 11:48:39 -07:00
if (!payload.isMetamaskInternal) {
console.log('MetaMaskPlugin - RPC complete:', payload, '->', response)
if (response.error) console.error('Error in RPC response:\n'+response.error.message)
}
2016-02-10 11:46:13 -08:00
try {
2016-03-10 13:04:45 -08:00
remoteStream.write(response)
2016-03-09 18:33:30 -08:00
} catch (err) {
console.error(err)
2016-02-10 11:46:13 -08:00
}
2015-12-18 22:05:16 -08:00
})
}
2015-08-01 16:33:31 -07:00
2016-02-10 17:44:46 -08:00
//
// remote features
2016-02-10 17:44:46 -08:00
//
function setupPublicConfig(stream){
var storeStream = publicConfigStore.createStream()
stream.pipe(storeStream).pipe(stream)
}
function setupProviderConnection(stream){
stream.on('data', onRpcRequest.bind(null, stream))
2016-03-09 18:33:30 -08:00
}
function setupControllerConnection(stream){
var dnode = Dnode({
2016-02-10 17:44:46 -08:00
getState: function(cb){ cb(null, getState()) },
setRpcTarget: setRpcTarget,
2016-03-31 16:32:35 -07:00
useEtherscanProvider: useEtherscanProvider,
2016-02-10 17:44:46 -08:00
// forward directly to idStore
2016-02-17 00:55:57 -08:00
createNewVault: idStore.createNewVault.bind(idStore),
2016-03-15 13:39:12 -07:00
recoverFromSeed: idStore.recoverFromSeed.bind(idStore),
2016-02-10 17:44:46 -08:00
submitPassword: idStore.submitPassword.bind(idStore),
setSelectedAddress: idStore.setSelectedAddress.bind(idStore),
2016-03-02 22:58:23 -08:00
approveTransaction: idStore.approveTransaction.bind(idStore),
2016-02-12 12:55:20 -08:00
cancelTransaction: idStore.cancelTransaction.bind(idStore),
2016-02-10 17:44:46 -08:00
setLocked: idStore.setLocked.bind(idStore),
clearSeedWordCache: idStore.clearSeedWordCache.bind(idStore),
2016-04-06 12:01:10 -07:00
exportAccount: idStore.exportAccount.bind(idStore),
2016-02-10 17:44:46 -08:00
})
stream.pipe(dnode).pipe(stream)
dnode.on('remote', function(remote){
2016-02-10 17:44:46 -08:00
// push updates to popup
ethStore.on('update', sendUpdate)
idStore.on('update', sendUpdate)
// teardown on disconnect
2016-03-09 18:33:30 -08:00
eos(stream, function unsubscribe(){
2016-02-10 17:44:46 -08:00
ethStore.removeListener('update', sendUpdate)
})
function sendUpdate(){
var state = getState()
remote.sendUpdate(state)
}
})
}
//
// plugin badge text
//
idStore.on('update', updateBadge)
2015-12-18 22:05:16 -08:00
2016-01-18 17:05:46 -08:00
function updateBadge(state){
var label = ''
var unconfTxs = configManager.unconfirmedTxs()
var count = Object.keys(unconfTxs).length
2016-01-18 17:05:46 -08:00
if (count) {
label = String(count)
}
chrome.browserAction.setBadgeText({ text: label })
chrome.browserAction.setBadgeBackgroundColor({ color: '#506F8B' })
2016-01-18 17:05:46 -08:00
}
2015-12-18 22:05:16 -08:00
2016-03-10 15:39:31 -08:00
//
// Add unconfirmed Tx + Msg
2016-03-10 15:39:31 -08:00
//
function addUnconfirmedTx(txParams, cb){
var txId = idStore.addUnconfirmedTransaction(txParams, cb)
createTxNotification({
title: 'New Unsigned Transaction',
txParams: txParams,
confirm: idStore.approveTransaction.bind(idStore, txId, noop),
cancel: idStore.cancelTransaction.bind(idStore, txId),
2016-03-10 15:39:31 -08:00
})
}
function addUnconfirmedMsg(msgParams, cb){
var msgId = idStore.addUnconfirmedMessage(msgParams, cb)
createMsgNotification({
title: 'New Unsigned Message',
msgParams: msgParams,
confirm: idStore.approveMessage.bind(idStore, msgId, noop),
cancel: idStore.cancelMessage.bind(idStore, msgId),
})
}
//
// config
//
// called from popup
function setRpcTarget(rpcTarget){
configManager.setRpcTarget(rpcTarget)
chrome.runtime.reload()
idStore.getNetwork(3) // 3 retry attempts
}
2016-03-31 16:32:35 -07:00
function useEtherscanProvider() {
configManager.useEtherscanProvider()
chrome.runtime.reload()
}
2016-03-09 18:33:30 -08:00
// util
function noop(){}