diff --git a/packages/account/package.json b/packages/account/package.json index 230b81b319e..ddf94585c59 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -36,7 +36,7 @@ }, "homepage": "https://github.com/ethereumjs/ethereumjs-account#readme", "dependencies": { - "ethereumjs-util": "^6.0.0", + "ethereumjs-util": "^7.0.2", "rlp": "^2.2.1", "safe-buffer": "^5.1.1" }, @@ -45,7 +45,7 @@ "@ethereumjs/config-prettier": "^1.1.0", "@ethereumjs/config-tsc": "^1.1.0", "@ethereumjs/config-tslint": "^1.1.0", - "@types/bn.js": "^4.11.3", + "@types/bn.js": "^4.11.6", "@types/node": "^11.9.4", "@types/tape": "^4.2.33", "merkle-patricia-tree": "^3.0.0", @@ -56,7 +56,7 @@ "tslint": "^5.12.0", "typedoc": "next", "typedoc-plugin-markdown": "^2.2.17", - "typescript": "^3.2.2", + "typescript": "^3.9.2", "typestrict": "^1.0.2" } } diff --git a/packages/block/package.json b/packages/block/package.json index b863496f5c4..d0e0b1a837b 100644 --- a/packages/block/package.json +++ b/packages/block/package.json @@ -39,10 +39,10 @@ }, "homepage": "https://github.com/ethereumjs/ethereumjs-block#readme", "dependencies": { - "@types/bn.js": "^4.11.5", + "@types/bn.js": "^4.11.6", "ethereumjs-common": "^1.5.0", "ethereumjs-tx": "^2.1.1", - "ethereumjs-util": "^6.1.0", + "ethereumjs-util": "^7.0.2", "merkle-patricia-tree": "^2.1.2" }, "devDependencies": { @@ -67,7 +67,7 @@ "tslint": "^5.15.0", "typedoc": "next", "typedoc-plugin-markdown": "^2.2.17", - "typescript": "^3.4.3", + "typescript": "^3.9.2", "typestrict": "^1.0.2" } } diff --git a/packages/block/src/block.ts b/packages/block/src/block.ts index 93d86bf3946..60b2c5f3390 100644 --- a/packages/block/src/block.ts +++ b/packages/block/src/block.ts @@ -1,12 +1,11 @@ import Common from 'ethereumjs-common' -import * as ethUtil from 'ethereumjs-util' -import { BN, rlp } from 'ethereumjs-util' +import { rlp, keccak256, KECCAK256_RLP, baToJSON } from 'ethereumjs-util' import { Transaction, TransactionOptions } from 'ethereumjs-tx' - import { BlockHeader } from './header' import { Blockchain, BlockData, ChainOptions } from './types' const Trie = require('merkle-patricia-tree') +const { BN } = require('ethereumjs-util') /** * An object that represents the block @@ -148,7 +147,7 @@ export class Block { if (this.transactions.length) { return txT === this.txTrie.root.toString('hex') } else { - return txT === ethUtil.KECCAK256_RLP.toString('hex') + return txT === KECCAK256_RLP.toString('hex') } } @@ -163,7 +162,7 @@ export class Block { validateTransactions(stringError = false) { const errors: string[] = [] - this.transactions.forEach(function(tx, i) { + this.transactions.forEach(function (tx, i) { const error = tx.validate(true) if (error) { errors.push(`${error} at tx ${i}`) @@ -209,7 +208,7 @@ export class Block { validateUnclesHash(): boolean { const raw = rlp.encode(this.uncleHeaders.map(uh => uh.raw)) - return ethUtil.keccak256(raw).toString('hex') === this.header.uncleHash.toString('hex') + return keccak256(raw).toString('hex') === this.header.uncleHash.toString('hex') } /** @@ -248,7 +247,7 @@ export class Block { uncleHeaders: this.uncleHeaders.forEach(uh => uh.toJSON(true)), } } else { - return ethUtil.baToJSON(this.raw) + return baToJSON(this.raw) } } diff --git a/packages/block/src/from-rpc.ts b/packages/block/src/from-rpc.ts index 21079190fd5..978b2e661bf 100644 --- a/packages/block/src/from-rpc.ts +++ b/packages/block/src/from-rpc.ts @@ -1,5 +1,5 @@ import { FakeTransaction, TransactionOptions } from 'ethereumjs-tx' -import * as ethUtil from 'ethereumjs-util' +import { toBuffer, setLengthLeft } from 'ethereumjs-util' import { Block } from './index' import { ChainOptions } from './types' @@ -34,17 +34,17 @@ export default function blockFromRpc( for (const _txParams of blockParams.transactions) { const txParams = normalizeTxParams(_txParams) // override from address - const fromAddress = ethUtil.toBuffer(txParams.from) + const fromAddress = toBuffer(txParams.from) delete txParams.from const tx = new FakeTransaction(txParams, chainOptions as TransactionOptions) tx.from = fromAddress - tx.getSenderAddress = function() { + tx.getSenderAddress = function () { return fromAddress } // override hash - const txHash = ethUtil.toBuffer(txParams.hash) - tx.hash = function() { + const txHash = toBuffer(txParams.hash) + tx.hash = function () { return txHash } @@ -60,7 +60,7 @@ function normalizeTxParams(_txParams: any) { txParams.gasLimit = txParams.gasLimit === undefined ? txParams.gas : txParams.gasLimit txParams.data = txParams.data === undefined ? txParams.input : txParams.data // strict byte length checking - txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null + txParams.to = txParams.to ? setLengthLeft(toBuffer(txParams.to), 20) : null // v as raw signature value {0,1} // v is the recovery bit and can be either {0,1} or {27,28}. diff --git a/packages/block/src/header-from-rpc.ts b/packages/block/src/header-from-rpc.ts index 4756905adda..e93eb422b6b 100644 --- a/packages/block/src/header-from-rpc.ts +++ b/packages/block/src/header-from-rpc.ts @@ -1,5 +1,5 @@ import { BlockHeader } from './header' -import * as ethUtil from 'ethereumjs-util' +import { KECCAK256_NULL, toBuffer } from 'ethereumjs-util' import { ChainOptions } from './types' /** @@ -16,7 +16,7 @@ export default function blockHeaderFromRpc(blockParams: any, chainOptions?: Chai coinbase: blockParams.miner, stateRoot: blockParams.stateRoot, transactionsTrie: blockParams.transactionsRoot, - receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.KECCAK256_NULL, + receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || KECCAK256_NULL, bloom: blockParams.logsBloom, difficulty: blockParams.difficulty, number: blockParams.number, @@ -32,7 +32,7 @@ export default function blockHeaderFromRpc(blockParams: any, chainOptions?: Chai // override hash in case something was missing blockHeader.hash = function() { - return ethUtil.toBuffer(blockParams.hash) + return toBuffer(blockParams.hash) } return blockHeader diff --git a/packages/block/src/header.ts b/packages/block/src/header.ts index 9e727116c83..39bedf292e2 100644 --- a/packages/block/src/header.ts +++ b/packages/block/src/header.ts @@ -1,10 +1,20 @@ import Common from 'ethereumjs-common' -import * as utils from 'ethereumjs-util' -import { BN } from 'ethereumjs-util' +import { + zeros, + KECCAK256_RLP_ARRAY, + KECCAK256_RLP, + toBuffer, + defineProperties, + bufferToInt, + rlphash, +} from 'ethereumjs-util' import { Blockchain, BlockHeaderData, BufferLike, ChainOptions, PrefixedHexString } from './types' import { Buffer } from 'buffer' import { Block } from './block' +const { BN } = require('ethereumjs-util') +import IBN = require('bn.js') + /** * An object that represents the block header */ @@ -55,35 +65,35 @@ export class BlockHeader { { name: 'parentHash', length: 32, - default: utils.zeros(32), + default: zeros(32), }, { name: 'uncleHash', - default: utils.KECCAK256_RLP_ARRAY, + default: KECCAK256_RLP_ARRAY, }, { name: 'coinbase', length: 20, - default: utils.zeros(20), + default: zeros(20), }, { name: 'stateRoot', length: 32, - default: utils.zeros(32), + default: zeros(32), }, { name: 'transactionsTrie', length: 32, - default: utils.KECCAK256_RLP, + default: KECCAK256_RLP, }, { name: 'receiptTrie', length: 32, - default: utils.KECCAK256_RLP, + default: KECCAK256_RLP, }, { name: 'bloom', - default: utils.zeros(256), + default: zeros(256), }, { name: 'difficulty', @@ -92,7 +102,7 @@ export class BlockHeader { { name: 'number', // TODO: params.homeSteadForkNumber.v left for legacy reasons, replace on future release - default: utils.toBuffer(1150000), + default: toBuffer(1150000), }, { name: 'gasLimit', @@ -115,15 +125,15 @@ export class BlockHeader { }, { name: 'mixHash', - default: utils.zeros(32), + default: zeros(32), // length: 32 }, { name: 'nonce', - default: utils.zeros(8), // sha3(42) + default: zeros(8), // sha3(42) }, ] - utils.defineProperties(this, fields, data) + defineProperties(this, fields, data) } /** @@ -131,7 +141,7 @@ export class BlockHeader { * * @param parentBlock - the parent `Block` of this header */ - canonicalDifficulty(parentBlock: Block): BN { + canonicalDifficulty(parentBlock: Block): IBN { const hardfork = this._getHardfork() const blockTs = new BN(this.timestamp) const parentTs = new BN(parentBlock.header.timestamp) @@ -143,11 +153,11 @@ export class BlockHeader { let num = new BN(this.number) // We use a ! here as TS can follow this hardforks-dependent logic, but it always gets assigned - let dif!: BN + let dif!: IBN if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) { // max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100) - const uncleAddend = parentBlock.header.uncleHash.equals(utils.KECCAK256_RLP_ARRAY) ? 1 : 2 + const uncleAddend = parentBlock.header.uncleHash.equals(KECCAK256_RLP_ARRAY) ? 1 : 2 let a = blockTs .sub(parentTs) .idivn(9) @@ -252,7 +262,7 @@ export class BlockHeader { * @param blockchain - the blockchain that this block is validating against * @param height - If this is an uncle header, this is the height of the block that is including it */ - async validate(blockchain: Blockchain, height?: BN): Promise { + async validate(blockchain: Blockchain, height?: IBN): Promise { if (this.isGenesis()) { return } @@ -283,11 +293,11 @@ export class BlockHeader { throw new Error('invalid gas limit') } - if (utils.bufferToInt(this.number) - utils.bufferToInt(parentBlock.header.number) !== 1) { + if (bufferToInt(this.number) - bufferToInt(parentBlock.header.number) !== 1) { throw new Error('invalid height') } - if (utils.bufferToInt(this.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) { + if (bufferToInt(this.timestamp) <= bufferToInt(parentBlock.header.timestamp)) { throw new Error('invalid timestamp') } @@ -301,7 +311,7 @@ export class BlockHeader { * Returns the hash of the block header. */ hash(): Buffer { - return utils.rlphash(this.raw) + return rlphash(this.raw) } /** @@ -347,7 +357,7 @@ export class BlockHeader { return commonHardFork !== null ? commonHardFork - : this._common.activeHardfork(utils.bufferToInt(this.number)) + : this._common.activeHardfork(bufferToInt(this.number)) } private async _getBlockByHash(blockchain: Blockchain, hash: Buffer): Promise { diff --git a/packages/block/test/difficulty.spec.ts b/packages/block/test/difficulty.spec.ts index c9fd649dea2..28207aa5749 100644 --- a/packages/block/test/difficulty.spec.ts +++ b/packages/block/test/difficulty.spec.ts @@ -1,8 +1,9 @@ -import * as utils from 'ethereumjs-util' -import { BN } from 'ethereumjs-util' +import { toBuffer } from 'ethereumjs-util' import { Block } from '../src/block' import tape = require('tape') +const { BN } = require('ethereumjs-util') + function isHexPrefixed(str: string) { return str.toLowerCase().startsWith('0x') } @@ -10,7 +11,7 @@ function isHexPrefixed(str: string) { function normalize(data: any) { Object.keys(data).forEach(function(i) { if (i !== 'homestead' && typeof data[i] === 'string') { - data[i] = isHexPrefixed(data[i]) ? new BN(utils.toBuffer(data[i])) : new BN(data[i]) + data[i] = isHexPrefixed(data[i]) ? new BN(toBuffer(data[i])) : new BN(data[i]) } }) } diff --git a/packages/block/test/header.spec.ts b/packages/block/test/header.spec.ts index ab96da391e0..da0303e3871 100644 --- a/packages/block/test/header.spec.ts +++ b/packages/block/test/header.spec.ts @@ -1,28 +1,27 @@ import tape = require('tape') import Common from 'ethereumjs-common' -import * as utils from 'ethereumjs-util' -import { rlp } from 'ethereumjs-util' +import { rlp, toBuffer, zeros, KECCAK256_RLP_S, KECCAK256_RLP_ARRAY_S } from 'ethereumjs-util' import { BlockHeader } from '../src/header' import { Block } from '../src/block' -tape('[Block]: Header functions', function(t) { - t.test('should create with default constructor', function(st) { +tape('[Block]: Header functions', function (t) { + t.test('should create with default constructor', function (st) { function compareDefaultHeader(st: tape.Test, header: BlockHeader) { - st.deepEqual(header.parentHash, utils.zeros(32)) - st.equal(header.uncleHash.toString('hex'), utils.KECCAK256_RLP_ARRAY_S) - st.deepEqual(header.coinbase, utils.zeros(20)) - st.deepEqual(header.stateRoot, utils.zeros(32)) - st.equal(header.transactionsTrie.toString('hex'), utils.KECCAK256_RLP_S) - st.equal(header.receiptTrie.toString('hex'), utils.KECCAK256_RLP_S) - st.deepEqual(header.bloom, utils.zeros(256)) + st.deepEqual(header.parentHash, zeros(32)) + st.equal(header.uncleHash.toString('hex'), KECCAK256_RLP_ARRAY_S) + st.deepEqual(header.coinbase, zeros(20)) + st.deepEqual(header.stateRoot, zeros(32)) + st.equal(header.transactionsTrie.toString('hex'), KECCAK256_RLP_S) + st.equal(header.receiptTrie.toString('hex'), KECCAK256_RLP_S) + st.deepEqual(header.bloom, zeros(256)) st.deepEqual(header.difficulty, Buffer.from([])) - st.deepEqual(header.number, utils.toBuffer(1150000)) + st.deepEqual(header.number, toBuffer(1150000)) st.deepEqual(header.gasLimit, Buffer.from('ffffffffffffff', 'hex')) st.deepEqual(header.gasUsed, Buffer.from([])) st.deepEqual(header.timestamp, Buffer.from([])) st.deepEqual(header.extraData, Buffer.from([])) - st.deepEqual(header.mixHash, utils.zeros(32)) - st.deepEqual(header.nonce, utils.zeros(8)) + st.deepEqual(header.mixHash, zeros(32)) + st.deepEqual(header.nonce, zeros(8)) } let header = new BlockHeader() @@ -35,7 +34,7 @@ tape('[Block]: Header functions', function(t) { st.end() }) - t.test('should test header initialization', function(st) { + t.test('should test header initialization', function (st) { const header1 = new BlockHeader(undefined, { chain: 'ropsten' }) const common = new Common('ropsten') const header2 = new BlockHeader(undefined, { common: common }) @@ -48,7 +47,7 @@ tape('[Block]: Header functions', function(t) { ) st.throws( - function() { + function () { new BlockHeader(undefined, { chain: 'ropsten', common: common }) }, /not allowed!$/, @@ -57,7 +56,7 @@ tape('[Block]: Header functions', function(t) { st.end() }) - t.test('should test validateGasLimit', function(st) { + t.test('should test validateGasLimit', function (st) { const testData = require('./testdata/bcBlockGasLimitTest.json').tests const bcBlockGasLimigTestData = testData.BlockGasLimit2p63m1 @@ -70,7 +69,7 @@ tape('[Block]: Header functions', function(t) { st.end() }) - t.test('should test isGenesis', function(st) { + t.test('should test isGenesis', function (st) { const header = new BlockHeader() st.equal(header.isGenesis(), false) header.number = Buffer.from([]) @@ -79,7 +78,7 @@ tape('[Block]: Header functions', function(t) { }) const testDataGenesis = require('./testdata/genesishashestest.json').test - t.test('should test genesis hashes (mainnet default)', function(st) { + t.test('should test genesis hashes (mainnet default)', function (st) { const header = new BlockHeader() header.setGenesisParams() st.strictEqual( @@ -90,7 +89,7 @@ tape('[Block]: Header functions', function(t) { st.end() }) - t.test('should test genesis parameters (ropsten)', function(st) { + t.test('should test genesis parameters (ropsten)', function (st) { const genesisHeader = new BlockHeader(undefined, { chain: 'ropsten' }) genesisHeader.setGenesisParams() const ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' diff --git a/packages/blockchain/package.json b/packages/blockchain/package.json index 0bb27b468d9..05a5488bf6a 100644 --- a/packages/blockchain/package.json +++ b/packages/blockchain/package.json @@ -41,7 +41,7 @@ "ethashjs": "~0.0.7", "ethereumjs-block": "~3.0.0", "ethereumjs-common": "^1.5.0", - "ethereumjs-util": "~6.1.0", + "ethereumjs-util": "~7.0.2", "flow-stoplight": "^1.0.0", "level-mem": "^3.0.1", "lru-cache": "^5.1.1", @@ -54,7 +54,7 @@ "@ethereumjs/config-tsc": "^1.1.1", "@ethereumjs/config-tslint": "^1.1.1", "@types/async": "^2.4.1", - "@types/bn.js": "^4.11.4", + "@types/bn.js": "^5.1.2", "@types/lru-cache": "^5.1.0", "@types/node": "^11.11.4", "@types/semaphore": "^1.1.0", @@ -67,7 +67,7 @@ "tslint": "^5.13.1", "typedoc": "next", "typedoc-plugin-markdown": "^2.2.17", - "typescript": "^3.3.3333", + "typescript": "^3.9.2", "typestrict": "^1.0.2" } } diff --git a/packages/common/package.json b/packages/common/package.json index c5750a49809..36b3b62ee34 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -58,7 +58,7 @@ "tslint": "^5.12.0", "typedoc": "next", "typedoc-plugin-markdown": "^2.2.17", - "typescript": "^3.2.2", + "typescript": "^3.9.2", "typestrict": "^1.0.2" }, "maintainers": [ diff --git a/packages/tx/package.json b/packages/tx/package.json index b644fe70d8a..3fcddb90af2 100644 --- a/packages/tx/package.json +++ b/packages/tx/package.json @@ -33,14 +33,14 @@ "license": "MPL-2.0", "dependencies": { "ethereumjs-common": "^1.5.0", - "ethereumjs-util": "^6.0.0" + "ethereumjs-util": "^7.0.2" }, "devDependencies": { "@ethereumjs/config-nyc": "^1.1.1", "@ethereumjs/config-prettier": "^1.1.1", "@ethereumjs/config-tsc": "^1.1.1", "@ethereumjs/config-tslint": "^1.1.1", - "@types/bn.js": "^4.11.5", + "@types/bn.js": "^4.11.6", "@types/minimist": "^1.2.0", "@types/node": "^11.13.4", "@types/tape": "^4.2.33", @@ -62,7 +62,7 @@ "tslint": "^5.15.0", "typedoc": "next", "typedoc-plugin-markdown": "^2.2.17", - "typescript": "^3.4.3", + "typescript": "^3.9.2", "typestrict": "^1.0.2" }, "repository": { diff --git a/packages/tx/src/transaction.ts b/packages/tx/src/transaction.ts index 21ae77fd2ae..b3a72c11f2b 100644 --- a/packages/tx/src/transaction.ts +++ b/packages/tx/src/transaction.ts @@ -8,7 +8,7 @@ import { ecsign, toBuffer, rlp, - stripZeros, + unpadBuffer, } from 'ethereumjs-util' import Common from 'ethereumjs-common' import { Buffer } from 'buffer' @@ -183,9 +183,8 @@ export default class Transaction { items = [ ...this.raw.slice(0, 6), toBuffer(this.getChainId()), - // TODO: stripping zeros should probably be a responsibility of the rlp module - stripZeros(toBuffer(0)), - stripZeros(toBuffer(0)), + unpadBuffer(toBuffer(0)), + unpadBuffer(toBuffer(0)), ] } else { items = this.raw.slice(0, 6) diff --git a/packages/vm/examples/run-blockchain/index.ts b/packages/vm/examples/run-blockchain/index.ts index de08d9712c2..2cffe4a085f 100644 --- a/packages/vm/examples/run-blockchain/index.ts +++ b/packages/vm/examples/run-blockchain/index.ts @@ -3,7 +3,7 @@ import VM from '../../' import Account from 'ethereumjs-account' import { Block, BlockHeader } from 'ethereumjs-block' import Blockchain from 'ethereumjs-blockchain' -import { toBuffer, setLength } from 'ethereumjs-util' +import { toBuffer, setLengthLeft } from 'ethereumjs-util' const testData = require('./test-data') const level = require('level') @@ -66,7 +66,7 @@ async function setupPreConditions(vm: VM, testData: any) { for (const hexStorageKey of Object.keys(acctData.storage)) { const val = toBuffer(acctData.storage[hexStorageKey]) - const storageKey = setLength(toBuffer(hexStorageKey), 32) + const storageKey = setLengthLeft(toBuffer(hexStorageKey), 32) await vm.stateManager.putContractStorage(addressBuf, storageKey, val) } diff --git a/packages/vm/examples/run-solidity-contract/index.ts b/packages/vm/examples/run-solidity-contract/index.ts index 90614aa44f0..460867ecd13 100644 --- a/packages/vm/examples/run-solidity-contract/index.ts +++ b/packages/vm/examples/run-solidity-contract/index.ts @@ -3,7 +3,7 @@ import VM from '../../dist' import * as assert from 'assert' import * as path from 'path' import * as fs from 'fs' -import * as util from 'ethereumjs-util' +import { privateToAddress, bufferToHex } from 'ethereumjs-util' import Account from 'ethereumjs-account' import { Transaction } from 'ethereumjs-tx' const abi = require('ethereumjs-abi') @@ -78,7 +78,7 @@ function getGreeterDeploymentBytecode(solcOutput: any): any { async function getAccountNonce(vm: VM, accountPrivateKey: Buffer) { const account = (await promisify(vm.stateManager.getAccount.bind(vm.stateManager))( - util.privateToAddress(accountPrivateKey), + privateToAddress(accountPrivateKey), )) as Account return account.nonce @@ -162,9 +162,9 @@ async function main() { 'hex', ) - const accountAddress = util.privateToAddress(accountPk) + const accountAddress = privateToAddress(accountPk) - console.log('Account:', util.bufferToHex(accountAddress)) + console.log('Account:', bufferToHex(accountAddress)) const account = new Account({ balance: 1e18 }) @@ -188,7 +188,7 @@ async function main() { const contractAddress = await deployContract(vm, accountPk, bytecode, INITIAL_GREETING) - console.log('Contract address:', util.bufferToHex(contractAddress)) + console.log('Contract address:', bufferToHex(contractAddress)) const greeting = await getGreeting(vm, contractAddress, accountAddress) diff --git a/packages/vm/examples/run-transactions-complete/index.ts b/packages/vm/examples/run-transactions-complete/index.ts index fb643bf960d..227c47db771 100644 --- a/packages/vm/examples/run-transactions-complete/index.ts +++ b/packages/vm/examples/run-transactions-complete/index.ts @@ -1,6 +1,6 @@ import VM from '../..' import Account from 'ethereumjs-account' -import * as utils from 'ethereumjs-util' +import { toBuffer, pubToAddress, bufferToHex } from 'ethereumjs-util' import { Transaction } from 'ethereumjs-tx' async function main() { @@ -9,13 +9,13 @@ async function main() { // import the key pair // used to sign transactions and generate addresses const keyPair = require('./key-pair') - const privateKey = utils.toBuffer(keyPair.secretKey) + const privateKey = toBuffer(keyPair.secretKey) - const publicKeyBuf = utils.toBuffer(keyPair.publicKey) - const address = utils.pubToAddress(publicKeyBuf, true) + const publicKeyBuf = toBuffer(keyPair.publicKey) + const address = pubToAddress(publicKeyBuf, true) console.log('---------------------') - console.log('Sender address: ', utils.bufferToHex(address)) + console.log('Sender address: ', bufferToHex(address)) // create a new account const account = new Account({ diff --git a/packages/vm/lib/evm/opFns.ts b/packages/vm/lib/evm/opFns.ts index f2d966e5b72..85be450d5cb 100644 --- a/packages/vm/lib/evm/opFns.ts +++ b/packages/vm/lib/evm/opFns.ts @@ -1,5 +1,5 @@ import BN = require('bn.js') -import * as utils from 'ethereumjs-util' +import { keccak256, setLengthRight, TWO_POW256, MAX_INTEGER, KECCAK256_NULL } from 'ethereumjs-util' import { ERROR, VmError } from '../exceptions' import { RunState } from './interpreter' @@ -38,12 +38,12 @@ export const handlers: { [k: string]: OpHandler } = { }, ADD: function (runState: RunState) { const [a, b] = runState.stack.popN(2) - const r = a.add(b).mod(utils.TWO_POW256) + const r = a.add(b).mod(TWO_POW256) runState.stack.push(r) }, MUL: function (runState: RunState) { const [a, b] = runState.stack.popN(2) - const r = a.mul(b).mod(utils.TWO_POW256) + const r = a.mul(b).mod(TWO_POW256) runState.stack.push(r) }, SUB: function (runState: RunState) { @@ -137,7 +137,7 @@ export const handlers: { [k: string]: OpHandler } = { runState.stack.push(new BN(0)) return } - const m = BN.red(utils.TWO_POW256) + const m = BN.red(TWO_POW256) const redBase = base.toRed(m) const r = redBase.redPow(exponent) runState.stack.push(r.fromRed()) @@ -229,7 +229,7 @@ export const handlers: { [k: string]: OpHandler } = { return } - const r = b.shln(a.toNumber()).iand(utils.MAX_INTEGER) + const r = b.shln(a.toNumber()).iand(MAX_INTEGER) runState.stack.push(r) }, SHR: function (runState: RunState) { @@ -255,7 +255,7 @@ export const handlers: { [k: string]: OpHandler } = { const isSigned = b.testn(255) if (a.gten(256)) { if (isSigned) { - r = new BN(utils.MAX_INTEGER) + r = new BN(MAX_INTEGER) } else { r = new BN(0) } @@ -266,7 +266,7 @@ export const handlers: { [k: string]: OpHandler } = { const c = b.shrn(a.toNumber()) if (isSigned) { const shiftedOutWidth = 255 - a.toNumber() - const mask = utils.MAX_INTEGER.shrn(shiftedOutWidth).shln(shiftedOutWidth) + const mask = MAX_INTEGER.shrn(shiftedOutWidth).shln(shiftedOutWidth) r = c.ior(mask) } else { r = c @@ -285,7 +285,7 @@ export const handlers: { [k: string]: OpHandler } = { runState.eei.useGas( new BN(runState._common.param('gasPrices', 'sha3Word')).imul(divCeil(length, new BN(32))), ) - const r = new BN(utils.keccak256(data)) + const r = new BN(keccak256(data)) runState.stack.push(r) }, // 0x30 range - closure state @@ -317,7 +317,7 @@ export const handlers: { [k: string]: OpHandler } = { const i = pos.toNumber() let loaded = runState.eei.getCallData().slice(i, i + 32) loaded = loaded.length ? loaded : Buffer.from([0]) - const r = new BN(utils.setLengthRight(loaded, 32)) + const r = new BN(setLengthRight(loaded, 32)) runState.stack.push(r) }, @@ -394,11 +394,11 @@ export const handlers: { [k: string]: OpHandler } = { const code = await runState.eei.getExternalCode(address) if (code.length === 0) { - runState.stack.push(new BN(utils.KECCAK256_NULL)) + runState.stack.push(new BN(KECCAK256_NULL)) return } - runState.stack.push(new BN(utils.keccak256(code))) + runState.stack.push(new BN(keccak256(code))) }, RETURNDATASIZE: function (runState: RunState) { runState.stack.push(runState.eei.getReturnDataSize()) @@ -826,7 +826,7 @@ export const handlers: { [k: string]: OpHandler } = { } function describeLocation(runState: RunState) { - var hash = utils.keccak256(runState.eei.getCode()).toString('hex') + var hash = keccak256(runState.eei.getCode()).toString('hex') var address = runState.eei.getAddress().toString('hex') var pc = runState.programCounter - 1 return hash + '/' + address + ':' + pc @@ -886,7 +886,7 @@ function getDataSlice(data: Buffer, offset: BN, length: BN): Buffer { data = data.slice(offset.toNumber(), end.toNumber()) // Right-pad with zeros to fill dataLength bytes - data = utils.setLengthRight(data, length.toNumber()) + data = setLengthRight(data, length.toNumber()) return data } diff --git a/packages/vm/package.json b/packages/vm/package.json index 520e6906076..b15f245b988 100644 --- a/packages/vm/package.json +++ b/packages/vm/package.json @@ -49,7 +49,7 @@ "ethereumjs-blockchain": "^4.0.3", "ethereumjs-common": "^1.5.0", "ethereumjs-tx": "^2.1.2", - "ethereumjs-util": "^6.2.0", + "ethereumjs-util": "^7.0.2", "functional-red-black-tree": "^1.0.1", "merkle-patricia-tree": "^2.3.2", "rustbn.js": "~0.2.0", @@ -62,7 +62,7 @@ "@ethereumjs/config-prettier": "^1.1.1", "@ethereumjs/config-tsc": "^1.1.1", "@ethereumjs/config-tslint": "^1.1.1", - "@types/bn.js": "^4.11.5", + "@types/bn.js": "^4.11.6", "@types/core-js": "^2.5.0", "@types/lru-cache": "^5.1.0", "@types/node": "^11.13.4", @@ -87,7 +87,7 @@ "tslint": "^5.16.0", "typedoc": "next", "typedoc-plugin-markdown": "^2.2.17", - "typescript": "^3.8.2", + "typescript": "^3.9.2", "typestrict": "^1.0.2" }, "author": "mjbecze ", diff --git a/packages/vm/tests/util.js b/packages/vm/tests/util.js index c2a0e46b462..07c0b4fe456 100644 --- a/packages/vm/tests/util.js +++ b/packages/vm/tests/util.js @@ -1,23 +1,21 @@ const async = require('async') -const utils = require('ethereumjs-util') -const BN = utils.BN -const rlp = utils.rlp +const { BN, rlp, keccak256, stripHexPrefix, setLengthLeft } = require('ethereumjs-util') const Account = require('ethereumjs-account').default const Transaction = require('ethereumjs-tx').Transaction const Block = require('ethereumjs-block').Block -exports.dumpState = function(state, cb) { +exports.dumpState = function (state, cb) { function readAccounts(state) { return new Promise((resolve, reject) => { let accounts = [] var rs = state.createReadStream() - rs.on('data', function(data) { + rs.on('data', function (data) { let account = new Account(data.value) account.address = data.key accounts.push(account) }) - rs.on('end', function() { + rs.on('end', function () { resolve(accounts) }) }) @@ -30,26 +28,26 @@ exports.dumpState = function(state, cb) { storageTrie.root = account.stateRoot let storageRS = storageTrie.createReadStream() - storageRS.on('data', function(data) { + storageRS.on('data', function (data) { storage[data.key.toString('hex')] = data.value.toString('hex') }) - storageRS.on('end', function() { + storageRS.on('end', function () { resolve(storage) }) }) } - readAccounts(state).then(function(accounts) { + readAccounts(state).then(function (accounts) { async.mapSeries( accounts, - function(account, cb) { - readStorage(state, account).then(storage => { + function (account, cb) { + readStorage(state, account).then((storage) => { account.storage = storage cb(null, account) }) }, - function(err, results) { + function (err, results) { if (err) { cb(err, null) } @@ -69,7 +67,7 @@ exports.dumpState = function(state, cb) { }) } -var format = (exports.format = function(a, toZero, isHex) { +var format = (exports.format = function (a, toZero, isHex) { if (a === '') { return Buffer.alloc(0) } @@ -97,7 +95,7 @@ var format = (exports.format = function(a, toZero, isHex) { * @param {[type]} txData the transaction object from tests repo * @returns {Object} object that will be passed to VM.runTx function */ -exports.makeTx = function(txData, hf) { +exports.makeTx = function (txData, hf) { var tx = new Transaction({}, { hardfork: hf }) tx.nonce = format(txData.nonce) tx.gasPrice = format(txData.gasPrice) @@ -116,23 +114,23 @@ exports.makeTx = function(txData, hf) { return tx } -exports.verifyPostConditions = function(state, testData, t, cb) { +exports.verifyPostConditions = function (state, testData, t, cb) { var hashedAccounts = {} var keyMap = {} for (var key in testData) { - var hash = utils.keccak256(Buffer.from(utils.stripHexPrefix(key), 'hex')).toString('hex') + var hash = keccak256(Buffer.from(stripHexPrefix(key), 'hex')).toString('hex') hashedAccounts[hash] = testData[key] keyMap[hash] = key } - var q = async.queue(function(task, cb2) { + var q = async.queue(function (task, cb2) { exports.verifyAccountPostConditions(state, task.address, task.account, task.testData, t, cb2) }, 1) var stream = state.createReadStream() - stream.on('data', function(data) { + stream.on('data', function (data) { var acnt = new Account(rlp.decode(data.value)) var key = data.key.toString('hex') var testData = hashedAccounts[key] @@ -150,7 +148,7 @@ exports.verifyPostConditions = function(state, testData, t, cb) { } }) - stream.on('end', function() { + stream.on('end', function () { function onEnd() { for (hash in keyMap) { t.fail('Missing account!: ' + keyMap[hash]) @@ -174,7 +172,7 @@ exports.verifyPostConditions = function(state, testData, t, cb) { * @param {[type]} acctData postconditions JSON from tests repo * @param {Function} cb completion callback */ -exports.verifyAccountPostConditions = function(state, address, account, acctData, t, cb) { +exports.verifyAccountPostConditions = function (state, address, account, acctData, t, cb) { t.comment('Account: ' + address) t.equal( format(account.balance, true).toString('hex'), @@ -193,15 +191,14 @@ exports.verifyAccountPostConditions = function(state, address, account, acctData var hashedStorage = {} for (var key in acctData.storage) { - hashedStorage[ - utils.keccak256(utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)).toString('hex') - ] = acctData.storage[key] + hashedStorage[keccak256(setLengthLeft(Buffer.from(key.slice(2), 'hex'), 32)).toString('hex')] = + acctData.storage[key] } if (storageKeys.length > 0) { state.root = account.stateRoot var rs = state.createReadStream() - rs.on('data', function(data) { + rs.on('data', function (data) { var key = data.key.toString('hex') var val = '0x' + rlp.decode(data.value).toString('hex') @@ -217,7 +214,7 @@ exports.verifyAccountPostConditions = function(state, address, account, acctData delete hashedStorage[key] }) - rs.on('end', function() { + rs.on('end', function () { for (var key in hashedStorage) { if (hashedStorage[key] !== '0x00') { t.fail('key: ' + key + ' not found in storage') @@ -237,7 +234,7 @@ exports.verifyAccountPostConditions = function(state, address, account, acctData * @param {Object} results to verify * @param {Object} testData from tests repo */ -exports.verifyGas = function(results, testData, t) { +exports.verifyGas = function (results, testData, t) { var coinbaseAddr = testData.env.currentCoinbase var preBal = testData.pre[coinbaseAddr] ? testData.pre[coinbaseAddr].balance : 0 @@ -260,13 +257,13 @@ exports.verifyGas = function(results, testData, t) { * @param {Object} results to verify * @param {Object} testData from tests repo */ -exports.verifyLogs = function(logs, testData, t) { +exports.verifyLogs = function (logs, testData, t) { if (testData.logs) { - testData.logs.forEach(function(log, i) { + testData.logs.forEach(function (log, i) { var rlog = logs[i] t.equal(rlog[0].toString('hex'), log.address, 'log: valid address') t.equal('0x' + rlog[2].toString('hex'), log.data, 'log: valid data') - log.topics.forEach(function(topic, i) { + log.topics.forEach(function (topic, i) { t.equal(rlog[1][i].toString('hex'), topic, 'log: invalid topic') }) }) @@ -278,7 +275,7 @@ exports.verifyLogs = function(logs, testData, t) { * @param {Buffer} * @returns {String} */ -exports.toDecimal = function(buffer) { +exports.toDecimal = function (buffer) { return new BN(buffer).toString() } @@ -287,7 +284,7 @@ exports.toDecimal = function(buffer) { * @param {String} * @returns {Buffer} */ -exports.fromDecimal = function(string) { +exports.fromDecimal = function (string) { return Buffer.from(new BN(string).toArray()) } @@ -296,8 +293,8 @@ exports.fromDecimal = function(string) { * @param {String} hexString address for example '0x03' * @returns {Buffer} */ -exports.fromAddress = function(hexString) { - return utils.setLength(Buffer.from(new BN(hexString.slice(2), 16).toArray()), 32) +exports.fromAddress = function (hexString) { + return setLengthLeft(Buffer.from(new BN(hexString.slice(2), 16).toArray()), 32) } /** @@ -305,18 +302,18 @@ exports.fromAddress = function(hexString) { * @param {String} hexCode string from tests repo * @returns {Buffer} */ -exports.toCodeHash = function(hexCode) { - return utils.keccak256(Buffer.from(hexCode.slice(2), 'hex')) +exports.toCodeHash = function (hexCode) { + return keccak256(Buffer.from(hexCode.slice(2), 'hex')) } -exports.makeBlockHeader = function(data) { +exports.makeBlockHeader = function (data) { var header = {} header.timestamp = format(data.currentTimestamp) header.gasLimit = format(data.currentGasLimit) if (data.previousHash) { header.parentHash = format(data.previousHash, false, true) } - header.coinbase = utils.setLength(format(data.currentCoinbase, false, true), 20) + header.coinbase = setLengthLeft(format(data.currentCoinbase, false, true), 20) header.difficulty = format(data.currentDifficulty) header.number = format(data.currentNumber) return header @@ -328,7 +325,7 @@ exports.makeBlockHeader = function(data) { * @param {Object} transactions transactions for the block * @returns {Object} the block */ -exports.makeBlockFromEnv = function(env, transactions) { +exports.makeBlockFromEnv = function (env, transactions) { return new Block({ header: exports.makeBlockHeader(env), transactions: transactions || {}, @@ -344,7 +341,7 @@ exports.makeBlockFromEnv = function(env, transactions) { * @param {Object} block that the transaction belongs to * @returns {Object} object that will be passed to VM.runCode function */ -exports.makeRunCodeData = function(exec, account, block) { +exports.makeRunCodeData = function (exec, account, block) { return { account: account, origin: format(exec.origin, false, true), @@ -365,12 +362,12 @@ exports.makeRunCodeData = function(exec, account, block) { * @param {[type]} testData - JSON from tests repo * @param {Function} done - callback when function is completed */ -exports.setupPreConditions = function(state, testData, done) { +exports.setupPreConditions = function (state, testData, done) { const keysOfPre = Object.keys(testData.pre) async.eachSeries( keysOfPre, - function(key, callback) { + function (key, callback) { const acctData = testData.pre[key] const account = new Account() @@ -383,40 +380,36 @@ exports.setupPreConditions = function(state, testData, done) { async.series( [ - function(cb2) { + function (cb2) { var keys = Object.keys(acctData.storage) async.forEachSeries( keys, - function(key, cb3) { + function (key, cb3) { const valBN = new BN(acctData.storage[key].slice(2), 16) if (valBN.isZero()) { return cb3() } let val = rlp.encode(valBN.toArrayLike(Buffer, 'be')) - key = utils.setLength(Buffer.from(key.slice(2), 'hex'), 32) + key = setLengthLeft(Buffer.from(key.slice(2), 'hex'), 32) storageTrie.put(key, val, cb3) }, cb2, ) }, - function(cb2) { + function (cb2) { account.setCode(state, codeBuf, cb2) }, - function(cb2) { + function (cb2) { account.stateRoot = storageTrie.root if (testData.exec && key === testData.exec.address) { testData.root = storageTrie.root } - state.put( - Buffer.from(utils.stripHexPrefix(key), 'hex'), - account.serialize(), - function() { - cb2() - }, - ) + state.put(Buffer.from(stripHexPrefix(key), 'hex'), account.serialize(), function () { + cb2() + }) }, ], callback, @@ -431,7 +424,7 @@ exports.setupPreConditions = function(state, testData, done) { * @param {String} forkConfig - the name of the hardfork for which an alias should be returned * @returns {String} Either an alias of the forkConfig param, or the forkConfig param itself */ -exports.getRequiredForkConfigAlias = function(forkConfig) { +exports.getRequiredForkConfigAlias = function (forkConfig) { // Run the Istanbul tests for MuirGlacier since there are no dedicated tests if (String(forkConfig).match(/^muirGlacier/i)) { return 'Istanbul'