Skip to content

Commit

Permalink
Merge branch 'master' of github.com:ethereumjs/ethereumjs-monorepo in…
Browse files Browse the repository at this point in the history
…to update-eslint
  • Loading branch information
scorbajio committed Jul 25, 2023
2 parents e57ed48 + 38de29b commit 3333467
Show file tree
Hide file tree
Showing 33 changed files with 1,342 additions and 18,314 deletions.
1 change: 0 additions & 1 deletion config/eslint.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ module.exports = {
'coverage',
'dist',
'examples',
'karma.conf.js',
'node_modules',
'prettier.config.js',
'recipes',
Expand Down
19,025 changes: 972 additions & 18,053 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 0 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,6 @@
"eslint-plugin-prettier": "4.2.1",
"eslint-plugin-simple-import-sort": "7.0.0",
"eslint-plugin-sonarjs": "0.19.0",
"karma": "6.4.0",
"karma-chrome-launcher": "3.1.1",
"karma-firefox-launcher": "2.1.2",
"karma-tap": "4.2.0",
"karma-typescript": "5.5.3",
"karma-typescript-es6-transform": "5.5.3",
"lint-staged": "13.0.3",
"lockfile-lint-api": "^5.5.1",
"playwright": "^1.35.1",
Expand Down
2 changes: 0 additions & 2 deletions packages/block/test/block.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { RLP } from '@ethereumjs/rlp'
import { bytesToHex, equalsBytes, hexToBytes, toBytes, zeros } from '@ethereumjs/util'
import { assert, describe, it } from 'vitest'
// explicitly import util, needed for karma-typescript bundling
// eslint-disable-next-line @typescript-eslint/no-unused-vars, simple-import-sort/imports

import { blockFromRpc } from '../src/from-rpc.js'
import { Block } from '../src/index.js'
Expand Down
2 changes: 1 addition & 1 deletion packages/client/libp2pBrowserBuild/libp2pnode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Libp2p from 'libp2p'
import Bootstrap from 'libp2p-bootstrap'

import type { Multiaddr } from 'multiaddr'
import type PeerId from 'peer-id'
import type { PeerId } from '@libp2p/interface-peer-id'

const MPLEX = require('libp2p-mplex')
const Websockets = require('libp2p-websockets')
Expand Down
2 changes: 1 addition & 1 deletion packages/client/libp2pBrowserBuild/net/peer/libp2pnode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import LibP2P from 'libp2p'
import Bootstrap from 'libp2p-bootstrap'

import type { Multiaddr } from 'multiaddr'
import type * as PeerId from 'peer-id'
import type { PeerId } from '@libp2p/interface-peer-id'

const KadDht = require('libp2p-kad-dht')
const MPLEX = require('libp2p-mplex')
Expand Down
4 changes: 2 additions & 2 deletions packages/client/libp2pBrowserBuild/net/peer/libp2ppeer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//@ts-nocheck
import { multiaddr } from 'multiaddr'
import PeerId from 'peer-id'

import { Peer } from '../../../src/net/peer/peer'
import { Libp2pSender } from '../libp2psender'
Expand All @@ -13,6 +12,7 @@ import type { Protocol } from '../../../src/net/protocol'
import type { Libp2pServer } from '../../../src/net/server'
import type { MuxedStream } from 'libp2p-interfaces/dist/src/stream-muxer/types'
import type { Multiaddr } from 'multiaddr'
import { PeerId, isPeerId } from '@libp2p/interface-peer-id'

export interface Libp2pPeerOptions extends Omit<PeerOptions, 'address' | 'transport'> {
/* Multiaddrs to listen on */
Expand Down Expand Up @@ -104,7 +104,7 @@ export class Libp2pPeer extends Peer {
const { stream } = await node.dialProtocol(peer as any, protocol)
await this.bindProtocol(p, new Libp2pSender(stream))
} catch (err: any) {
const peerInfo = peer instanceof PeerId ? `id=${peer.toB58String()}` : `multiaddr=${peer}`
const peerInfo = isPeerId(peer) ? `id=${peer.toB58String()}` : `multiaddr=${peer}`
this.config.logger.debug(
`Peer doesn't support protocol=${protocol} ${peerInfo} ${err.stack}`
)
Expand Down
11 changes: 6 additions & 5 deletions packages/client/libp2pBrowserBuild/net/server/libp2pserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// eslint-disable-next-line implicit-dependencies/no-implicit, import/no-extraneous-dependencies
import { keys } from 'libp2p-crypto'
import { multiaddr } from 'multiaddr'
import PeerId from 'peer-id'
import { PeerId } from '@libp2p/interface-peer-id'

import { Event } from '../../../src/types'
import { Libp2pPeer } from '../../../src/net/peer'
Expand All @@ -13,6 +13,7 @@ import { Server } from '../../../src/net/server/server'
import type { ServerOptions } from '../../../src/net/server/server'
import type Connection from 'libp2p-interfaces/dist/src/connection/connection'
import type { Multiaddr } from 'multiaddr'
import { createFromPrivKey } from '@libp2p/peer-id-factory'

export interface Libp2pServerOptions extends ServerOptions {
/* Multiaddrs to listen on */
Expand Down Expand Up @@ -79,7 +80,7 @@ export class Libp2pServer extends Server {
}
}
this.node.on('peer:discovery', async (peerId: PeerId) => {
const id = peerId.toB58String()
const id = peerId.toString()
if (this.peers.get(id) || this.isBanned(id)) {
return
}
Expand All @@ -103,7 +104,7 @@ export class Libp2pServer extends Server {
this.node.addressManager.getListenAddrs().map(async (ma) => {
this.config.events.emit(Event.SERVER_LISTENING, {
transport: this.name,
url: `${ma}/p2p/${peerId.toB58String()}`,
url: `${ma}/p2p/${peerId.toString()}`,
})
})
this.started = true
Expand Down Expand Up @@ -161,7 +162,7 @@ export class Libp2pServer extends Server {
async getPeerId() {
const privKey = await keys.generateKeyPairFromSeed('ed25519', this.key, 512)
const protoBuf = keys.marshalPrivateKey(privKey)
return PeerId.createFromPrivKey(protoBuf)
return createFromPrivKey(protoBuf)
}

getPeerInfo(connection: Connection): [peerId: PeerId, multiaddr: Multiaddr, inbound: boolean] {
Expand All @@ -171,7 +172,7 @@ export class Libp2pServer extends Server {
createPeer(peerId: PeerId, multiaddrs?: Multiaddr[], inbound = false) {
const peer = new Libp2pPeer({
config: this.config,
id: peerId.toB58String(),
id: peerId.toString(),
multiaddrs,
protocols: Array.from(this.protocols),
inbound,
Expand Down
3 changes: 2 additions & 1 deletion packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@
"level": "^8.0.0",
"memory-level": "^1.0.0",
"multiaddr": "^10.0.1",
"peer-id": "^0.14.3",
"@libp2p/interface-peer-id": "2.0.2",
"@libp2p/peer-id-factory": "2.0.4",
"qheap": "^1.4.0",
"winston": "^3.3.3",
"winston-daily-rotate-file": "^4.5.5",
Expand Down
47 changes: 47 additions & 0 deletions packages/client/src/rpc/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { bigIntToHex, bytesToHex, intToHex } from '@ethereumjs/util'

import { INVALID_PARAMS } from './error-code'

import type { Chain } from '../blockchain'
import type { Block } from '@ethereumjs/block'
import type { JsonRpcTx, TypedTransaction } from '@ethereumjs/tx'

Expand Down Expand Up @@ -32,3 +35,47 @@ export const jsonRpcTx = (tx: TypedTransaction, block?: Block, txIndex?: number)
versionedHashes: txJSON.versionedHashes,
}
}

/**
* Get block by option
*/
export const getBlockByOption = async (blockOpt: string, chain: Chain) => {
if (blockOpt === 'pending') {
throw {
code: INVALID_PARAMS,
message: `"pending" is not yet supported`,
}
}

let block: Block
const latest = chain.blocks.latest ?? (await chain.getCanonicalHeadBlock())

switch (blockOpt) {
case 'earliest':
block = await chain.getBlock(BigInt(0))
break
case 'latest':
block = latest
break
case 'safe':
block = chain.blocks.safe ?? (await chain.getCanonicalSafeBlock())
break
case 'finalized':
block = chain.blocks.finalized ?? (await chain.getCanonicalFinalizedBlock())
break
default: {
const blockNumber = BigInt(blockOpt)
if (blockNumber === latest.header.number) {
block = latest
} else if (blockNumber > latest.header.number) {
throw {
code: INVALID_PARAMS,
message: 'specified block greater than current height',
}
} else {
block = await chain.getBlock(blockNumber)
}
}
}
return block
}
112 changes: 110 additions & 2 deletions packages/client/src/rpc/modules/debug.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { bigIntToHex, bytesToHex, hexToBytes } from '@ethereumjs/util'
import { Address, TypeOutput, bigIntToHex, bytesToHex, hexToBytes, toType } from '@ethereumjs/util'

import { INTERNAL_ERROR, INVALID_PARAMS } from '../error-code'
import { getBlockByOption } from '../helpers'
import { middleware, validators } from '../validation'

import type { EthereumClient } from '../..'
import type { Chain } from '../../blockchain'
import type { FullEthereumService } from '../../service'
import type { RpcTx } from '../types'
import type { VM } from '@ethereumjs/vm'

export interface tracerOpts {
disableStack?: boolean
Expand Down Expand Up @@ -73,18 +77,28 @@ const validateTracerConfig = (opts: tracerOpts): tracerOpts => {
*/
export class Debug {
private service: FullEthereumService
private chain: Chain
private vm: VM
/**
* Create debug_* RPC module
* @param client Client to which the module binds
*/
constructor(client: EthereumClient) {
this.service = client.services.find((s) => s.name === 'eth') as FullEthereumService
this.chain = this.service.chain
this.vm = (this.service as FullEthereumService).execution?.vm
this.traceTransaction = middleware(this.traceTransaction.bind(this), 1, [[validators.hex]])
this.traceCall = middleware(this.traceCall.bind(this), 2, [
[validators.transaction()],
[validators.blockOption],
])
}

/**
* Returns a call trace for the requested transaction or null if not available
* @param params string representing the transaction hash
* @param params an array of two parameters:
* 1. string representing the transaction hash
* 2. an optional tracer options object
*/
async traceTransaction(params: [string, tracerOpts]) {
const [txHash, config] = params
Expand Down Expand Up @@ -170,4 +184,98 @@ export class Debug {
}
}
}

/**
* Returns a trace of an eth_call within the context of the given block execution using the final state of the parent block
* @param params an array of 3 parameters:
* 1. an {@link RpcTx} object that mirrors the eth_call parameters object
* 2. A block hash or number formatted as a hex prefixed string
* 3. An optional tracer options object
* @returns an execution trace of an {@link eth_call} in the context of a given block execution
* mirroring the output from {@link traceTransaction}
*/
async traceCall(params: [RpcTx, string, tracerOpts]) {
const [callArgs, blockOpt, tracerOpts] = params
// Validate configuration and parameters
if (!this.service.execution.receiptsManager) {
throw {
message: 'missing receiptsManager',
code: INTERNAL_ERROR,
}
}

if (this.vm === undefined) {
throw new Error('missing vm')
}

const opts = validateTracerConfig(tracerOpts)

const block = await getBlockByOption(blockOpt, this.chain)
const parentBlock = await this.service.chain.getBlock(block.header.parentHash)

const vm = await this.vm.shallowCopy()
await vm.stateManager.setStateRoot(parentBlock.header.stateRoot)
const { from, to, gas: gasLimit, gasPrice, value, data } = callArgs

const trace = {
gas: '',
returnValue: '',
failed: false,
structLogs: [] as structLog[],
}
vm.evm.events?.on('step', async (step, next) => {
const memory = []
let storage = {}
if (opts.disableStorage === false) {
storage = await vm.stateManager.dumpStorage(step.address)
}
if (opts.enableMemory === true) {
for (let x = 0; x < step.memoryWordCount; x++) {
const word = bytesToHex(step.memory.slice(x * 32, 32))
memory.push(word)
}
}
const log = {
pc: step.pc,
op: step.opcode.name,
gasCost: step.opcode.fee + Number(step.opcode.dynamicFee),
gas: Number(step.gasLeft),
depth: step.depth,
error: null,
stack: opts.disableStack !== true ? step.stack.map(bigIntToHex) : undefined,
storage,
memory,
returnData: undefined,
}
trace.structLogs.push(log)
next?.()
})

vm.evm.events?.on('afterMessage', (data, next) => {
if (data.execResult.exceptionError !== undefined && trace.structLogs.length > 0) {
// Mark last opcode trace as error if exception occurs
trace.structLogs[trace.structLogs.length - 1].error = true
}
next?.()
})
const runCallOpts = {
caller: from !== undefined ? Address.fromString(from) : undefined,
to: to !== undefined ? Address.fromString(to) : undefined,
gasLimit: toType(gasLimit, TypeOutput.BigInt),
gasPrice: toType(gasPrice, TypeOutput.BigInt),
value: toType(value, TypeOutput.BigInt),
data: data !== undefined ? hexToBytes(data) : undefined,
}
const res = await vm.evm.runCall(runCallOpts)
trace.gas = bigIntToHex(res.execResult.executionGasUsed)
trace.failed = res.execResult.exceptionError !== undefined
trace.returnValue = bytesToHex(res.execResult.returnValue)
return trace
}
catch(err: any) {
throw {
code: INTERNAL_ERROR,
message: err.message.toString(),
}
}
}
46 changes: 1 addition & 45 deletions packages/client/src/rpc/modules/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from '@ethereumjs/util'

import { INTERNAL_ERROR, INVALID_PARAMS, PARSE_ERROR } from '../error-code'
import { jsonRpcTx } from '../helpers'
import { getBlockByOption, jsonRpcTx } from '../helpers'
import { middleware, validators } from '../validation'

import type { EthereumClient } from '../..'
Expand Down Expand Up @@ -196,50 +196,6 @@ const jsonRpcReceipt = async (
dataGasPrice: dataGasPrice !== undefined ? bigIntToHex(dataGasPrice) : undefined,
})

/**
* Get block by option
*/
const getBlockByOption = async (blockOpt: string, chain: Chain) => {
if (blockOpt === 'pending') {
throw {
code: INVALID_PARAMS,
message: `"pending" is not yet supported`,
}
}

let block: Block
const latest = chain.blocks.latest ?? (await chain.getCanonicalHeadBlock())

switch (blockOpt) {
case 'earliest':
block = await chain.getBlock(BigInt(0))
break
case 'latest':
block = latest
break
case 'safe':
block = chain.blocks.safe ?? (await chain.getCanonicalSafeBlock())
break
case 'finalized':
block = chain.blocks.finalized ?? (await chain.getCanonicalFinalizedBlock())
break
default: {
const blockNumber = BigInt(blockOpt)
if (blockNumber === latest.header.number) {
block = latest
} else if (blockNumber > latest.header.number) {
throw {
code: INVALID_PARAMS,
message: 'specified block greater than current height',
}
} else {
block = await chain.getBlock(blockNumber)
}
}
}
return block
}

/**
* eth_* RPC module
* @memberof module:rpc/modules
Expand Down
Loading

0 comments on commit 3333467

Please sign in to comment.