Skip to content

Commit

Permalink
devp2p: add DEBUG everywhere, except util.ts (#3165)
Browse files Browse the repository at this point in the history
  • Loading branch information
jochem-brouwer authored Nov 27, 2023
1 parent 0170906 commit c185241
Show file tree
Hide file tree
Showing 8 changed files with 227 additions and 126 deletions.
13 changes: 11 additions & 2 deletions packages/devp2p/src/dns/dns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,17 @@ export class DNS {
protected _DNSTreeCache: { [key: string]: string }
protected readonly _errorTolerance: number = 10

private DEBUG: boolean

constructor(options: DNSOptions = {}) {
this._DNSTreeCache = {}

if (typeof options.dnsServerAddress === 'string') {
dns.setServers([options.dnsServerAddress])
}

this.DEBUG =
typeof window === 'undefined' ? process?.env?.DEBUG?.includes('ethjs') ?? false : false
}

/**
Expand Down Expand Up @@ -60,7 +65,9 @@ export class DNS {

if (this._isNewPeer(peer, peers)) {
peers.push(peer)
debug(`got new peer candidate from DNS address=${peer.address}`)
if (this.DEBUG) {
debug(`got new peer candidate from DNS address=${peer.address}`)
}
}

totalSearches++
Expand Down Expand Up @@ -98,7 +105,9 @@ export class DNS {
return null
}
} catch (error: any) {
debug(`Errored searching DNS tree at subdomain ${subdomain}: ${error}`)
if (this.DEBUG) {
debug(`Errored searching DNS tree at subdomain ${subdomain}: ${error}`)
}
return null
}
}
Expand Down
7 changes: 6 additions & 1 deletion packages/devp2p/src/dpt/ban-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,19 @@ const verbose = createDebugLogger('verbose').enabled

export class BanList {
private _lru: LRUCache<string, boolean>
private DEBUG: boolean
constructor() {
this._lru = new LRU({ max: 10000 })
this.DEBUG =
typeof window === 'undefined' ? process?.env?.DEBUG?.includes('ethjs') ?? false : false
}

add(obj: string | Uint8Array | PeerInfo, maxAge?: number) {
for (const key of KBucket.getKeys(obj)) {
this._lru.set(key, true, { ttl: maxAge })
debug(`Added peer ${formatLogId(key, verbose)}, size: ${this._lru.size}`)
if (this.DEBUG) {
debug(`Added peer ${formatLogId(key, verbose)}, size: ${this._lru.size}`)
}
}
}

Expand Down
29 changes: 20 additions & 9 deletions packages/devp2p/src/dpt/dpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ export class DPT {
protected _onlyConfirmed: boolean
protected _confirmedPeers: Set<string>

private DEBUG: boolean

constructor(privateKey: Uint8Array, options: DPTOptions) {
this.events = new EventEmitter()
this._privateKey = privateKey
Expand Down Expand Up @@ -76,6 +78,9 @@ export class DPT {
// By default calls refresh every 3s
const refreshIntervalSubdivided = Math.floor((options.refreshInterval ?? 60000) / 10) // 60 sec * 1000
this._refreshIntervalId = setInterval(() => this.refresh(), refreshIntervalSubdivided)

this.DEBUG =
typeof window === 'undefined' ? process?.env?.DEBUG?.includes('ethjs') ?? false : false
}

bind(...args: any[]): void {
Expand Down Expand Up @@ -139,7 +144,9 @@ export class DPT {

async addPeer(obj: PeerInfo): Promise<PeerInfo> {
if (this._banlist.has(obj)) throw new Error('Peer is banned')
this._debug(`attempt adding peer ${obj.address}:${obj.udpPort}`)
if (this.DEBUG) {
this._debug(`attempt adding peer ${obj.address}:${obj.udpPort}`)
}

// check k-bucket first
const peer = this._kbucket.get(obj)
Expand Down Expand Up @@ -216,9 +223,11 @@ export class DPT {
this._refreshIntervalSelectionCounter = (this._refreshIntervalSelectionCounter + 1) % 10

const peers = this.getPeers()
this._debug(
`call .refresh() (selector ${this._refreshIntervalSelectionCounter}) (${peers.length} peers in table)`
)
if (this.DEBUG) {
this._debug(
`call .refresh() (selector ${this._refreshIntervalSelectionCounter}) (${peers.length} peers in table)`
)
}

for (const peer of peers) {
// Randomly distributed selector based on peer ID
Expand All @@ -240,11 +249,13 @@ export class DPT {
if (this._shouldGetDnsPeers) {
const dnsPeers = await this.getDnsPeers()

this._debug(
`.refresh() Adding ${dnsPeers.length} from DNS tree, (${
this.getPeers().length
} current peers in table)`
)
if (this.DEBUG) {
this._debug(
`.refresh() Adding ${dnsPeers.length} from DNS tree, (${
this.getPeers().length
} current peers in table)`
)
}

this._addPeerBatch(dnsPeers)
}
Expand Down
55 changes: 35 additions & 20 deletions packages/devp2p/src/dpt/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export class Server {
protected _socket: DgramSocket | null
private _debug: Debugger

private DEBUG: boolean

constructor(dpt: DPT, privateKey: Uint8Array, options: DPTServerOptions) {
this.events = new EventEmitter()
this._dpt = dpt
Expand All @@ -57,18 +59,25 @@ export class Server {
}
})
}

this.DEBUG =
typeof window === 'undefined' ? process?.env?.DEBUG?.includes('ethjs') ?? false : false
}

bind(...args: any[]) {
this._isAliveCheck()
this._debug('call .bind')
if (this.DEBUG) {
this._debug('call .bind')
}

if (this._socket) this._socket.bind(...args)
}

destroy(...args: any[]) {
this._isAliveCheck()
this._debug('call .destroy')
if (this.DEBUG) {
this._debug('call .destroy')
}

if (this._socket) {
this._socket.close(...args)
Expand Down Expand Up @@ -96,11 +105,13 @@ export class Server {
deferred,
timeoutId: setTimeout(() => {
if (this._requests.get(rkey) !== undefined) {
this._debug(
`ping timeout: ${peer.address}:${peer.udpPort} ${
peer.id ? formatLogId(bytesToHex(peer.id), verbose) : '-'
}`
)
if (this.DEBUG) {
this._debug(
`ping timeout: ${peer.address}:${peer.udpPort} ${
peer.id ? formatLogId(bytesToHex(peer.id), verbose) : '-'
}`
)
}
this._requests.delete(rkey)
deferred.reject(new Error(`Timeout error: ping ${peer.address}:${peer.udpPort}`))
} else {
Expand All @@ -122,12 +133,14 @@ export class Server {
}

_send(peer: PeerInfo, typename: string, data: any) {
this.debug(
typename,
`send ${typename} to ${peer.address}:${peer.udpPort} (peerId: ${
peer.id ? formatLogId(bytesToHex(peer.id), verbose) : '-'
})`
)
if (this.DEBUG) {
this.debug(
typename,
`send ${typename} to ${peer.address}:${peer.udpPort} (peerId: ${
peer.id ? formatLogId(bytesToHex(peer.id), verbose) : '-'
})`
)
}

const msg = encode(typename, data, this._privateKey)

Expand All @@ -139,13 +152,15 @@ export class Server {
_handler(msg: Uint8Array, rinfo: RemoteInfo) {
const info = decode(msg) // Dgram serializes everything to `Uint8Array`
const peerId = pk2id(info.publicKey)
this.debug(
info.typename.toString(),
`received ${info.typename} from ${rinfo.address}:${rinfo.port} (peerId: ${formatLogId(
bytesToHex(peerId),
verbose
)})`
)
if (this.DEBUG) {
this.debug(
info.typename.toString(),
`received ${info.typename} from ${rinfo.address}:${rinfo.port} (peerId: ${formatLogId(
bytesToHex(peerId),
verbose
)})`
)
}

// add peer if not in our table
const peer = this._dpt.getPeer(peerId)
Expand Down
74 changes: 44 additions & 30 deletions packages/devp2p/src/protocol/les.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,17 @@ export class LES extends Protocol {
protected _status: LES.Status | null = null
protected _peerStatus: LES.Status | null = null

private DEBUG: boolean

constructor(version: number, peer: Peer, send: SendMethod) {
super(peer, send, ProtocolType.LES, version, LES.MESSAGE_CODES)

this._statusTimeoutId = setTimeout(() => {
this._peer.disconnect(DISCONNECT_REASON.TIMEOUT)
}, 5000) // 5 sec * 1000

this.DEBUG =
typeof window === 'undefined' ? process?.env?.DEBUG?.includes('ethjs') ?? false : false
}

static les2 = { name: 'les', version: 2, length: 21, constructor: LES }
Expand All @@ -40,14 +45,17 @@ export class LES extends Protocol {
const payload = RLP.decode(data)
if (code !== LES.MESSAGE_CODES.STATUS) {
const logData = formatLogData(bytesToHex(data as Uint8Array), this._verbose)
this.debug(
this.getMsgPrefix(code),
// @ts-ignore
`${`Received ${this.getMsgPrefix(code)} message from ${this._peer._socket.remoteAddress}:${
// @ts-ignore
this._peer._socket.remotePort
}`}: ${logData}`
)
if (this.DEBUG) {
this.debug(
this.getMsgPrefix(code),
`${`Received ${this.getMsgPrefix(code)} message from ${
(<any>this._peer)._socket.remoteAddress
}:${
// @ts-ignore
this._peer._socket.remotePort
}`}: ${logData}`
)
}
}
switch (code) {
case LES.MESSAGE_CODES.STATUS: {
Expand All @@ -63,14 +71,16 @@ export class LES extends Protocol {
status[bytesToUtf8(value[0] as Uint8Array)] = value[1]
}
this._peerStatus = status
this.debug(
this.getMsgPrefix(code),
`${`Received ${this.getMsgPrefix(code)} message from ${
// @ts-ignore
this._peer._socket.remoteAddress
// @ts-ignore
}:${this._peer._socket.remotePort}`}: ${this._getStatusString(this._peerStatus)}`
)
if (this.DEBUG) {
this.debug(
this.getMsgPrefix(code),
`${`Received ${this.getMsgPrefix(code)} message from ${
// @ts-ignore
this._peer._socket.remoteAddress
// @ts-ignore
}:${this._peer._socket.remotePort}`}: ${this._getStatusString(this._peerStatus)}`
)
}
this._handleStatus()
break
}
Expand Down Expand Up @@ -188,14 +198,16 @@ export class LES extends Protocol {
statusList.push([utf8ToBytes(key), status[key]])
}

this.debug(
'STATUS',
// @ts-ignore
`Send STATUS message to ${this._peer._socket.remoteAddress}:${
if (this.DEBUG) {
this.debug(
'STATUS',
// @ts-ignore
this._peer._socket.remotePort
} (les${this._version}): ${this._getStatusString(this._status)}`
)
`Send STATUS message to ${this._peer._socket.remoteAddress}:${
// @ts-ignore
this._peer._socket.remotePort
} (les${this._version}): ${this._getStatusString(this._status)}`
)
}

let payload = RLP.encode(statusList)

Expand All @@ -215,14 +227,16 @@ export class LES extends Protocol {
* @param payload Payload (including reqId, e.g. `[1, [437000, 1, 0, 0]]`)
*/
sendMessage(code: LES.MESSAGE_CODES, payload: Input) {
this.debug(
this.getMsgPrefix(code),
// @ts-ignore
`Send ${this.getMsgPrefix(code)} message to ${this._peer._socket.remoteAddress}:${
if (this.DEBUG) {
this.debug(
this.getMsgPrefix(code),
// @ts-ignore
this._peer._socket.remotePort
}: ${formatLogData(bytesToHex(RLP.encode(payload)), this._verbose)}`
)
`Send ${this.getMsgPrefix(code)} message to ${this._peer._socket.remoteAddress}:${
// @ts-ignore
this._peer._socket.remotePort
}: ${formatLogData(bytesToHex(RLP.encode(payload)), this._verbose)}`
)
}

switch (code) {
case LES.MESSAGE_CODES.STATUS:
Expand Down
Loading

0 comments on commit c185241

Please sign in to comment.