diff --git a/packages/devp2p/examples/peer-communication-les.ts b/packages/devp2p/examples/peer-communication-les.ts index 36b4ed7eeb..350e17e52a 100644 --- a/packages/devp2p/examples/peer-communication-les.ts +++ b/packages/devp2p/examples/peer-communication-les.ts @@ -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' @@ -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) @@ -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( @@ -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 @@ -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}`)) }) } @@ -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') diff --git a/packages/devp2p/examples/peer-communication.ts b/packages/devp2p/examples/peer-communication.ts index 154aeeb75d..3fd39e4bf3 100644 --- a/packages/devp2p/examples/peer-communication.ts +++ b/packages/devp2p/examples/peer-communication.ts @@ -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' @@ -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) @@ -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( @@ -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 @@ -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}`)) }) } @@ -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 }) diff --git a/packages/devp2p/examples/simple.ts b/packages/devp2p/examples/simple.ts index f0939e3177..6105551209 100644 --- a/packages/devp2p/examples/simple.ts +++ b/packages/devp2p/examples/simple.ts @@ -1,5 +1,4 @@ import { Chain, Common } from '@ethereumjs/common' -import { isTruthy } from '@ethereumjs/util' import chalk from 'chalk' import { DPT } from '../src/index' @@ -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})` @@ -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))) } diff --git a/packages/devp2p/src/dns/dns.ts b/packages/devp2p/src/dns/dns.ts index fae4992e6b..1a391a7a92 100644 --- a/packages/devp2p/src/dns/dns.ts +++ b/packages/devp2p/src/dns/dns.ts @@ -1,4 +1,3 @@ -import { isFalsy, isTruthy } from '@ethereumjs/util' import { debug as createDebugLogger } from 'debug' import { ENR } from './enr' @@ -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]) } } @@ -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) { diff --git a/packages/devp2p/src/dpt/kbucket.ts b/packages/devp2p/src/dpt/kbucket.ts index ac360024d6..c9a99e262e 100644 --- a/packages/devp2p/src/dpt/kbucket.ts +++ b/packages/devp2p/src/dpt/kbucket.ts @@ -1,4 +1,3 @@ -import { isTruthy } from '@ethereumjs/util' import { EventEmitter } from 'events' import _KBucket = require('k-bucket') @@ -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 } diff --git a/packages/devp2p/src/dpt/server.ts b/packages/devp2p/src/dpt/server.ts index 9b95b9950c..ae273cc04f 100644 --- a/packages/devp2p/src/dpt/server.ts +++ b/packages/devp2p/src/dpt/server.ts @@ -1,4 +1,3 @@ -import { isTruthy } from '@ethereumjs/util' import { debug as createDebugLogger } from 'debug' import * as dgram from 'dgram' import { EventEmitter } from 'events' @@ -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 } @@ -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, diff --git a/packages/devp2p/src/protocol/eth.ts b/packages/devp2p/src/protocol/eth.ts index ca899636aa..95dec575a0 100644 --- a/packages/devp2p/src/protocol/eth.ts +++ b/packages/devp2p/src/protocol/eth.ts @@ -5,7 +5,6 @@ import { bufArrToArr, bufferToBigInt, bufferToHex, - isTruthy, } from '@ethereumjs/util' import * as snappy from 'snappyjs' @@ -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) @@ -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() @@ -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) : '-' @@ -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) } @@ -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) } diff --git a/packages/devp2p/src/protocol/les.ts b/packages/devp2p/src/protocol/les.ts index 683f6ae2b9..cdfe303adb 100644 --- a/packages/devp2p/src/protocol/les.ts +++ b/packages/devp2p/src/protocol/les.ts @@ -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' @@ -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 @@ -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) @@ -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) } @@ -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) } diff --git a/packages/devp2p/src/protocol/protocol.ts b/packages/devp2p/src/protocol/protocol.ts index 0d27c81d4e..5f239ed963 100644 --- a/packages/devp2p/src/protocol/protocol.ts +++ b/packages/devp2p/src/protocol/protocol.ts @@ -1,4 +1,3 @@ -import { isTruthy } from '@ethereumjs/util' import { debug as createDebugLogger } from 'debug' import { EventEmitter } from 'events' import ms = require('ms') @@ -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) } } @@ -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 @@ -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) } } diff --git a/packages/devp2p/src/protocol/snap.ts b/packages/devp2p/src/protocol/snap.ts index 0208267d29..c496b10f80 100644 --- a/packages/devp2p/src/protocol/snap.ts +++ b/packages/devp2p/src/protocol/snap.ts @@ -1,5 +1,4 @@ import { RLP, utils } from '@ethereumjs/rlp' -import { isTruthy } from '@ethereumjs/util' import * as snappy from 'snappyjs' import { formatLogData } from '../util' @@ -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) } diff --git a/packages/devp2p/src/rlpx/ecies.ts b/packages/devp2p/src/rlpx/ecies.ts index 9ea15ebf11..d6ffd6d921 100644 --- a/packages/devp2p/src/rlpx/ecies.ts +++ b/packages/devp2p/src/rlpx/ecies.ts @@ -1,5 +1,5 @@ import { RLP } from '@ethereumjs/rlp' -import { bufArrToArr, isFalsy, isTruthy } from '@ethereumjs/util' +import { bufArrToArr } from '@ethereumjs/util' import * as crypto from 'crypto' import { debug as createDebugLogger } from 'debug' import { getPublicKey } from 'ethereum-cryptography/secp256k1' @@ -78,7 +78,7 @@ export class ECIES { constructor(privateKey: Buffer, id: Buffer, remoteId: Buffer) { this._privateKey = privateKey this._publicKey = id2pk(id) - this._remotePublicKey = isTruthy(remoteId) ? id2pk(remoteId) : null + this._remotePublicKey = remoteId !== null ? id2pk(remoteId) : null this._nonce = crypto.randomBytes(32) this._ephemeralPrivateKey = genPrivateKey() @@ -167,7 +167,7 @@ export class ECIES { this._ingressMac.update(Buffer.concat([xor(macSecret, this._nonce), remoteData])) this._egressMac = new MAC(macSecret) - if (isFalsy(this._initMsg)) return + if (this._initMsg === null || this._initMsg === undefined) return this._egressMac.update(Buffer.concat([xor(macSecret, this._remoteNonce), this._initMsg])) } @@ -246,16 +246,16 @@ export class ECIES { const x = ecdhX(this._remotePublicKey, this._privateKey) - if (isFalsy(this._remoteNonce)) { + if (this._remoteNonce === null) { return } this._remoteEphemeralPublicKey = Buffer.from( ecdsaRecover(signature, recoveryId, xor(x, this._remoteNonce), false) ) - if (isFalsy(this._remoteEphemeralPublicKey)) return + if (this._remoteEphemeralPublicKey === null) return this._ephemeralSharedSecret = ecdhX(this._remoteEphemeralPublicKey, this._ephemeralPrivateKey) - if (heid !== null && isTruthy(this._remoteEphemeralPublicKey)) { + if (heid !== null && this._remoteEphemeralPublicKey !== null) { assertEq( keccak256(pk2id(this._remoteEphemeralPublicKey)), heid, diff --git a/packages/devp2p/src/rlpx/peer.ts b/packages/devp2p/src/rlpx/peer.ts index f485ec3bf2..7a67194df5 100644 --- a/packages/devp2p/src/rlpx/peer.ts +++ b/packages/devp2p/src/rlpx/peer.ts @@ -1,5 +1,5 @@ import { RLP } from '@ethereumjs/rlp' -import { arrToBufArr, bufArrToArr, isFalsy, isTruthy } from '@ethereumjs/util' +import { arrToBufArr, bufArrToArr } from '@ethereumjs/util' import BufferList = require('bl') import { debug as createDebugLogger } from 'debug' import { EventEmitter } from 'events' @@ -88,7 +88,7 @@ export class Peer extends EventEmitter { _id: Buffer _remoteClientIdFilter: any _remoteId: Buffer - _EIP8: Buffer + _EIP8: Buffer | boolean _eciesSession: ECIES _state: string _weHello: HelloMsg | null @@ -101,7 +101,7 @@ export class Peer extends EventEmitter { _closed: boolean _connected: boolean _disconnectReason?: DISCONNECT_REASONS - _disconnectWe: any + _disconnectWe: null | boolean _pingTimeout: number _logger: Debugger @@ -139,9 +139,10 @@ export class Peer extends EventEmitter { this._socket.on('data', this._onSocketData.bind(this)) this._socket.on('error', (err: Error) => this.emit('error', err)) this._socket.once('close', this._onSocketClose.bind(this)) - this._logger = isTruthy(this._socket.remoteAddress) - ? devp2pDebug.extend(this._socket.remoteAddress).extend(DEBUG_BASE_NAME) - : devp2pDebug.extend(DEBUG_BASE_NAME) + this._logger = + this._socket.remoteAddress !== undefined + ? devp2pDebug.extend(this._socket.remoteAddress).extend(DEBUG_BASE_NAME) + : devp2pDebug.extend(DEBUG_BASE_NAME) this._connected = false this._closed = false this._disconnectWe = null @@ -166,7 +167,7 @@ export class Peer extends EventEmitter { this._logger( `Send auth (EIP8: ${this._EIP8}) to ${this._socket.remoteAddress}:${this._socket.remotePort}` ) - if (isTruthy(this._EIP8)) { + if (this._EIP8 === true) { const authEIP8 = this._eciesSession.createAuthEIP8() if (!authEIP8) return this._socket.write(authEIP8) @@ -284,11 +285,7 @@ export class Peer extends EventEmitter { const debugMsg = `Send PING to ${this._socket.remoteAddress}:${this._socket.remotePort}` this.debug('PING', debugMsg) let data = Buffer.from(RLP.encode([])) - if ( - isTruthy(this._hello) && - isTruthy(this._hello.protocolVersion) && - this._hello.protocolVersion >= 5 - ) { + if (this._hello !== null && this._hello.protocolVersion >= 5) { data = snappy.compress(data) } @@ -308,11 +305,7 @@ export class Peer extends EventEmitter { this.debug('PONG', debugMsg) let data = Buffer.from(RLP.encode([])) - if ( - isTruthy(this._hello) && - isTruthy(this._hello.protocolVersion) && - this._hello.protocolVersion >= 5 - ) { + if (this._hello !== null && this._hello.protocolVersion >= 5) { data = snappy.compress(data) } this._sendMessage(PREFIXES.PONG, data) @@ -397,7 +390,7 @@ export class Peer extends EventEmitter { return this.disconnect(DISCONNECT_REASONS.INVALID_IDENTITY) } - if (isTruthy(this._remoteClientIdFilter)) { + if (this._remoteClientIdFilter !== undefined) { for (const filterStr of this._remoteClientIdFilter) { if (this._hello.clientId.toLowerCase().includes(filterStr.toLowerCase())) { return this.disconnect(DISCONNECT_REASONS.USELESS_PEER) @@ -409,7 +402,7 @@ export class Peer extends EventEmitter { for (const item of this._hello.capabilities) { for (const obj of this._capabilities!) { if (obj.name !== item.name || obj.version !== item.version) continue - if (isTruthy(shared[obj.name]) && shared[obj.name].version > obj.version) continue + if (shared[obj.name] !== undefined && shared[obj.name].version > obj.version) continue shared[obj.name] = obj } } @@ -509,7 +502,7 @@ export class Peer extends EventEmitter { const parseData = this._socketData.slice(0, bytesCount) this._logger(`Received header ${this._socket.remoteAddress}:${this._socket.remotePort}`) const size = this._eciesSession.parseHeader(parseData) - if (isFalsy(size)) { + if (size === undefined) { this._logger('invalid header size!') return } @@ -569,11 +562,7 @@ export class Peer extends EventEmitter { // Use snappy uncompression if peer supports DevP2P >=v5 let compressed = false const origPayload = payload - if ( - isTruthy(this._hello) && - isTruthy(this._hello.protocolVersion) && - this._hello?.protocolVersion >= 5 - ) { + if (this._hello !== null && this._hello.protocolVersion >= 5) { payload = snappy.uncompress(payload) compressed = true } @@ -702,7 +691,7 @@ export class Peer extends EventEmitter { */ _addFirstPeerDebugger() { const ip = this._socket.remoteAddress - if (isTruthy(ip)) { + if (typeof ip === 'string') { this._logger = devp2pDebug.extend(ip).extend(`FIRST_PEER`).extend(DEBUG_BASE_NAME) } } @@ -715,7 +704,7 @@ export class Peer extends EventEmitter { * @param disconnectReason Capitalized disconnect reason (e.g. 'TIMEOUT') */ private debug(messageName: string, msg: string, disconnectReason?: string) { - if (isTruthy(disconnectReason)) { + if (disconnectReason !== undefined) { this._logger.extend(messageName).extend(disconnectReason)(msg) } else { this._logger.extend(messageName)(msg) diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index 6188967475..7a5eae9136 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -1,4 +1,3 @@ -import { isFalsy, isTruthy } from '@ethereumjs/util' import { debug as createDebugLogger } from 'debug' import { getPublicKey } from 'ethereum-cryptography/secp256k1' import { EventEmitter } from 'events' @@ -79,7 +78,7 @@ export class RLPx extends EventEmitter { this._dpt = options.dpt ?? null if (this._dpt !== null) { this._dpt.on('peer:new', (peer: PeerInfo) => { - if (isFalsy(peer.tcpPort)) { + if (peer.tcpPort === null || peer.tcpPort === undefined) { this._dpt!.banPeer(peer, ms('5m')) this._debug(`banning peer with missing tcp port: ${peer.address}`) return @@ -108,9 +107,10 @@ export class RLPx extends EventEmitter { this._server.on('error', (err) => this.emit('error', err)) this._server.on('connection', (socket) => this._onConnect(socket, null)) const serverAddress = this._server.address() - this._debug = isTruthy(serverAddress) - ? devp2pDebug.extend(DEBUG_BASE_NAME).extend(serverAddress as string) - : devp2pDebug.extend(DEBUG_BASE_NAME) + this._debug = + serverAddress !== null + ? devp2pDebug.extend(DEBUG_BASE_NAME).extend(serverAddress as string) + : devp2pDebug.extend(DEBUG_BASE_NAME) this._peers = new Map() this._peersQueue = [] this._peersLRU = new LRUCache({ max: 25000 }) @@ -139,7 +139,7 @@ export class RLPx extends EventEmitter { } async connect(peer: PeerInfo) { - if (isFalsy(peer.tcpPort) || isFalsy(peer.address)) return + if (peer.tcpPort === undefined || peer.tcpPort === null || peer.address === undefined) return this._isAliveCheck() if (!Buffer.isBuffer(peer.id)) throw new TypeError('Expected peer.id as Buffer') @@ -249,14 +249,14 @@ export class RLPx extends EventEmitter { }) peer.once('close', (reason, disconnectWe) => { - if (isTruthy(disconnectWe)) { + if (disconnectWe === true) { this._debug( `disconnect from ${socket.remoteAddress}:${socket.remotePort}, reason: ${DISCONNECT_REASONS[reason]}`, `disconnect` ) } - if (isFalsy(disconnectWe) && reason === DISCONNECT_REASONS.TOO_MANY_PEERS) { + if (disconnectWe !== true && reason === DISCONNECT_REASONS.TOO_MANY_PEERS) { // hack if (this._getOpenQueueSlots() > 0) { this._peersQueue.push({ diff --git a/packages/devp2p/src/util.ts b/packages/devp2p/src/util.ts index 4f6a419c6c..de3f94761d 100644 --- a/packages/devp2p/src/util.ts +++ b/packages/devp2p/src/util.ts @@ -1,5 +1,5 @@ import { RLP } from '@ethereumjs/rlp' -import { arrToBufArr, isTruthy } from '@ethereumjs/util' +import { arrToBufArr } from '@ethereumjs/util' import { debug as createDebugLogger } from 'debug' import { keccak256 as _keccak256 } from 'ethereum-cryptography/keccak' import { utils } from 'ethereum-cryptography/secp256k1' @@ -76,7 +76,7 @@ export function assertEq( if (expected.equals(actual)) return fullMsg = `${msg}: ${expected.toString('hex')} / ${actual.toString('hex')}` const debugMsg = `[ERROR] ${fullMsg}` - if (isTruthy(messageName)) { + if (messageName !== undefined) { debug(messageName, debugMsg) } else { debug(debugMsg) @@ -86,7 +86,7 @@ export function assertEq( if (expected === actual) return fullMsg = `${msg}: ${expected} / ${actual}` - if (isTruthy(messageName)) { + if (messageName !== undefined) { debug(messageName, fullMsg) } else { debug(fullMsg) diff --git a/packages/devp2p/test/integration/util.ts b/packages/devp2p/test/integration/util.ts index bcab807d71..5d4ea3b86b 100644 --- a/packages/devp2p/test/integration/util.ts +++ b/packages/devp2p/test/integration/util.ts @@ -1,5 +1,4 @@ import { Chain, Common, Hardfork } from '@ethereumjs/common' -import { isTruthy } from '@ethereumjs/util' import { DPT, ETH, RLPx, genPrivateKey } from '../../src' import * as testdata from '../testdata.json' @@ -127,13 +126,13 @@ export function twoPeerMsgExchange( protocol.sendStatus(opts.status0) // (1 ->) protocol.once('status', () => { - if (isTruthy(opts.onOnceStatus0)) opts.onOnceStatus0(rlpxs, protocol) + if (opts.onOnceStatus0 !== undefined) opts.onOnceStatus0(rlpxs, protocol) }) // (-> 2) protocol.on('message', async (code: any, payload: any) => { - if (isTruthy(opts.onOnMsg0)) opts.onOnMsg0(rlpxs, protocol, code, payload) + if (opts.onOnMsg0 !== undefined) opts.onOnMsg0(rlpxs, protocol, code, payload) }) peer.on('error', (err: Error) => { - if (isTruthy(opts.onPeerError0)) { + if (opts.onPeerError0 !== undefined) { opts.onPeerError0(err, rlpxs) } else { t.fail(`Unexpected peer 0 error: ${err}`) @@ -152,10 +151,10 @@ export function twoPeerMsgExchange( protocol.sendStatus(opts.status1) // (2 ->) break } - if (isTruthy(opts.onOnMsg1)) opts.onOnMsg1(rlpxs, protocol, code, payload) + if (opts.onOnMsg1 !== undefined) opts.onOnMsg1(rlpxs, protocol, code, payload) }) peer.on('error', (err: any) => { - if (isTruthy(opts.onPeerError1)) { + if (opts.onPeerError1 !== undefined) { opts.onPeerError1(err, rlpxs) } else { t.fail(`Unexpected peer 1 error: ${err}`) @@ -244,7 +243,7 @@ export function twoPeerMsgExchange3( opts.receiveMessage(rlpxs, protocol, code, payload) }) peer.on('error', (err: any) => { - if (isTruthy(opts.onPeerError1)) { + if (opts.onPeerError1 !== false) { opts.onPeerError1(err, rlpxs) } else { t.fail(`Unexpected peer 1 error: ${err}`)