Skip to content
This repository has been archived by the owner on Oct 28, 2022. It is now read-only.

Commit

Permalink
new sign logic (MetaMask#62)
Browse files Browse the repository at this point in the history
* Add: sign logic

* Add: disable eth-contract-registry

* Fix: e2e test
  • Loading branch information
yqrashawn committed Mar 27, 2020
1 parent e447f4f commit 722e2b5
Show file tree
Hide file tree
Showing 15 changed files with 181 additions and 152 deletions.
2 changes: 1 addition & 1 deletion app/scripts/lib/seed-phrase-verifier.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import KeyringController from 'eth-keyring-controller'
import KeyringController from 'cfx-keyring-controller'
import log from 'loglevel'

const seedPhraseVerifier = {
Expand Down
12 changes: 6 additions & 6 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import createOriginMiddleware from './lib/createOriginMiddleware'
import createOnboardingMiddleware from './lib/createOnboardingMiddleware'
import providerAsMiddleware from '@yqrashawn/cfx-json-rpc-middleware/providerAsMiddleware'
import { setupMultiplex } from './lib/stream-utils.js'
import KeyringController from 'eth-keyring-controller'
import KeyringController from 'cfx-keyring-controller'
import EnsController from './controllers/ens'
import NetworkController from './controllers/network'
import PreferencesController from './controllers/preferences'
Expand All @@ -34,7 +34,7 @@ import OnboardingController from './controllers/onboarding'
// import ThreeBoxController from './controllers/threebox'
import RecentBlocksController from './controllers/recent-blocks'
import IncomingTransactionsController from './controllers/incoming-transactions'
import MessageManager from './lib/message-manager'
// import MessageManager from './lib/message-manager'
import DecryptMessageManager from './lib/decrypt-message-manager'
import EncryptionPublicKeyManager from './lib/encryption-public-key-manager'
import PersonalMessageManager from './lib/personal-message-manager'
Expand Down Expand Up @@ -312,8 +312,8 @@ export default class MetamaskController extends EventEmitter {
)

this.networkController.lookupNetwork()
this.messageManager = new MessageManager()
this.personalMessageManager = new PersonalMessageManager()
this.messageManager = this.personalMessageManager
this.decryptMessageManager = new DecryptMessageManager()
this.encryptionPublicKeyManager = new EncryptionPublicKeyManager()
this.typedMessageManager = new TypedMessageManager({
Expand Down Expand Up @@ -398,7 +398,7 @@ export default class MetamaskController extends EventEmitter {
// tx signing
processTransaction: this.newUnapprovedTransaction.bind(this),
// msg signing
processEthSignMessage: this.newUnsignedMessage.bind(this),
processEthSignMessage: this.newUnsignedPersonalMessage.bind(this),
processTypedMessage: this.newUnsignedTypedMessage.bind(this),
processTypedMessageV3: this.newUnsignedTypedMessage.bind(this),
processTypedMessageV4: this.newUnsignedTypedMessage.bind(this),
Expand Down Expand Up @@ -636,8 +636,8 @@ export default class MetamaskController extends EventEmitter {
getNextNonce: nodeify(this.getNextNonce, this),

// messageManager
signMessage: nodeify(this.signMessage, this),
cancelMessage: this.cancelMessage.bind(this),
signMessage: nodeify(this.signPersonalMessage, this),
cancelMessage: this.cancelPersonalMessage.bind(this),

// personalMessageManager
signPersonalMessage: nodeify(this.signPersonalMessage, this),
Expand Down
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"bip39": "^2.2.0",
"bn.js": "^4.11.7",
"c3": "^0.7.10",
"cfx-keyring-controller": "^5.6.1",
"classnames": "^2.2.6",
"content-hash": "^2.5.0",
"copy-to-clipboard": "^3.0.8",
Expand All @@ -105,9 +106,7 @@
"eth-json-rpc-errors": "^2.0.2",
"eth-json-rpc-filters": "^4.1.1",
"eth-json-rpc-infura": "^4.0.2",
"eth-keyring-controller": "^5.5.0",
"eth-ledger-bridge-keyring": "^0.2.0",
"eth-method-registry": "^1.2.0",
"eth-phishing-detect": "^1.1.4",
"eth-query": "^2.1.2",
"eth-sig-util": "^2.3.0",
Expand All @@ -127,7 +126,7 @@
"extensionizer": "^1.0.1",
"fast-json-patch": "^2.0.4",
"fuse.js": "^3.2.0",
"gaba": "^1.9.3",
"gaba": "^1.10.0",
"human-standard-token-abi": "^2.0.0",
"jazzicon": "^2.0.0",
"js-conflux-sdk": "^0.8.0-alpha",
Expand Down Expand Up @@ -198,7 +197,7 @@
"@storybook/addon-knobs": "^5.2.8",
"@storybook/react": "^5.2.8",
"@storybook/storybook-deployer": "^2.8.1",
"@yqrashawn/conflux-local-network-lite": "^2.0.0-beta",
"@yqrashawn/conflux-local-network-lite": "^2.0.1",
"@yqrashawn/conflux-portal-onboarding": "^0.2.0-alpha",
"addons-linter": "1.14.0",
"babel-eslint": "^10.0.2",
Expand Down
9 changes: 6 additions & 3 deletions test/e2e/contract-test/contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ const initialize = () => {
}

personalSignData.addEventListener('click', () => {
const typedData = {
const personalSignData = {
types: {
EIP712Domain: [
{ name: 'name', type: 'string' },
Expand Down Expand Up @@ -548,7 +548,7 @@ const initialize = () => {
confluxJS.provider.sendAsync(
{
method: 'personal_sign',
params: [JSON.stringify(typedData), conflux.selectedAddress],
params: [JSON.stringify(personalSignData), conflux.selectedAddress],
from: conflux.selectedAddress,
},
(err, result) => {
Expand Down Expand Up @@ -669,13 +669,16 @@ const initialize = () => {

confluxJS.provider.sendAsync(
{
method: 'eth_signTypedData_v3',
method: 'cfx_signTypedData_v3',
params: [conflux.selectedAddress, JSON.stringify(typedData)],
from: conflux.selectedAddress,
},
(err, result) => {
if (err) {
console.log(err)
if (!chainId) {
console.log('chainId is not defined')
}
} else {
signTypedDataResults.innerHTML = JSON.stringify(result)
sendSignedTypedData.disabled = false
Expand Down
18 changes: 9 additions & 9 deletions test/e2e/contract-test/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,28 @@ <h2>Status</h2>
Accounts: <span id="accounts"></span>
</div>
</section>
<section>
<h2>
<a target="_blank" href="https://conflux-chain.github.io/metamask-docs/API_Reference/Signing_Data/Eth_Sign">CFX Sign Data<a> (same as Metamask's personal_sign)
</h2>
<button id="cfxSignData" disabled>CFX Sign</button>
<div>CFX Sign Data Result: <span id="cfxSignDataResult"></span></div>
</section>
<section>
<h2>Sign Typed Data V3</h2>
<button id="signTypedData" disabled>Sign</button>
<button id="signTypedData" disabled>Typed Sign</button>
<div>Sign Typed Data Result: <span id="signTypedDataResult"></span></div>
<br>
<button id="sendSignedTypedData" disabled>Sned</button>
<div>Send Signed Typed Data Result: <span id="sendSignedTypedDataResult"></span></div>
</section>
<section>
<section style="display: none;">
<h2>
<a target="_blank" href="https://conflux-chain.github.io/metamask-docs/API_Reference/Signing_Data/Personal_Sign">Personal Sign Data<a> (Prefered)
</h2>
<button id="personalSignData" disabled>Personal Sign</button>
<div>Personal Sign Data Result: <span id="personalSignDataResult"></span></div>
</section>
<section>
<h2>
<a target="_blank" href="https://conflux-chain.github.io/metamask-docs/API_Reference/Signing_Data/Eth_Sign">CFX Sign Data<a> (Deprecated)
</h2>
<button id="cfxSignData" disabled>CFX Sign</button>
<div>CFX Sign Data Result: <span id="cfxSignDataResult"></span></div>
</section>
</main>
</body>
</html>
2 changes: 1 addition & 1 deletion test/e2e/signature-request.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ describe('MetaMask', function () {

it('creates a sign typed data signature request', async function () {
await driver.clickElement(
By.xpath(`//button[contains(text(), 'Sign')]`),
By.xpath(`//button[contains(text(), 'Typed Sign')]`),
10000
)
await driver.delay(largeDelayMs)
Expand Down
4 changes: 2 additions & 2 deletions test/unit/app/controllers/metamask-controller-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,7 @@ describe('MetaMaskController', function () {
})
})

describe('#newUnsignedMessage', function () {
describe.skip('#newUnsignedMessage', function () {
let msgParams, metamaskMsgs, messages, msgId

const address = '0xc42edfcc21ed14dda456aa0756c153f7985d8813'
Expand Down Expand Up @@ -905,7 +905,7 @@ describe('MetaMaskController', function () {
assert.equal(metamaskPersonalMsgs[msgId].status, 'signed')
assert.equal(
metamaskPersonalMsgs[msgId].rawSig,
'0x6a1b65e2b8ed53cf398a769fad24738f9fbe29841fe6854e226953542c4b6a173473cb152b6b1ae5f06d601d45dd699a129b0a8ca84e78b423031db5baa734741b'
'0x42aa75cb4f4991a9e4b84645896b6a2a402f38de45a3f522dd7f1f0aa99205237bf8f9693a435438ad9d37e536552ecdc407ba41f54f57bc2e182c3bd5470eb801'
)
})
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
KOVAN_CODE,
GOERLI_CODE,
} from '../../../../../app/scripts/controllers/network/enums'
import KeyringController from 'eth-keyring-controller'
import KeyringController from 'cfx-keyring-controller'

describe('Recipient Blacklist Checker', function () {
describe('#checkAccount', function () {
Expand Down
2 changes: 1 addition & 1 deletion test/unit/app/seed-phrase-verifier-test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'assert'
import { cloneDeep } from 'lodash'
import KeyringController from 'eth-keyring-controller'
import KeyringController from 'cfx-keyring-controller'
import firstTimeState from '../../../app/scripts/first-time-state'
import seedPhraseVerifier from '../../../app/scripts/lib/seed-phrase-verifier'
import mockEncryptor from '../../lib/mock-encryptor'
Expand Down
8 changes: 4 additions & 4 deletions test/unit/ui/app/actions.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import configureStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import EthQuery from '../../../../app/scripts/eth-query'
import Eth from 'ethjs'
import KeyringController from 'eth-keyring-controller'
import KeyringController from 'cfx-keyring-controller'

import { createTestProviderTools } from '../../../stub/provider'
import enLocale from '../../../../app/_locales/en/messages.json'
Expand Down Expand Up @@ -644,12 +644,12 @@ describe('Actions', function () {
signMessageSpy.restore()
})

it('calls signMsg in background', function () {
it('calls signPerMsg in background', function () {
const store = mockStore({
metamask: {},
})

signMessageSpy = sinon.spy(background, 'signMessage')
signMessageSpy = sinon.spy(background, 'signPersonalMessage')
store.dispatch(actions.signMsg(msgParams))
assert(signMessageSpy.calledOnce)
})
Expand All @@ -665,7 +665,7 @@ describe('Actions', function () {
{ type: 'DISPLAY_WARNING', value: 'error' },
]

signMessageSpy = sinon.stub(background, 'signMessage')
signMessageSpy = sinon.stub(background, 'signPersonalMessage')
signMessageSpy.callsFake((_, callback) => {
callback(new Error('error'))
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ function mergeProps (stateProps, dispatchProps, ownProps) {
if (type === 'personal_sign') {
cancel = cancelPersonalMessage
sign = signPersonalMessage
} else if (type === 'eth_signTypedData') {
} else if (type === 'cfx_signTypedData' || type === 'eth_signTypedData') {
cancel = cancelTypedMessage
sign = signTypedMessage
} else if (type === 'eth_sign') {
} else if (type === 'cfx_sign' || type === 'eth_sign') {
cancel = cancelMessage
sign = signMessage
}
Expand Down
99 changes: 50 additions & 49 deletions ui/app/helpers/utils/transactions.util.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import ethUtil from 'ethereumjs-util'
import MethodRegistry from 'eth-method-registry'
// import MethodRegistry from 'eth-method-registry'
import abi from 'human-standard-token-abi'
import abiDecoder from 'abi-decoder'
import {
TRANSACTION_TYPE_CANCEL,
TRANSACTION_STATUS_CONFIRMED,
} from '../../../../app/scripts/controllers/transactions/enums'
import prefixForNetwork from '../../../lib/etherscan-prefix-for-network'
import fetchWithCache from './fetch-with-cache'
// import fetchWithCache from './fetch-with-cache'

import {
TOKEN_METHOD_TRANSFER,
Expand All @@ -26,7 +26,7 @@ import {
DEPOSIT_TRANSACTION_KEY,
} from '../constants/transactions'

import log from 'loglevel'
// import log from 'loglevel'
import { addCurrencies } from './conversion-util'

abiDecoder.addABI(abi)
Expand All @@ -35,58 +35,59 @@ export function getTokenData (data = '') {
return abiDecoder.decodeMethod(data)
}

async function getMethodFrom4Byte (fourBytePrefix) {
const fourByteResponse = await fetchWithCache(
`https://www.4byte.directory/api/v1/signatures/?hex_signature=${fourBytePrefix}`,
{
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
mode: 'cors',
}
)

if (fourByteResponse.count === 1) {
return fourByteResponse.results[0].text_signature
} else {
return null
}
}

const registry = new MethodRegistry({ provider: global.ethereumProvider })
// async function getMethodFrom4Byte (fourBytePrefix) {
// const fourByteResponse = await fetchWithCache(
// `https://www.4byte.directory/api/v1/signatures/?hex_signature=${fourBytePrefix}`,
// {
// referrerPolicy: 'no-referrer-when-downgrade',
// body: null,
// method: 'GET',
// mode: 'cors',
// }
// )

// if (fourByteResponse.count === 1) {
// return fourByteResponse.results[0].text_signature
// } else {
// return null
// }
// }

// const registry = new MethodRegistry({ provider: global.ethereumProvider })

/**
* Attempts to return the method data from the MethodRegistry library, the message registry library and the token abi, in that order of preference
* @param {string} fourBytePrefix - The prefix from the method code associated with the data
* @returns {Object}
*/
export async function getMethodDataAsync (fourBytePrefix) {
try {
const fourByteSig = getMethodFrom4Byte(fourBytePrefix).catch((e) => {
log.error(e)
return null
})

let sig = await registry.lookup(fourBytePrefix)

if (!sig) {
sig = await fourByteSig
}

if (!sig) {
return {}
}

const parsedResult = registry.parse(sig)

return {
name: parsedResult.name,
params: parsedResult.args,
}
} catch (error) {
log.error(error)
return {}
}
export async function getMethodDataAsync (/* fourBytePrefix */) {
return {}
// try {
// const fourByteSig = getMethodFrom4Byte(fourBytePrefix).catch((e) => {
// log.error(e)
// return null
// })

// let sig = await registry.lookup(fourBytePrefix)

// if (!sig) {
// sig = await fourByteSig
// }

// if (!sig) {
// return {}
// }

// const parsedResult = registry.parse(sig)

// return {
// name: parsedResult.name,
// params: parsedResult.args,
// }
// } catch (error) {
// log.error(error)
// return {}
// }
}

export function isConfirmDeployContract (txData = {}) {
Expand Down
2 changes: 1 addition & 1 deletion ui/app/pages/confirm-transaction/conf-tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ class ConfirmTxScreen extends Component {
signatureSelect (type, version) {
// Temporarily direct only v3 and v4 requests to new code.
if (
type === 'eth_signTypedData' &&
(type === 'cfx_signTypedData' || type === 'eth_signTypedData') &&
(version === 'V3' || version === 'V4')
) {
return SignatureRequest
Expand Down
Loading

0 comments on commit 722e2b5

Please sign in to comment.