Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

upgrade ethereumjs util #10886

Merged
merged 1 commit into from
Apr 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from 'assert';
import ethUtil from 'ethereumjs-util';
import { stripHexPrefix } from 'ethereumjs-util';
import accountImporter from '.';

describe('Account Import Strategies', function () {
Expand All @@ -13,7 +13,7 @@ describe('Account Import Strategies', function () {
const importPrivKey = await accountImporter.importAccount('Private Key', [
privkey,
]);
assert.equal(importPrivKey, ethUtil.stripHexPrefix(privkey));
assert.equal(importPrivKey, stripHexPrefix(privkey));
});

it('throws an error for empty string private key', async function () {
Expand Down
15 changes: 10 additions & 5 deletions app/scripts/account-import-strategies/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import log from 'loglevel';
import Wallet from 'ethereumjs-wallet';
import importers from 'ethereumjs-wallet/thirdparty';
import ethUtil from 'ethereumjs-util';
import {
toBuffer,
isValidPrivate,
bufferToHex,
stripHexPrefix,
} from 'ethereumjs-util';
import { addHexPrefix } from '../lib/util';

const accountImporter = {
Expand All @@ -22,13 +27,13 @@ const accountImporter = {
}

const prefixed = addHexPrefix(privateKey);
const buffer = ethUtil.toBuffer(prefixed);
const buffer = toBuffer(prefixed);

if (!ethUtil.isValidPrivate(buffer)) {
if (!isValidPrivate(buffer)) {
throw new Error('Cannot import invalid private key.');
}

const stripped = ethUtil.stripHexPrefix(prefixed);
const stripped = stripHexPrefix(prefixed);
return stripped;
},
'JSON File': (input, password) => {
Expand All @@ -47,7 +52,7 @@ const accountImporter = {

function walletToPrivateKey(wallet) {
const privateKeyBuffer = wallet.getPrivateKey();
return ethUtil.bufferToHex(privateKeyBuffer);
return bufferToHex(privateKeyBuffer);
}

export default accountImporter;
6 changes: 3 additions & 3 deletions app/scripts/controllers/ens/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import punycode from 'punycode/punycode';
import ethUtil from 'ethereumjs-util';
import { toChecksumAddress } from 'ethereumjs-util';
import { ObservableStore } from '@metamask/obs-store';
import log from 'loglevel';
import { CHAIN_ID_TO_NETWORK_ID_MAP } from '../../../../shared/constants/network';
Expand Down Expand Up @@ -43,7 +43,7 @@ export default class EnsController {
}

reverseResolveAddress(address) {
return this._reverseResolveAddress(ethUtil.toChecksumAddress(address));
return this._reverseResolveAddress(toChecksumAddress(address));
}

async _reverseResolveAddress(address) {
Expand Down Expand Up @@ -79,7 +79,7 @@ export default class EnsController {
return undefined;
}

if (ethUtil.toChecksumAddress(registeredAddress) !== address) {
if (toChecksumAddress(registeredAddress) !== address) {
return undefined;
}

Expand Down
2 changes: 1 addition & 1 deletion app/scripts/controllers/ens/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ describe('EnsController', function () {
const ens = new EnsController({
ens: {
reverse: sinon.stub().withArgs(address).returns('peaksignal.eth'),
lookup: sinon.stub().withArgs('peaksignal.eth').returns('0xfoo'),
lookup: sinon.stub().withArgs('peaksignal.eth').returns('0x00'),
},
onNetworkDidChange,
getCurrentChainId,
Expand Down
10 changes: 6 additions & 4 deletions app/scripts/controllers/metametrics.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { merge, omit } from 'lodash';
import { ObservableStore } from '@metamask/obs-store';
import { bufferToHex, sha3 } from 'ethereumjs-util';
import { bufferToHex, keccak } from 'ethereumjs-util';
import { ENVIRONMENT_TYPE_BACKGROUND } from '../../../shared/constants/app';
import {
METAMETRICS_ANONYMOUS_ID,
Expand Down Expand Up @@ -110,9 +110,11 @@ export default class MetaMetricsController {

generateMetaMetricsId() {
return bufferToHex(
sha3(
String(Date.now()) +
String(Math.round(Math.random() * Number.MAX_SAFE_INTEGER)),
keccak(
Buffer.from(
String(Date.now()) +
String(Math.round(Math.random() * Number.MAX_SAFE_INTEGER)),
),
),
);
}
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/controllers/token-rates.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ObservableStore } from '@metamask/obs-store';
import log from 'loglevel';
import { normalize as normalizeAddress } from 'eth-sig-util';
import ethUtil from 'ethereumjs-util';
import { toChecksumAddress } from 'ethereumjs-util';
import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout';

const fetchWithTimeout = getFetchWithTimeout(30000);
Expand Down Expand Up @@ -45,7 +45,7 @@ export default class TokenRatesController {
this._tokens.forEach((token) => {
const price =
prices[token.address.toLowerCase()] ||
prices[ethUtil.toChecksumAddress(token.address)];
prices[toChecksumAddress(token.address)];
contractExchangeRates[normalizeAddress(token.address)] = price
? price[nativeCurrency]
: 0;
Expand Down
12 changes: 6 additions & 6 deletions app/scripts/controllers/transactions/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EventEmitter from 'safe-event-emitter';
import { ObservableStore } from '@metamask/obs-store';
import ethUtil from 'ethereumjs-util';
import { bufferToHex, keccak, toBuffer } from 'ethereumjs-util';
import Transaction from 'ethereumjs-tx';
import EthQuery from 'ethjs-query';
import { ethErrors } from 'eth-rpc-errors';
Expand Down Expand Up @@ -569,9 +569,9 @@ export default class TransactionController extends EventEmitter {

// add r,s,v values for provider request purposes see createMetamaskMiddleware
// and JSON rpc standard for further explanation
txMeta.r = ethUtil.bufferToHex(ethTx.r);
txMeta.s = ethUtil.bufferToHex(ethTx.s);
txMeta.v = ethUtil.bufferToHex(ethTx.v);
txMeta.r = bufferToHex(ethTx.r);
txMeta.s = bufferToHex(ethTx.s);
txMeta.v = bufferToHex(ethTx.v);

this.txStateManager.updateTransaction(
txMeta,
Expand All @@ -580,7 +580,7 @@ export default class TransactionController extends EventEmitter {

// set state to signed
this.txStateManager.setTxStatusSigned(txMeta.id);
const rawTx = ethUtil.bufferToHex(ethTx.serialize());
const rawTx = bufferToHex(ethTx.serialize());
return rawTx;
}

Expand All @@ -606,7 +606,7 @@ export default class TransactionController extends EventEmitter {
txHash = await this.query.sendRawTransaction(rawTx);
} catch (error) {
if (error.message.toLowerCase().includes('known transaction')) {
txHash = ethUtil.sha3(addHexPrefix(rawTx)).toString('hex');
txHash = keccak(toBuffer(addHexPrefix(rawTx), 'hex')).toString('hex');
txHash = addHexPrefix(txHash);
} else {
throw error;
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/controllers/transactions/index.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { strict as assert } from 'assert';
import EventEmitter from 'events';
import ethUtil from 'ethereumjs-util';
import { toBuffer } from 'ethereumjs-util';
import EthTx from 'ethereumjs-tx';
import { ObservableStore } from '@metamask/obs-store';
import sinon from 'sinon';
Expand Down Expand Up @@ -518,7 +518,7 @@ describe('Transaction Controller', function () {
noop,
);
const rawTx = await txController.signTransaction('1');
const ethTx = new EthTx(ethUtil.toBuffer(rawTx));
const ethTx = new EthTx(toBuffer(rawTx));
assert.equal(ethTx.getChainId(), 42);
});
});
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/controllers/transactions/tx-gas-utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EthQuery from 'ethjs-query';
import log from 'loglevel';
import ethUtil from 'ethereumjs-util';
import { addHexPrefix } from 'ethereumjs-util';
import { cloneDeep } from 'lodash';
import { hexToBn, BnMultiplyByFraction, bnToHex } from '../../lib/util';

Expand Down Expand Up @@ -103,7 +103,7 @@ export default class TxGasUtil {

// add additional gas buffer to our estimation for safety
const gasLimit = this.addGasBuffer(
ethUtil.addHexPrefix(estimatedGasHex),
addHexPrefix(estimatedGasHex),
blockGasLimit,
multiplier,
);
Expand Down
6 changes: 3 additions & 3 deletions app/scripts/lib/decrypt-message-manager.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EventEmitter from 'events';
import { ObservableStore } from '@metamask/obs-store';
import ethUtil from 'ethereumjs-util';
import { bufferToHex, stripHexPrefix } from 'ethereumjs-util';
import { ethErrors } from 'eth-rpc-errors';
import log from 'loglevel';
import { MESSAGE_TYPE } from '../../../shared/constants/app';
Expand Down Expand Up @@ -337,14 +337,14 @@ export default class DecryptMessageManager extends EventEmitter {
*/
normalizeMsgData(data) {
try {
const stripped = ethUtil.stripHexPrefix(data);
const stripped = stripHexPrefix(data);
if (stripped.match(hexRe)) {
return addHexPrefix(stripped);
}
} catch (e) {
log.debug(`Message was not hex encoded, interpreting as utf8.`);
}

return ethUtil.bufferToHex(Buffer.from(data, 'utf8'));
return bufferToHex(Buffer.from(data, 'utf8'));
}
}
4 changes: 2 additions & 2 deletions app/scripts/lib/message-manager.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EventEmitter from 'events';
import { ObservableStore } from '@metamask/obs-store';
import ethUtil from 'ethereumjs-util';
import { bufferToHex } from 'ethereumjs-util';
import { ethErrors } from 'eth-rpc-errors';
import { MESSAGE_TYPE } from '../../../shared/constants/app';
import { METAMASK_CONTROLLER_EVENTS } from '../metamask-controller';
Expand Down Expand Up @@ -298,5 +298,5 @@ function normalizeMsgData(data) {
return data;
}
// data is unicode, convert to hex
return ethUtil.bufferToHex(Buffer.from(data, 'utf8'));
return bufferToHex(Buffer.from(data, 'utf8'));
}
6 changes: 3 additions & 3 deletions app/scripts/lib/personal-message-manager.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import EventEmitter from 'events';
import { ObservableStore } from '@metamask/obs-store';
import ethUtil from 'ethereumjs-util';
import { bufferToHex, stripHexPrefix } from 'ethereumjs-util';
import { ethErrors } from 'eth-rpc-errors';
import log from 'loglevel';
import { MESSAGE_TYPE } from '../../../shared/constants/app';
Expand Down Expand Up @@ -322,14 +322,14 @@ export default class PersonalMessageManager extends EventEmitter {
*/
normalizeMsgData(data) {
try {
const stripped = ethUtil.stripHexPrefix(data);
const stripped = stripHexPrefix(data);
if (stripped.match(hexRe)) {
return addHexPrefix(stripped);
}
} catch (e) {
log.debug(`Message was not hex encoded, interpreting as utf8.`);
}

return ethUtil.bufferToHex(Buffer.from(data, 'utf8'));
return bufferToHex(Buffer.from(data, 'utf8'));
}
}
4 changes: 2 additions & 2 deletions app/scripts/lib/util.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'assert';
import extension from 'extensionizer';
import ethUtil from 'ethereumjs-util';
import { stripHexPrefix } from 'ethereumjs-util';
import BN from 'bn.js';
import { memoize } from 'lodash';

Expand Down Expand Up @@ -111,7 +111,7 @@ function sufficientBalance(txParams, hexBalance) {
*
*/
function hexToBn(inputHex) {
return new BN(ethUtil.stripHexPrefix(inputHex), 16);
return new BN(stripHexPrefix(inputHex), 16);
}

/**
Expand Down
18 changes: 8 additions & 10 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import createSubscriptionManager from 'eth-json-rpc-filters/subscriptionManager'
import providerAsMiddleware from 'eth-json-rpc-middleware/providerAsMiddleware';
import KeyringController from 'eth-keyring-controller';
import { Mutex } from 'await-semaphore';
import ethUtil from 'ethereumjs-util';
import { toChecksumAddress, stripHexPrefix } from 'ethereumjs-util';
import log from 'loglevel';
import TrezorKeyring from 'eth-trezor-keyring';
import LedgerBridgeKeyring from '@metamask/eth-ledger-bridge-keyring';
Expand Down Expand Up @@ -1096,16 +1096,14 @@ export default class MetamaskController extends EventEmitter {
// Filter ERC20 tokens
const filteredAccountTokens = {};
Object.keys(accountTokens).forEach((address) => {
const checksummedAddress = ethUtil.toChecksumAddress(address);
const checksummedAddress = toChecksumAddress(address);
filteredAccountTokens[checksummedAddress] = {};
Object.keys(accountTokens[address]).forEach((chainId) => {
filteredAccountTokens[checksummedAddress][chainId] =
chainId === MAINNET_CHAIN_ID
? accountTokens[address][chainId].filter(
({ address: tokenAddress }) => {
const checksumAddress = ethUtil.toChecksumAddress(
tokenAddress,
);
const checksumAddress = toChecksumAddress(tokenAddress);
return contractMap[checksumAddress]
? contractMap[checksumAddress].erc20
: true;
Expand Down Expand Up @@ -1142,10 +1140,10 @@ export default class MetamaskController extends EventEmitter {
const accounts = {
hd: hdAccounts
.filter((item, pos) => hdAccounts.indexOf(item) === pos)
.map((address) => ethUtil.toChecksumAddress(address)),
.map((address) => toChecksumAddress(address)),
simpleKeyPair: simpleKeyPairAccounts
.filter((item, pos) => simpleKeyPairAccounts.indexOf(item) === pos)
.map((address) => ethUtil.toChecksumAddress(address)),
.map((address) => toChecksumAddress(address)),
ledger: [],
trezor: [],
};
Expand All @@ -1155,7 +1153,7 @@ export default class MetamaskController extends EventEmitter {
let { transactions } = this.txController.store.getState();
// delete tx for other accounts that we're not importing
transactions = transactions.filter((tx) => {
const checksummedTxFrom = ethUtil.toChecksumAddress(tx.txParams.from);
const checksummedTxFrom = toChecksumAddress(tx.txParams.from);
return accounts.hd.includes(checksummedTxFrom);
});

Expand Down Expand Up @@ -1640,7 +1638,7 @@ export default class MetamaskController extends EventEmitter {
const msgId = msgParams.metamaskId;
const msg = this.decryptMessageManager.getMsg(msgId);
try {
const stripped = ethUtil.stripHexPrefix(msgParams.data);
const stripped = stripHexPrefix(msgParams.data);
const buff = Buffer.from(stripped, 'hex');
msgParams.data = JSON.parse(buff.toString('utf8'));

Expand Down Expand Up @@ -1670,7 +1668,7 @@ export default class MetamaskController extends EventEmitter {
msgParams,
);

const stripped = ethUtil.stripHexPrefix(cleanMsgParams.data);
const stripped = stripHexPrefix(cleanMsgParams.data);
const buff = Buffer.from(stripped, 'hex');
cleanMsgParams.data = JSON.parse(buff.toString('utf8'));

Expand Down
8 changes: 4 additions & 4 deletions app/scripts/metamask-controller.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from 'assert';
import sinon from 'sinon';
import { cloneDeep } from 'lodash';
import nock from 'nock';
import ethUtil from 'ethereumjs-util';
import { pubToAddress, bufferToHex } from 'ethereumjs-util';
import { obj as createThoughStream } from 'through2';
import EthQuery from 'eth-query';
import proxyquire from 'proxyquire';
Expand Down Expand Up @@ -186,9 +186,9 @@ describe('MetaMaskController', function () {
);
const privKeyBuffer = simpleKeyrings[0].wallets[0]._privKey;
const pubKeyBuffer = simpleKeyrings[0].wallets[0]._pubKey;
const addressBuffer = ethUtil.pubToAddress(pubKeyBuffer);
const privKey = ethUtil.bufferToHex(privKeyBuffer);
const pubKey = ethUtil.bufferToHex(addressBuffer);
const addressBuffer = pubToAddress(pubKeyBuffer);
const privKey = bufferToHex(privKeyBuffer);
const pubKey = bufferToHex(addressBuffer);
assert.equal(privKey, addHexPrefix(importPrivkey));
assert.equal(pubKey, '0xe18035bf8712672935fdb4e5e431b1a0183d2dfc');
});
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/migrations/039.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { cloneDeep } from 'lodash';
import ethUtil from 'ethereumjs-util';
import { toChecksumAddress } from 'ethereumjs-util';

const version = 39;

Expand All @@ -12,7 +12,7 @@ function isOldDai(token = {}) {
token &&
typeof token === 'object' &&
token.symbol === DAI_V1_TOKEN_SYMBOL &&
ethUtil.toChecksumAddress(token.address) === DAI_V1_CONTRACT_ADDRESS
toChecksumAddress(token.address) === DAI_V1_CONTRACT_ADDRESS
);
}

Expand Down
Loading