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

devp2p: remove isTruthy and isFalsy #2254

Merged
merged 3 commits into from
Aug 30, 2022
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
15 changes: 5 additions & 10 deletions packages/devp2p/examples/peer-communication-les.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { randomBytes } from 'crypto'
import { Block, BlockHeader } from '@ethereumjs/block'
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { TypedTransaction } from '@ethereumjs/tx'
import { isTruthy } from '@ethereumjs/util'
import chalk from 'chalk'
import ms from 'ms'

Expand Down Expand Up @@ -65,9 +64,7 @@ const rlpx = new devp2p.RLPx(PRIVATE_KEY, {
remoteClientIdFilter: REMOTE_CLIENTID_FILTER,
})

rlpx.on('error', (err) =>
console.error(chalk.red(`RLPx error: ${isTruthy(err.stack) ? err.stack : err}`))
)
rlpx.on('error', (err) => console.error(chalk.red(`RLPx error: ${err.stack ?? err}`)))

rlpx.on('peer:added', (peer) => {
const addr = getPeerAddr(peer)
Expand Down Expand Up @@ -150,7 +147,7 @@ rlpx.on('peer:added', (peer) => {
})

rlpx.on('peer:removed', (peer, reasonCode, disconnectWe) => {
const who = isTruthy(disconnectWe) ? 'we disconnect' : 'peer disconnect'
const who = disconnectWe === true ? 'we disconnect' : 'peer disconnect'
const total = rlpx.getPeers().length
console.log(
chalk.yellow(
Expand All @@ -172,9 +169,7 @@ rlpx.on('peer:error', (peer, err) => {
return
}

console.error(
chalk.red(`Peer error (${getPeerAddr(peer)}): ${isTruthy(err.stack) ? err.stack : err}`)
)
console.error(chalk.red(`Peer error (${getPeerAddr(peer)}): ${err.stack ?? err}`))
})

// uncomment, if you want accept incoming connections
Expand All @@ -183,7 +178,7 @@ rlpx.on('peer:error', (peer, err) => {

for (const bootnode of BOOTNODES) {
dpt.bootstrap(bootnode).catch((err) => {
console.error(chalk.bold.red(`DPT bootstrap error: ${isTruthy(err.stack) ? err.stack : err}`))
console.error(chalk.bold.red(`DPT bootstrap error: ${err.stack ?? err}`))
})
}

Expand All @@ -198,7 +193,7 @@ dpt.addPeer({ address: '127.0.0.1', udpPort: 30303, tcpPort: 30303 })
udpPort: peer.tcpPort
})
})
.catch((err) => console.log(`error on connection to local node: ${isTruthy(err.stack) ? err.stack : err}`)) */
.catch((err) => console.log(`error on connection to local node: ${err.stack ?? err}`)) */

function onNewBlock(block: Block, peer: Peer) {
const blockHashHex = block.hash().toString('hex')
Expand Down
16 changes: 6 additions & 10 deletions packages/devp2p/examples/peer-communication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Block, BlockHeader } from '@ethereumjs/block'
import { Chain, Common, Hardfork } from '@ethereumjs/common'
import { RLP } from '@ethereumjs/rlp'
import { TransactionFactory, TypedTransaction } from '@ethereumjs/tx'
import { arrToBufArr, isTruthy } from '@ethereumjs/util'
import { arrToBufArr } from '@ethereumjs/util'
import chalk from 'chalk'
import LRUCache from 'lru-cache'
import ms from 'ms'
Expand Down Expand Up @@ -69,9 +69,7 @@ const rlpx = new devp2p.RLPx(PRIVATE_KEY, {
remoteClientIdFilter: REMOTE_CLIENTID_FILTER,
})

rlpx.on('error', (err) =>
console.error(chalk.red(`RLPx error: ${isTruthy(err.stack) ? err.stack : err}`))
)
rlpx.on('error', (err) => console.error(chalk.red(`RLPx error: ${err.stack ?? err}`)))

rlpx.on('peer:added', (peer) => {
const addr = getPeerAddr(peer)
Expand Down Expand Up @@ -289,7 +287,7 @@ rlpx.on('peer:added', (peer) => {
})

rlpx.on('peer:removed', (peer, reasonCode, disconnectWe) => {
const who = isTruthy(disconnectWe) ? 'we disconnect' : 'peer disconnect'
const who = disconnectWe === true ? 'we disconnect' : 'peer disconnect'
const total = rlpx.getPeers().length
console.log(
chalk.yellow(
Expand All @@ -311,9 +309,7 @@ rlpx.on('peer:error', (peer, err) => {
return
}

console.error(
chalk.red(`Peer error (${getPeerAddr(peer)}): ${isTruthy(err.stack) ? err.stack : err}`)
)
console.error(chalk.red(`Peer error (${getPeerAddr(peer)}): ${err.stack ?? err}`))
})

// uncomment, if you want accept incoming connections
Expand All @@ -322,7 +318,7 @@ rlpx.on('peer:error', (peer, err) => {

for (const bootnode of BOOTNODES) {
dpt.bootstrap(bootnode).catch((err) => {
console.error(chalk.bold.red(`DPT bootstrap error: ${isTruthy(err.stack) ? err.stack : err}`))
console.error(chalk.bold.red(`DPT bootstrap error: ${err.stack ?? err}`))
})
}

Expand All @@ -337,7 +333,7 @@ dpt.addPeer({ address: '127.0.0.1', udpPort: 30303, tcpPort: 30303 })
udpPort: peer.tcpPort
})
})
.catch((err) => console.log(`error on connection to local node: ${isTruthy(err.stack) ? err.stack : err}`))
.catch((err) => console.log(`error on connection to local node: ${err.stack ?? err}`))
*/

const txCache = new LRUCache({ max: 1000 })
Expand Down
7 changes: 2 additions & 5 deletions packages/devp2p/examples/simple.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Chain, Common } from '@ethereumjs/common'
import { isTruthy } from '@ethereumjs/util'
import chalk from 'chalk'

import { DPT } from '../src/index'
Expand All @@ -25,7 +24,7 @@ const dpt = new DPT(Buffer.from(PRIVATE_KEY, 'hex'), {
})

/* eslint-disable no-console */
dpt.on('error', (err) => console.error(chalk.red(isTruthy(err.stack) ? err.stack : err)))
dpt.on('error', (err) => console.error(chalk.red(err.stack ?? err)))

dpt.on('peer:added', (peer) => {
const info = `(${peer.id.toString('hex')},${peer.address},${peer.udpPort},${peer.tcpPort})`
Expand All @@ -42,7 +41,5 @@ dpt.on('peer:removed', (peer) => {
// dpt.bind(30303, '0.0.0.0')

for (const bootnode of BOOTNODES) {
dpt
.bootstrap(bootnode)
.catch((err) => console.error(chalk.bold.red(isTruthy(err.stack) ? err.stack : err)))
dpt.bootstrap(bootnode).catch((err) => console.error(chalk.bold.red(err.stack ?? err)))
}
5 changes: 2 additions & 3 deletions packages/devp2p/src/dns/dns.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { isFalsy, isTruthy } from '@ethereumjs/util'
import { debug as createDebugLogger } from 'debug'

import { ENR } from './enr'
Expand Down Expand Up @@ -37,7 +36,7 @@ export class DNS {
constructor(options: DNSOptions = {}) {
this._DNSTreeCache = {}

if (isTruthy(options.dnsServerAddress)) {
if (typeof options.dnsServerAddress === 'string') {
dns.setServers([options.dnsServerAddress])
}
}
Expand Down Expand Up @@ -198,7 +197,7 @@ export class DNS {
* @return {boolean}
*/
private _isNewPeer(peer: PeerInfo | null, peers: PeerInfo[]): boolean {
if (isFalsy(peer) || isFalsy(peer.address)) return false
if (peer === null || peer.address === undefined) return false

for (const existingPeer of peers) {
if (peer.address === existingPeer.address) {
Expand Down
4 changes: 2 additions & 2 deletions packages/devp2p/src/dpt/kbucket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { isTruthy } from '@ethereumjs/util'
import { EventEmitter } from 'events'
import _KBucket = require('k-bucket')

Expand Down Expand Up @@ -49,7 +48,8 @@ export class KBucket extends EventEmitter {

const keys = []
if (Buffer.isBuffer(obj.id)) keys.push(obj.id.toString('hex'))
if (isTruthy(obj.address) && isTruthy(obj.tcpPort)) keys.push(`${obj.address}:${obj.tcpPort}`)
if (obj.address !== undefined && typeof obj.tcpPort === 'number')
keys.push(`${obj.address}:${obj.tcpPort}`)
return keys
}

Expand Down
7 changes: 3 additions & 4 deletions packages/devp2p/src/dpt/server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { isTruthy } from '@ethereumjs/util'
import { debug as createDebugLogger } from 'debug'
import * as dgram from 'dgram'
import { EventEmitter } from 'events'
Expand Down Expand Up @@ -164,7 +163,7 @@ export class Server extends EventEmitter {
}
}, this._timeout)
}
if (this._socket && isTruthy(peer.udpPort))
if (this._socket && typeof peer.udpPort === 'number')
this._socket.send(msg, 0, msg.length, peer.udpPort, peer.address)
return msg.slice(0, 32) // message id
}
Expand Down Expand Up @@ -204,12 +203,12 @@ export class Server extends EventEmitter {
case 'pong': {
let rkey = info.data.hash.toString('hex')
const rkeyParity = this._parityRequestMap.get(rkey)
if (isTruthy(rkeyParity)) {
if (typeof rkeyParity === 'string') {
rkey = rkeyParity
this._parityRequestMap.delete(rkeyParity)
}
const request = this._requests.get(rkey)
if (isTruthy(request)) {
if (request !== undefined) {
this._requests.delete(rkey)
request.deferred.resolve({
id: peerId,
Expand Down
19 changes: 5 additions & 14 deletions packages/devp2p/src/protocol/eth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
bufArrToArr,
bufferToBigInt,
bufferToHex,
isTruthy,
} from '@ethereumjs/util'
import * as snappy from 'snappyjs'

Expand All @@ -32,7 +31,7 @@ export class ETH extends Protocol {
// Set forkHash and nextForkBlock
if (this._version >= 64) {
const c = this._peer._common
this._hardfork = isTruthy(c.hardfork()) ? c.hardfork() : this._hardfork
this._hardfork = c.hardfork() ?? this._hardfork
// Set latestBlock minimally to start block of fork to have some more
// accurate basis if no latestBlock is provided along status send
this._latestBlock = c.hardforkBlock(this._hardfork) ?? BigInt(0)
Expand Down Expand Up @@ -68,7 +67,7 @@ export class ETH extends Protocol {
)
this._peerStatus = payload as ETH.StatusMsg
const peerStatusMsg = `${
isTruthy(this._peerStatus) ? this._getStatusString(this._peerStatus) : ''
this._peerStatus !== undefined ? this._getStatusString(this._peerStatus) : ''
}`
this.debug(messageName, `${debugMsg}: ${peerStatusMsg}`)
this._handleStatus()
Expand Down Expand Up @@ -219,7 +218,7 @@ export class ETH extends Protocol {
)}`
if (this._version >= 64) {
sStr += `, ForkHash: ${
isTruthy(status[5]) ? '0x' + (status[5][0] as Buffer).toString('hex') : '-'
status[5] !== undefined ? '0x' + (status[5][0] as Buffer).toString('hex') : '-'
}`
sStr += `, ForkNext: ${
(status[5][1] as Buffer).length > 0 ? buffer2int(status[5][1] as Buffer) : '-'
Expand Down Expand Up @@ -268,11 +267,7 @@ export class ETH extends Protocol {
let payload = Buffer.from(RLP.encode(bufArrToArr(this._status)))

// Use snappy compression if peer supports DevP2P >=v5
if (
isTruthy(this._peer._hello) &&
isTruthy(this._peer._hello.protocolVersion) &&
this._peer._hello.protocolVersion >= 5
) {
if (this._peer._hello !== null && this._peer._hello.protocolVersion >= 5) {
payload = snappy.compress(payload)
}

Expand Down Expand Up @@ -324,11 +319,7 @@ export class ETH extends Protocol {
payload = Buffer.from(RLP.encode(bufArrToArr(payload)))

// Use snappy compression if peer supports DevP2P >=v5
if (
isTruthy(this._peer._hello) &&
isTruthy(this._peer._hello.protocolVersion) &&
this._peer._hello?.protocolVersion >= 5
) {
if (this._peer._hello !== null && this._peer._hello.protocolVersion >= 5) {
payload = snappy.compress(payload)
}

Expand Down
34 changes: 13 additions & 21 deletions packages/devp2p/src/protocol/les.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RLP } from '@ethereumjs/rlp'
import { arrToBufArr, bigIntToBuffer, bufArrToArr, isFalsy, isTruthy } from '@ethereumjs/util'
import { arrToBufArr, bigIntToBuffer, bufArrToArr } from '@ethereumjs/util'
import ms = require('ms')
import * as snappy from 'snappyjs'

Expand Down Expand Up @@ -136,20 +136,20 @@ export class LES extends Protocol {
)}, `
sStr += `HeadH:${status['headHash'].toString('hex')}, HeadN:${buffer2int(status['headNum'])}, `
sStr += `GenH:${status['genesisHash'].toString('hex')}`
if (isTruthy(status['serveHeaders'])) sStr += `, serveHeaders active`
if (isTruthy(status['serveChainSince']))
if (status['serveHeaders'] !== undefined) sStr += `, serveHeaders active`
if (status['serveChainSince'] !== undefined)
sStr += `, ServeCS: ${buffer2int(status['serveChainSince'])}`
if (isTruthy(status['serveStateSince']))
if (status['serveStateSince'] !== undefined)
sStr += `, ServeSS: ${buffer2int(status['serveStateSince'])}`
if (isTruthy(status['txRelay'])) sStr += `, txRelay active`
if (isTruthy(status['flowControl/BL)'])) sStr += `, flowControl/BL set`
if (isTruthy(status['flowControl/MRR)'])) sStr += `, flowControl/MRR set`
if (isTruthy(status['flowControl/MRC)'])) sStr += `, flowControl/MRC set`
if (isTruthy(status['forkID']))
if (status['txRelay'] !== undefined) sStr += `, txRelay active`
if (status['flowControl/BL)'] !== undefined) sStr += `, flowControl/BL set`
if (status['flowControl/MRR)'] !== undefined) sStr += `, flowControl/MRR set`
if (status['flowControl/MRC)'] !== undefined) sStr += `, flowControl/MRC set`
if (status['forkID'] !== undefined)
sStr += `, forkID: [crc32: ${status['forkID'][0].toString('hex')}, nextFork: ${buffer2int(
status['forkID'][1]
)}]`
if (isTruthy(status['recentTxLookup']))
if (status['recentTxLookup'] !== undefined)
sStr += `, recentTxLookup: ${buffer2int(status['recentTxLookup'])}`
sStr += `]`
return sStr
Expand All @@ -158,7 +158,7 @@ export class LES extends Protocol {
sendStatus(status: LES.Status) {
if (this._status !== null) return

if (isFalsy(status.announceType)) {
if (status.announceType === undefined) {
status['announceType'] = int2buffer(DEFAULT_ANNOUNCE_TYPE)
}
status['protocolVersion'] = int2buffer(this._version)
Expand All @@ -181,11 +181,7 @@ export class LES extends Protocol {
let payload = Buffer.from(RLP.encode(bufArrToArr(statusList)))

// Use snappy compression if peer supports DevP2P >=v5
if (
isTruthy(this._peer._hello) &&
isTruthy(this._peer._hello.protocolVersion) &&
this._peer._hello?.protocolVersion >= 5
) {
if (this._peer._hello !== null && this._peer._hello.protocolVersion >= 5) {
payload = snappy.compress(payload)
}

Expand Down Expand Up @@ -248,11 +244,7 @@ export class LES extends Protocol {
payload = Buffer.from(RLP.encode(payload))

// Use snappy compression if peer supports DevP2P >=v5
if (
isTruthy(this._peer._hello) &&
isTruthy(this._peer._hello.protocolVersion) &&
this._peer._hello?.protocolVersion >= 5
) {
if (this._peer._hello !== null && this._peer._hello.protocolVersion >= 5) {
payload = snappy.compress(payload)
}

Expand Down
9 changes: 4 additions & 5 deletions packages/devp2p/src/protocol/protocol.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { isTruthy } from '@ethereumjs/util'
import { debug as createDebugLogger } from 'debug'
import { EventEmitter } from 'events'
import ms = require('ms')
Expand Down Expand Up @@ -72,7 +71,7 @@ export class Protocol extends EventEmitter {

// Remote Peer IP logger
const ip = this._peer._socket.remoteAddress
if (isTruthy(ip)) {
if (typeof ip === 'string') {
this.msgDebuggers[ip] = devp2pDebug.extend(ip)
}
}
Expand All @@ -85,7 +84,7 @@ export class Protocol extends EventEmitter {
*/
_addFirstPeerDebugger() {
const ip = this._peer._socket.remoteAddress
if (isTruthy(ip)) {
if (typeof ip === 'string') {
this.msgDebuggers[ip] = devp2pDebug.extend('FIRST_PEER')
this._peer._addFirstPeerDebugger()
this._firstPeer = ip
Expand All @@ -100,11 +99,11 @@ export class Protocol extends EventEmitter {
*/
protected debug(messageName: string, msg: string) {
this._debug(msg)
if (isTruthy(this.msgDebuggers[messageName])) {
if (this.msgDebuggers[messageName] !== undefined) {
this.msgDebuggers[messageName](msg)
}
const ip = this._peer._socket.remoteAddress
if (isTruthy(ip) && isTruthy(this.msgDebuggers[ip])) {
if (typeof ip === 'string' && this.msgDebuggers[ip] !== undefined) {
this.msgDebuggers[ip](msg)
}
}
Expand Down
3 changes: 1 addition & 2 deletions packages/devp2p/src/protocol/snap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { RLP, utils } from '@ethereumjs/rlp'
import { isTruthy } from '@ethereumjs/util'
import * as snappy from 'snappyjs'

import { formatLogData } from '../util'
Expand Down Expand Up @@ -76,7 +75,7 @@ export class SNAP extends Protocol {

// Use snappy compression if peer supports DevP2P >=v5
const protocolVersion = this._peer._hello?.protocolVersion
if (isTruthy(protocolVersion) && protocolVersion >= 5) {
if (protocolVersion !== undefined && protocolVersion >= 5) {
payload = snappy.compress(payload)
}

Expand Down
Loading