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

Added tx and msg signing to keychain & controller

This commit is contained in:
Dan Finlay 2016-10-20 19:01:04 -07:00
parent 957b7a72b5
commit 9560ae93ee
4 changed files with 134 additions and 39 deletions

View File

@ -21,7 +21,7 @@ const controller = new MetamaskController({
setData, setData,
loadData, loadData,
}) })
const idStore = controller.idStore const keyringController = controller.keyringController
function triggerUi () { function triggerUi () {
if (!popupIsOpen) notification.show() if (!popupIsOpen) notification.show()
@ -82,7 +82,7 @@ function setupControllerConnection (stream) {
// push updates to popup // push updates to popup
controller.ethStore.on('update', controller.sendUpdate.bind(controller)) controller.ethStore.on('update', controller.sendUpdate.bind(controller))
controller.listeners.push(remote) controller.listeners.push(remote)
idStore.on('update', controller.sendUpdate.bind(controller)) keyringController.on('update', controller.sendUpdate.bind(controller))
// teardown on disconnect // teardown on disconnect
eos(stream, () => { eos(stream, () => {
@ -96,9 +96,9 @@ function setupControllerConnection (stream) {
// plugin badge text // plugin badge text
// //
idStore.on('update', updateBadge) keyringController.on('update', updateBadge)
function updateBadge (state) { function updateBadge () {
var label = '' var label = ''
var unconfTxs = controller.configManager.unconfirmedTxs() var unconfTxs = controller.configManager.unconfirmedTxs()
var unconfTxLen = Object.keys(unconfTxs).length var unconfTxLen = Object.keys(unconfTxs).length

View File

@ -2,6 +2,8 @@ const EventEmitter = require('events').EventEmitter
const encryptor = require('./lib/encryptor') const encryptor = require('./lib/encryptor')
const messageManager = require('./lib/message-manager') const messageManager = require('./lib/message-manager')
const ethUtil = require('ethereumjs-util') const ethUtil = require('ethereumjs-util')
const BN = ethUtil.BN
const Transaction = require('ethereumjs-tx')
// Keyrings: // Keyrings:
const SimpleKeyring = require('./keyrings/simple') const SimpleKeyring = require('./keyrings/simple')
@ -198,8 +200,60 @@ module.exports = class KeyringController extends EventEmitter {
} }
} }
signTransaction(txParams, cb) {
try {
const address = ethUtil.addHexPrefix(txParams.from.toLowercase())
const keyring = this.getKeyringForAccount(address)
// Handle gas pricing
var gasMultiplier = this.configManager.getGasMultiplier() || 1
var gasPrice = new BN(ethUtil.stripHexPrefix(txParams.gasPrice), 16)
gasPrice = gasPrice.mul(new BN(gasMultiplier * 100, 10)).div(new BN(100, 10))
txParams.gasPrice = ethUtil.intToHex(gasPrice.toNumber())
// normalize values
txParams.to = ethUtil.addHexPrefix(txParams.to.toLowerCase())
txParams.from = ethUtil.addHexPrefix(txParams.from.toLowerCase())
txParams.value = ethUtil.addHexPrefix(txParams.value)
txParams.data = ethUtil.addHexPrefix(txParams.data)
txParams.gasLimit = ethUtil.addHexPrefix(txParams.gasLimit || txParams.gas)
txParams.nonce = ethUtil.addHexPrefix(txParams.nonce)
let tx = new Transaction(txParams)
tx = keyring.signTransaction(address, tx)
// Add the tx hash to the persisted meta-tx object
var txHash = ethUtil.bufferToHex(tx.hash())
var metaTx = this.configManager.getTx(txParams.metamaskId)
metaTx.hash = txHash
this.configManager.updateTx(metaTx)
// return raw serialized tx
var rawTx = ethUtil.bufferToHex(tx.serialize())
cb(null, rawTx)
} catch (e) {
cb(e)
}
}
signMessage(msgParams, cb) { signMessage(msgParams, cb) {
cb() try {
const keyring = this.getKeyringForAccount(msgParams.from)
const address = ethUtil.addHexPrefix(msgParams.from.toLowercase())
const rawSig = keyring.signMessage(address, msgParams.data)
cb(null, rawSig)
} catch (e) {
cb(e)
}
}
getKeyringForAccount(address) {
const hexed = ethUtil.addHexPrefix(address.toLowerCase())
return this.keyrings.find((ring) => {
return ring.getAccounts()
.map(acct => ethUtil.addHexPrefix(acct.toLowerCase()))
.includes(hexed)
})
} }
cancelMessage(msgId, cb) { cancelMessage(msgId, cb) {

View File

@ -1,5 +1,6 @@
const EventEmitter = require('events').EventEmitter const EventEmitter = require('events').EventEmitter
const Wallet = require('ethereumjs-wallet') const Wallet = require('ethereumjs-wallet')
const ethUtil = require('ethereumjs-util')
const type = 'Simple Key Pair' const type = 'Simple Key Pair'
module.exports = class SimpleKeyring extends EventEmitter { module.exports = class SimpleKeyring extends EventEmitter {
@ -40,4 +41,44 @@ module.exports = class SimpleKeyring extends EventEmitter {
return this.wallets.map(w => w.getAddress().toString('hex')) return this.wallets.map(w => w.getAddress().toString('hex'))
} }
// tx is an instance of the ethereumjs-transaction class.
signTransaction(address, tx) {
const wallet = this.getWalletForAccount(address)
var privKey = wallet.getPrivateKey()
tx.sign(privKey)
return tx
}
// For eth_sign, we need to sign transactions:
signMessage(withAccount, data) {
const wallet = this.getWalletForAccount(withAccount)
const message = ethUtil.removeHexPrefix(data)
var privKey = wallet.getPrivateKey()
var msgSig = ethUtil.ecsign(new Buffer(message, 'hex'), privKey)
var rawMsgSig = ethUtil.bufferToHex(concatSig(msgSig.v, msgSig.r, msgSig.s))
return rawMsgSig
}
getWalletForAccount(account) {
return this.wallets.find(w => w.getAddress().toString('hex') === account)
}
}
function concatSig (v, r, s) {
const rSig = ethUtil.fromSigned(r)
const sSig = ethUtil.fromSigned(s)
const vSig = ethUtil.bufferToInt(v)
const rStr = padWithZeroes(ethUtil.toUnsigned(rSig).toString('hex'), 64)
const sStr = padWithZeroes(ethUtil.toUnsigned(sSig).toString('hex'), 64)
const vStr = ethUtil.stripHexPrefix(ethUtil.intToHex(vSig))
return ethUtil.addHexPrefix(rStr.concat(sStr, vStr)).toString('hex')
}
function padWithZeroes (number, length) {
var myString = '' + number
while (myString.length < length) {
myString = '0' + myString
}
return myString
} }

View File

@ -1,7 +1,7 @@
const extend = require('xtend') const extend = require('xtend')
const EthStore = require('eth-store') const EthStore = require('eth-store')
const MetaMaskProvider = require('web3-provider-engine/zero.js') const MetaMaskProvider = require('web3-provider-engine/zero.js')
const IdentityStore = require('./keyring-controller') const KeyringController = require('./keyring-controller')
const messageManager = require('./lib/message-manager') const messageManager = require('./lib/message-manager')
const HostStore = require('./lib/remote-store.js').HostStore const HostStore = require('./lib/remote-store.js').HostStore
const Web3 = require('web3') const Web3 = require('web3')
@ -15,12 +15,12 @@ module.exports = class MetamaskController {
this.opts = opts this.opts = opts
this.listeners = [] this.listeners = []
this.configManager = new ConfigManager(opts) this.configManager = new ConfigManager(opts)
this.idStore = new IdentityStore({ this.keyringController = new KeyringController({
configManager: this.configManager, configManager: this.configManager,
}) })
this.provider = this.initializeProvider(opts) this.provider = this.initializeProvider(opts)
this.ethStore = new EthStore(this.provider) this.ethStore = new EthStore(this.provider)
this.idStore.setStore(this.ethStore) this.keyringController.setStore(this.ethStore)
this.getNetwork() this.getNetwork()
this.messageManager = messageManager this.messageManager = messageManager
this.publicConfigStore = this.initPublicConfigStore() this.publicConfigStore = this.initPublicConfigStore()
@ -38,13 +38,13 @@ module.exports = class MetamaskController {
return extend( return extend(
this.state, this.state,
this.ethStore.getState(), this.ethStore.getState(),
this.idStore.getState(), this.keyringController.getState(),
this.configManager.getConfig() this.configManager.getConfig()
) )
} }
getApi () { getApi () {
const idStore = this.idStore const keyringController = this.keyringController
return { return {
getState: (cb) => { cb(null, this.getState()) }, getState: (cb) => { cb(null, this.getState()) },
@ -59,19 +59,19 @@ module.exports = class MetamaskController {
checkTOSChange: this.checkTOSChange.bind(this), checkTOSChange: this.checkTOSChange.bind(this),
setGasMultiplier: this.setGasMultiplier.bind(this), setGasMultiplier: this.setGasMultiplier.bind(this),
// forward directly to idStore // forward directly to keyringController
createNewVault: idStore.createNewVault.bind(idStore), createNewVault: keyringController.createNewVault.bind(keyringController),
addNewKeyring: idStore.addNewKeyring.bind(idStore), addNewKeyring: keyringController.addNewKeyring.bind(keyringController),
submitPassword: idStore.submitPassword.bind(idStore), submitPassword: keyringController.submitPassword.bind(keyringController),
setSelectedAddress: idStore.setSelectedAddress.bind(idStore), setSelectedAddress: keyringController.setSelectedAddress.bind(keyringController),
approveTransaction: idStore.approveTransaction.bind(idStore), approveTransaction: keyringController.approveTransaction.bind(keyringController),
cancelTransaction: idStore.cancelTransaction.bind(idStore), cancelTransaction: keyringController.cancelTransaction.bind(keyringController),
signMessage: idStore.signMessage.bind(idStore), signMessage: keyringController.signMessage.bind(keyringController),
cancelMessage: idStore.cancelMessage.bind(idStore), cancelMessage: keyringController.cancelMessage.bind(keyringController),
setLocked: idStore.setLocked.bind(idStore), setLocked: keyringController.setLocked.bind(keyringController),
exportAccount: idStore.exportAccount.bind(idStore), exportAccount: keyringController.exportAccount.bind(keyringController),
saveAccountLabel: idStore.saveAccountLabel.bind(idStore), saveAccountLabel: keyringController.saveAccountLabel.bind(keyringController),
tryPassword: idStore.tryPassword.bind(idStore), tryPassword: keyringController.tryPassword.bind(keyringController),
// coinbase // coinbase
buyEth: this.buyEth.bind(this), buyEth: this.buyEth.bind(this),
// shapeshift // shapeshift
@ -133,27 +133,27 @@ module.exports = class MetamaskController {
} }
initializeProvider (opts) { initializeProvider (opts) {
const idStore = this.idStore const keyringController = this.keyringController
var providerOpts = { var providerOpts = {
rpcUrl: this.configManager.getCurrentRpcAddress(), rpcUrl: this.configManager.getCurrentRpcAddress(),
// account mgmt // account mgmt
getAccounts: (cb) => { getAccounts: (cb) => {
var selectedAddress = idStore.getSelectedAddress() var selectedAddress = this.configManager.getSelectedAccount()
var result = selectedAddress ? [selectedAddress] : [] var result = selectedAddress ? [selectedAddress] : []
cb(null, result) cb(null, result)
}, },
// tx signing // tx signing
approveTransaction: this.newUnsignedTransaction.bind(this), approveTransaction: this.newUnsignedTransaction.bind(this),
signTransaction: (...args) => { signTransaction: (...args) => {
idStore.signTransaction(...args) keyringController.signTransaction(...args)
this.sendUpdate() this.sendUpdate()
}, },
// msg signing // msg signing
approveMessage: this.newUnsignedMessage.bind(this), approveMessage: this.newUnsignedMessage.bind(this),
signMessage: (...args) => { signMessage: (...args) => {
idStore.signMessage(...args) keyringController.signMessage(...args)
this.sendUpdate() this.sendUpdate()
}, },
} }
@ -161,7 +161,7 @@ module.exports = class MetamaskController {
var provider = MetaMaskProvider(providerOpts) var provider = MetaMaskProvider(providerOpts)
var web3 = new Web3(provider) var web3 = new Web3(provider)
this.web3 = web3 this.web3 = web3
idStore.web3 = web3 keyringController.web3 = web3
provider.on('block', this.processBlock.bind(this)) provider.on('block', this.processBlock.bind(this))
provider.on('error', this.getNetwork.bind(this)) provider.on('error', this.getNetwork.bind(this))
@ -172,7 +172,7 @@ module.exports = class MetamaskController {
initPublicConfigStore () { initPublicConfigStore () {
// get init state // get init state
var initPublicState = extend( var initPublicState = extend(
idStoreToPublic(this.idStore.getState()), keyringControllerToPublic(this.keyringController.getState()),
configToPublic(this.configManager.getConfig()) configToPublic(this.configManager.getConfig())
) )
@ -182,13 +182,13 @@ module.exports = class MetamaskController {
this.configManager.subscribe(function (state) { this.configManager.subscribe(function (state) {
storeSetFromObj(publicConfigStore, configToPublic(state)) storeSetFromObj(publicConfigStore, configToPublic(state))
}) })
this.idStore.on('update', function (state) { this.keyringController.on('update', function (state) {
storeSetFromObj(publicConfigStore, idStoreToPublic(state)) storeSetFromObj(publicConfigStore, keyringControllerToPublic(state))
this.sendUpdate() this.sendUpdate()
}) })
// idStore substate // keyringController substate
function idStoreToPublic (state) { function keyringControllerToPublic (state) {
return { return {
selectedAddress: state.selectedAddress, selectedAddress: state.selectedAddress,
} }
@ -211,12 +211,12 @@ module.exports = class MetamaskController {
} }
newUnsignedTransaction (txParams, onTxDoneCb) { newUnsignedTransaction (txParams, onTxDoneCb) {
const idStore = this.idStore const keyringController = this.keyringController
let err = this.enforceTxValidations(txParams) let err = this.enforceTxValidations(txParams)
if (err) return onTxDoneCb(err) if (err) return onTxDoneCb(err)
idStore.addUnconfirmedTransaction(txParams, onTxDoneCb, (err, txData) => { keyringController.addUnconfirmedTransaction(txParams, onTxDoneCb, (err, txData) => {
if (err) return onTxDoneCb(err) if (err) return onTxDoneCb(err)
this.sendUpdate() this.sendUpdate()
this.opts.showUnconfirmedTx(txParams, txData, onTxDoneCb) this.opts.showUnconfirmedTx(txParams, txData, onTxDoneCb)
@ -231,9 +231,9 @@ module.exports = class MetamaskController {
} }
newUnsignedMessage (msgParams, cb) { newUnsignedMessage (msgParams, cb) {
var state = this.idStore.getState() var state = this.keyringController.getState()
if (!state.isUnlocked) { if (!state.isUnlocked) {
this.idStore.addUnconfirmedMessage(msgParams, cb) this.keyringController.addUnconfirmedMessage(msgParams, cb)
this.opts.unlockAccountMessage() this.opts.unlockAccountMessage()
} else { } else {
this.addUnconfirmedMessage(msgParams, cb) this.addUnconfirmedMessage(msgParams, cb)
@ -242,8 +242,8 @@ module.exports = class MetamaskController {
} }
addUnconfirmedMessage (msgParams, cb) { addUnconfirmedMessage (msgParams, cb) {
const idStore = this.idStore const keyringController = this.keyringController
const msgId = idStore.addUnconfirmedMessage(msgParams, cb) const msgId = keyringController.addUnconfirmedMessage(msgParams, cb)
this.opts.showUnconfirmedMessage(msgParams, msgId) this.opts.showUnconfirmedMessage(msgParams, msgId)
} }