From 3437b24c6f6a9e971a06c665ea33f3e04fa3e924 Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 13 Jul 2023 13:49:44 -0700 Subject: [PATCH 01/23] Change access specifiers for RLPx _privateKey, _id, _debug, _timeout --- packages/client/src/net/server/rlpxserver.ts | 2 +- packages/devp2p/src/rlpx/rlpx.ts | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/client/src/net/server/rlpxserver.ts b/packages/client/src/net/server/rlpxserver.ts index d700c95366..5b1d675990 100644 --- a/packages/client/src/net/server/rlpxserver.ts +++ b/packages/client/src/net/server/rlpxserver.ts @@ -105,7 +105,7 @@ export class RlpxServer extends Server { ports: { discovery: this.config.port, listener: this.config.port }, } } - const id = bytesToUnprefixedHex(this.rlpx._id) + const id = bytesToUnprefixedHex(this.rlpx.id) return { enode: `enode://${id}@${listenAddr}`, id, diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index 5964d0a1b3..ecbc187cea 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -31,10 +31,10 @@ const DEBUG_BASE_NAME = 'rlpx' const verbose = createDebugLogger('verbose').enabled export class RLPx extends EventEmitter { - _privateKey: Uint8Array - _id: Uint8Array - _debug: Debugger - _timeout: number + protected _privateKey: Uint8Array + public readonly id: Uint8Array + private _debug: Debugger + protected _timeout: number _maxPeers: number _clientId: Uint8Array _remoteClientIdFilter?: string[] @@ -55,7 +55,7 @@ export class RLPx extends EventEmitter { super() this._privateKey = privateKey - this._id = pk2id(secp256k1.getPublicKey(this._privateKey, false)) + this.id = pk2id(secp256k1.getPublicKey(this._privateKey, false)) // options this._timeout = options.timeout ?? 10000 // 10 sec * 1000 @@ -205,7 +205,7 @@ export class RLPx extends EventEmitter { socket, remoteId: peerId!, privateKey: this._privateKey, - id: this._id, + id: this.id, timeout: this._timeout, clientId: this._clientId, remoteClientIdFilter: this._remoteClientIdFilter, @@ -232,7 +232,7 @@ export class RLPx extends EventEmitter { } this._debug(msg) const id = peer.getId() - if (id && equalsBytes(id, this._id)) { + if (id && equalsBytes(id, this.id)) { return peer.disconnect(DISCONNECT_REASON.SAME_IDENTITY) } From d6e994e42ca8306984d10c598a3d6a364e43c760 Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 13 Jul 2023 14:00:23 -0700 Subject: [PATCH 02/23] Renaming accessed id property in client tests --- packages/client/test/net/server/rlpxserver.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/client/test/net/server/rlpxserver.spec.ts b/packages/client/test/net/server/rlpxserver.spec.ts index 622f4595fe..8e61f40334 100644 --- a/packages/client/test/net/server/rlpxserver.spec.ts +++ b/packages/client/test/net/server/rlpxserver.spec.ts @@ -128,7 +128,7 @@ tape('[RlpxServer]', async (t) => { ;(server as any).rlpx = td.object({ destroy: td.func(), }) - server.rlpx!._id = hexToBytes('0x' + mockId) + server.rlpx!.id = hexToBytes('0x' + mockId) td.when( server.dpt!.bootstrap({ address: '10.0.0.1', udpPort: 1234, tcpPort: 1234 }) ).thenResolve(undefined) @@ -172,7 +172,7 @@ tape('[RlpxServer]', async (t) => { ;(server as any).rlpx = td.object({ destroy: td.func(), }) - server.rlpx!._id = hexToBytes('0x' + mockId) + server.rlpx!.id = hexToBytes('0x' + mockId) td.when( server.dpt!.bootstrap({ address: '10.0.0.1', udpPort: 1234, tcpPort: 1234 }) ).thenResolve(undefined) @@ -261,7 +261,7 @@ tape('[RlpxServer]', async (t) => { ;(server as any).peers.set('01', { id: '01' } as any) server.rlpx!.emit('peer:removed', rlpxPeer) server.rlpx!.emit('peer:error', rlpxPeer, new Error('err0')) - server.rlpx!._id = hexToBytes('0xff') + server.rlpx!.id = hexToBytes('0xff') server.rlpx!.emit('listening') }) From edd692ac8a055c01b9879a8f14efe6c02a1552fc Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 13 Jul 2023 14:13:26 -0700 Subject: [PATCH 03/23] Change access specifiers for RLPx _maxPeers, _clientId, _remoteClientIdFilter, and _capabilities --- packages/devp2p/src/rlpx/rlpx.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index ecbc187cea..96ea7b5e85 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -35,10 +35,10 @@ export class RLPx extends EventEmitter { public readonly id: Uint8Array private _debug: Debugger protected _timeout: number - _maxPeers: number - _clientId: Uint8Array - _remoteClientIdFilter?: string[] - _capabilities: Capabilities[] + protected _maxPeers: number + protected _clientId: Uint8Array + protected _remoteClientIdFilter?: string[] + protected _capabilities: Capabilities[] _common: Common _listenPort: number | null _dpt: DPT | null From 640f52b5042d7d38118d84a9479e9d744440f5fd Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 13 Jul 2023 14:21:32 -0700 Subject: [PATCH 04/23] Ignore error message from reassigning readonly property in tests --- packages/client/test/net/server/rlpxserver.spec.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/client/test/net/server/rlpxserver.spec.ts b/packages/client/test/net/server/rlpxserver.spec.ts index 8e61f40334..905eaaa3dd 100644 --- a/packages/client/test/net/server/rlpxserver.spec.ts +++ b/packages/client/test/net/server/rlpxserver.spec.ts @@ -128,6 +128,8 @@ tape('[RlpxServer]', async (t) => { ;(server as any).rlpx = td.object({ destroy: td.func(), }) + + // @ts-ignore server.rlpx!.id = hexToBytes('0x' + mockId) td.when( server.dpt!.bootstrap({ address: '10.0.0.1', udpPort: 1234, tcpPort: 1234 }) @@ -172,6 +174,8 @@ tape('[RlpxServer]', async (t) => { ;(server as any).rlpx = td.object({ destroy: td.func(), }) + + // @ts-ignore server.rlpx!.id = hexToBytes('0x' + mockId) td.when( server.dpt!.bootstrap({ address: '10.0.0.1', udpPort: 1234, tcpPort: 1234 }) @@ -261,6 +265,8 @@ tape('[RlpxServer]', async (t) => { ;(server as any).peers.set('01', { id: '01' } as any) server.rlpx!.emit('peer:removed', rlpxPeer) server.rlpx!.emit('peer:error', rlpxPeer, new Error('err0')) + + // @ts-ignore server.rlpx!.id = hexToBytes('0xff') server.rlpx!.emit('listening') }) From 1b9f734b0b82b2feb2b8e8e49b0e1d24cdaad5a2 Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 13 Jul 2023 14:23:47 -0700 Subject: [PATCH 05/23] Change access specifiers for _common, _listenPort, and _dpt --- packages/devp2p/src/rlpx/rlpx.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index 96ea7b5e85..356fceab21 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -39,9 +39,9 @@ export class RLPx extends EventEmitter { protected _clientId: Uint8Array protected _remoteClientIdFilter?: string[] protected _capabilities: Capabilities[] - _common: Common - _listenPort: number | null - _dpt: DPT | null + protected _common: Common + protected _listenPort: number | null + protected _dpt: DPT | null _peersLRU: LRUCache _peersQueue: { peer: PeerInfo; ts: number }[] From be2d41d289f39998eb71e826c2dbdbbe9c028dc7 Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 13 Jul 2023 14:37:39 -0700 Subject: [PATCH 06/23] Change access specifiers for _peersLRU, _peersQueue, _server, _peers, _refillIntervalId, and _refillIntervalSelectionCounter --- packages/devp2p/src/rlpx/rlpx.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index 356fceab21..a125588699 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -43,13 +43,13 @@ export class RLPx extends EventEmitter { protected _listenPort: number | null protected _dpt: DPT | null - _peersLRU: LRUCache - _peersQueue: { peer: PeerInfo; ts: number }[] - _server: net.Server | null - _peers: Map + protected _peersLRU: LRUCache + protected _peersQueue: { peer: PeerInfo; ts: number }[] + protected _server: net.Server | null + protected _peers: Map - _refillIntervalId: NodeJS.Timeout - _refillIntervalSelectionCounter: number = 0 + protected _refillIntervalId: NodeJS.Timeout + protected _refillIntervalSelectionCounter: number = 0 constructor(privateKey: Uint8Array, options: RLPxOptions) { super() From abcd71bae70a9e31cbece215d29c17aa3f31742e Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 10:06:47 -0700 Subject: [PATCH 07/23] Ignore accessibility errors in examples --- packages/devp2p/examples/peer-communication-les.cts | 4 ++++ packages/devp2p/examples/peer-communication.cts | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/packages/devp2p/examples/peer-communication-les.cts b/packages/devp2p/examples/peer-communication-les.cts index 7d20dafea8..1a8ae50a25 100644 --- a/packages/devp2p/examples/peer-communication-les.cts +++ b/packages/devp2p/examples/peer-communication-les.cts @@ -220,7 +220,11 @@ async function isValidBlock(block: Block) { setInterval(() => { const peersCount = dpt.getPeers().length const openSlots = rlpx._getOpenSlots() + + // @ts-ignore const queueLength = rlpx._peersQueue.length + + // @ts-ignore const queueLength2 = rlpx._peersQueue.filter((o) => o.ts <= Date.now()).length console.log( diff --git a/packages/devp2p/examples/peer-communication.cts b/packages/devp2p/examples/peer-communication.cts index 199780009a..e1906a6157 100644 --- a/packages/devp2p/examples/peer-communication.cts +++ b/packages/devp2p/examples/peer-communication.cts @@ -371,7 +371,11 @@ async function isValidBlock(block: Block) { setInterval(() => { const peersCount = dpt.getPeers().length const openSlots = rlpx._getOpenSlots() + + // @ts-ignore const queueLength = rlpx._peersQueue.length + + // @ts-ignore const queueLength2 = rlpx._peersQueue.filter((o) => o.ts <= Date.now()).length console.log( From 666e077cb93469f0949811b237e07e6fe8860ed9 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 10:17:43 -0700 Subject: [PATCH 08/23] Update names and access specifiers of Peer fields --- packages/devp2p/src/rlpx/peer.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/devp2p/src/rlpx/peer.ts b/packages/devp2p/src/rlpx/peer.ts index 05a3be6e52..b8d32584e5 100644 --- a/packages/devp2p/src/rlpx/peer.ts +++ b/packages/devp2p/src/rlpx/peer.ts @@ -64,16 +64,16 @@ interface Hello { } export class Peer extends EventEmitter { - _clientId: Uint8Array - _capabilities?: Capabilities[] - _common: Common - _port: number - _id: Uint8Array - _remoteClientIdFilter?: string[] - _remoteId: Uint8Array - _EIP8: Uint8Array | boolean - _eciesSession: ECIES - _state: string + protected readonly _clientId: Uint8Array + protected _capabilities?: Capabilities[] + public common: Common + protected _port: number + protected readonly _id: Uint8Array + protected _remoteClientIdFilter?: string[] + protected _remoteId: Uint8Array + protected _EIP8: Uint8Array | boolean + protected _eciesSession: ECIES + protected _state: string _weHello: HelloMsg | null _hello: Hello | null _nextPacketSize: number @@ -100,7 +100,7 @@ export class Peer extends EventEmitter { // hello data this._clientId = options.clientId this._capabilities = options.capabilities - this._common = options.common + this.common = options.common this._port = options.port this._id = options.id this._remoteClientIdFilter = options.remoteClientIdFilter From 29849e960cb97d526259279e2bfaf000c748c515 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 10:18:06 -0700 Subject: [PATCH 09/23] Ignore access errors for _eciesSession --- packages/devp2p/src/rlpx/rlpx.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index a125588699..10e8ef28fb 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -224,9 +224,13 @@ export class RLPx extends EventEmitter { peer.once('connect', () => { let msg = `handshake with ${socket.remoteAddress}:${socket.remotePort} was successful` + + // @ts-ignore if (peer._eciesSession._gotEIP8Auth === true) { msg += ` (peer eip8 auth)` } + + // @ts-ignore if (peer._eciesSession._gotEIP8Ack === true) { msg += ` (peer eip8 ack)` } From 991397cffa6c09c8557abffbeb5ea23748bcb91a Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 10:18:28 -0700 Subject: [PATCH 10/23] Make common field public for Peer class --- packages/devp2p/src/protocol/eth.ts | 6 +++--- packages/devp2p/src/protocol/les.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/devp2p/src/protocol/eth.ts b/packages/devp2p/src/protocol/eth.ts index a87b596e39..bb086c7566 100644 --- a/packages/devp2p/src/protocol/eth.ts +++ b/packages/devp2p/src/protocol/eth.ts @@ -35,7 +35,7 @@ export class ETH extends Protocol { // Set forkHash and nextForkBlock if (this._version >= 64) { - const c = this._peer._common + const c = this._peer.common 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 @@ -127,7 +127,7 @@ export class ETH extends Protocol { * @param forkId Remote fork ID */ _validateForkId(forkId: Uint8Array[]) { - const c = this._peer._common + const c = this._peer.common const peerForkHash = bytesToHex(forkId[0]) const peerNextFork = bytesToBigInt(forkId[1]) @@ -263,7 +263,7 @@ export class ETH extends Protocol { if (this._status !== null) return this._status = [ intToBytes(this._version), - bigIntToBytes(this._peer._common.chainId()), + bigIntToBytes(this._peer.common.chainId()), status.td, status.bestHash, status.genesisHash, diff --git a/packages/devp2p/src/protocol/les.ts b/packages/devp2p/src/protocol/les.ts index 64a3f69a63..106a113f0b 100644 --- a/packages/devp2p/src/protocol/les.ts +++ b/packages/devp2p/src/protocol/les.ts @@ -175,7 +175,7 @@ export class LES extends Protocol { status['announceType'] = intToBytes(DEFAULT_ANNOUNCE_TYPE) } status['protocolVersion'] = intToBytes(this._version) - status['networkId'] = bigIntToBytes(this._peer._common.chainId()) + status['networkId'] = bigIntToBytes(this._peer.common.chainId()) this._status = status From b623ef098bc6a52690c277293dae2c97452046ed Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 10:58:14 -0700 Subject: [PATCH 11/23] Update names and access specifiers of Peer fields --- packages/client/src/net/server/rlpxserver.ts | 2 + packages/devp2p/src/protocol/eth.ts | 10 ++++- packages/devp2p/src/protocol/les.ts | 10 +++++ packages/devp2p/src/protocol/protocol.ts | 4 ++ packages/devp2p/src/protocol/snap.ts | 5 +++ packages/devp2p/src/rlpx/peer.ts | 42 ++++++++++---------- packages/devp2p/src/rlpx/rlpx.ts | 2 + 7 files changed, 53 insertions(+), 22 deletions(-) diff --git a/packages/client/src/net/server/rlpxserver.ts b/packages/client/src/net/server/rlpxserver.ts index 5b1d675990..cfd1added0 100644 --- a/packages/client/src/net/server/rlpxserver.ts +++ b/packages/client/src/net/server/rlpxserver.ts @@ -254,7 +254,9 @@ export class RlpxServer extends Server { let peer: RlpxPeer | null = new RlpxPeer({ config: this.config, id: bytesToUnprefixedHex(rlpxPeer.getId()!), + // @ts-ignore host: rlpxPeer._socket.remoteAddress!, + // @ts-ignore port: rlpxPeer._socket.remotePort!, protocols: Array.from(this.protocols), // @ts-ignore: Property 'server' does not exist on type 'Socket'. diff --git a/packages/devp2p/src/protocol/eth.ts b/packages/devp2p/src/protocol/eth.ts index bb086c7566..2f6b8301b8 100644 --- a/packages/devp2p/src/protocol/eth.ts +++ b/packages/devp2p/src/protocol/eth.ts @@ -60,7 +60,9 @@ export class ETH extends Protocol { _handleMessage(code: ETH.MESSAGE_CODES, data: Uint8Array) { const payload = RLP.decode(data) const debugMsg = this.DEBUG - ? `Received ${this.getMsgPrefix(code)} message from ${this._peer._socket.remoteAddress}:${ + ? // @ts-ignore + `Received ${this.getMsgPrefix(code)} message from ${this._peer._socket.remoteAddress}:${ + // @ts-ignore this._peer._socket.remotePort }` : undefined @@ -289,7 +291,10 @@ export class ETH extends Protocol { if (this.DEBUG) { this.debug( 'STATUS', + + // @ts-ignore `Send STATUS message to ${this._peer._socket.remoteAddress}:${ + // @ts-ignore this._peer._socket.remotePort } (eth${this._version}): ${this._getStatusString(this._status)}` ) @@ -298,6 +303,7 @@ export class ETH extends Protocol { let payload = RLP.encode(this._status) // Use snappy compression if peer supports DevP2P >=v5 + // @ts-ignore if (this._peer._hello !== null && this._peer._hello.protocolVersion >= 5) { payload = snappy.compress(payload) } @@ -310,6 +316,7 @@ export class ETH extends Protocol { if (this.DEBUG) { const logData = formatLogData(bytesToHex(RLP.encode(payload)), this._verbose) const messageName = this.getMsgPrefix(code) + // @ts-ignore const debugMsg = `Send ${messageName} message to ${this._peer._socket.remoteAddress}:${this._peer._socket.remotePort}: ${logData}` this.debug(messageName, debugMsg) @@ -352,6 +359,7 @@ export class ETH extends Protocol { payload = RLP.encode(payload) // Use snappy compression if peer supports DevP2P >=v5 + // @ts-ignore 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 106a113f0b..a91c96eeaa 100644 --- a/packages/devp2p/src/protocol/les.ts +++ b/packages/devp2p/src/protocol/les.ts @@ -42,7 +42,9 @@ export class LES extends Protocol { 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}` ) @@ -64,7 +66,9 @@ export class LES extends Protocol { 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() @@ -186,7 +190,9 @@ export class LES extends Protocol { this.debug( 'STATUS', + // @ts-ignore `Send STATUS message to ${this._peer._socket.remoteAddress}:${ + // @ts-ignore this._peer._socket.remotePort } (les${this._version}): ${this._getStatusString(this._status)}` ) @@ -194,6 +200,7 @@ export class LES extends Protocol { let payload = RLP.encode(statusList) // Use snappy compression if peer supports DevP2P >=v5 + // @ts-ignore if (this._peer._hello !== null && this._peer._hello.protocolVersion >= 5) { payload = snappy.compress(payload) } @@ -210,7 +217,9 @@ export class LES extends Protocol { sendMessage(code: LES.MESSAGE_CODES, payload: Input) { this.debug( this.getMsgPrefix(code), + // @ts-ignore `Send ${this.getMsgPrefix(code)} message to ${this._peer._socket.remoteAddress}:${ + // @ts-ignore this._peer._socket.remotePort }: ${formatLogData(bytesToHex(RLP.encode(payload)), this._verbose)}` ) @@ -255,6 +264,7 @@ export class LES extends Protocol { payload = RLP.encode(payload) // Use snappy compression if peer supports DevP2P >=v5 + // @ts-ignore 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 1e05e94553..f52bef2ce2 100644 --- a/packages/devp2p/src/protocol/protocol.ts +++ b/packages/devp2p/src/protocol/protocol.ts @@ -63,6 +63,7 @@ export abstract class Protocol extends EventEmitter { } // Remote Peer IP logger + // @ts-ignore const ip = this._peer._socket.remoteAddress if (typeof ip === 'string') { this.msgDebuggers[ip] = devp2pDebug.extend(ip) @@ -76,6 +77,7 @@ export abstract class Protocol extends EventEmitter { * Can be used together with the `devp2p:FIRST_PEER` debugger. */ _addFirstPeerDebugger() { + // @ts-ignore const ip = this._peer._socket.remoteAddress if (typeof ip === 'string') { this.msgDebuggers[ip] = devp2pDebug.extend('FIRST_PEER') @@ -95,6 +97,8 @@ export abstract class Protocol extends EventEmitter { if (this.msgDebuggers[messageName] !== undefined) { this.msgDebuggers[messageName](msg) } + + // @ts-ignore const ip = this._peer._socket.remoteAddress 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 d88d7dfa4d..cdeb8ae7ce 100644 --- a/packages/devp2p/src/protocol/snap.ts +++ b/packages/devp2p/src/protocol/snap.ts @@ -23,7 +23,9 @@ export class SNAP extends Protocol { // Note, this needs optimization, see issue #1882 this.debug( this.getMsgPrefix(code), + // @ts-ignore `Received ${this.getMsgPrefix(code)} message from ${this._peer._socket.remoteAddress}:${ + // @ts-ignore this._peer._socket.remotePort }: ${formatLogData(bytesToHex(data), this._verbose)}` ) @@ -57,7 +59,9 @@ export class SNAP extends Protocol { sendMessage(code: SNAP.MESSAGE_CODES, payload: any) { this.debug( this.getMsgPrefix(code), + // @ts-ignore `Send ${this.getMsgPrefix(code)} message to ${this._peer._socket.remoteAddress}:${ + // @ts-ignore this._peer._socket.remotePort }: ${formatLogData(utils.bytesToHex(RLP.encode(payload)), this._verbose)}` ) @@ -79,6 +83,7 @@ export class SNAP extends Protocol { payload = RLP.encode(payload) // Use snappy compression if peer supports DevP2P >=v5 + // @ts-ignore const protocolVersion = this._peer._hello?.protocolVersion if (protocolVersion !== undefined && protocolVersion >= 5) { payload = snappy.compress(payload) diff --git a/packages/devp2p/src/rlpx/peer.ts b/packages/devp2p/src/rlpx/peer.ts index b8d32584e5..d867ac2323 100644 --- a/packages/devp2p/src/rlpx/peer.ts +++ b/packages/devp2p/src/rlpx/peer.ts @@ -64,29 +64,29 @@ interface Hello { } export class Peer extends EventEmitter { - protected readonly _clientId: Uint8Array + public readonly clientId: Uint8Array protected _capabilities?: Capabilities[] public common: Common protected _port: number - protected readonly _id: Uint8Array + public readonly id: Uint8Array protected _remoteClientIdFilter?: string[] protected _remoteId: Uint8Array protected _EIP8: Uint8Array | boolean protected _eciesSession: ECIES protected _state: string - _weHello: HelloMsg | null - _hello: Hello | null - _nextPacketSize: number - _socket: Socket - _socketData: Uint8Array - _pingIntervalId: NodeJS.Timeout | null - _pingTimeoutId: NodeJS.Timeout | null - _closed: boolean - _connected: boolean - _disconnectReason?: DISCONNECT_REASON - _disconnectWe: null | boolean - _pingTimeout: number - _logger: Debugger + protected _weHello: HelloMsg | null + protected _hello: Hello | null + protected _nextPacketSize: number + protected _socket: Socket + protected _socketData: Uint8Array + protected _pingIntervalId: NodeJS.Timeout | null + protected _pingTimeoutId: NodeJS.Timeout | null + protected _closed: boolean + protected _connected: boolean + protected _disconnectReason?: DISCONNECT_REASON + protected _disconnectWe: null | boolean + protected _pingTimeout: number + private _logger: Debugger /** * Subprotocols (e.g. `ETH`) derived from the exchange on @@ -98,17 +98,17 @@ export class Peer extends EventEmitter { super() // hello data - this._clientId = options.clientId + this.clientId = options.clientId this._capabilities = options.capabilities this.common = options.common this._port = options.port - this._id = options.id + this.id = options.id this._remoteClientIdFilter = options.remoteClientIdFilter // ECIES session this._remoteId = options.remoteId this._EIP8 = options.EIP8 ?? true - this._eciesSession = new ECIES(options.privateKey, this._id, this._remoteId) + this._eciesSession = new ECIES(options.privateKey, this.id, this._remoteId) // Auth, Ack, Header, Body this._state = 'Auth' @@ -221,14 +221,14 @@ export class Peer extends EventEmitter { // TODO: Remove when we can also serve snap requests from other peers .filter((c) => c.name !== 'snap') .map((c) => `${c.name}${c.version}`) - .join(',')} clientId=${bytesToUtf8(this._clientId)}` + .join(',')} clientId=${bytesToUtf8(this.clientId)}` ) const payload: HelloMsg = [ intToBytes(BASE_PROTOCOL_VERSION), - this._clientId, + this.clientId, this._capabilities!.map((c) => [utf8ToBytes(c.name), intToBytes(c.version)]), this._port === null ? new Uint8Array(0) : intToBytes(this._port), - this._id, + this.id, ] if (!this._closed) { diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index 10e8ef28fb..d42aee0046 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -264,7 +264,9 @@ export class RLPx extends EventEmitter { this._peersQueue.push({ peer: { id: peer.getId()!, + // @ts-ignore address: peer._socket.remoteAddress, + // @ts-ignore tcpPort: peer._socket.remotePort, }, ts: (Date.now() + 300000) as number, // 5 min * 60 * 1000 From 7fcc6070e1b242485e5a26715416cf4700c14f0d Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 10:58:57 -0700 Subject: [PATCH 12/23] Make id public readonly --- packages/devp2p/src/rlpx/rlpx.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/devp2p/src/rlpx/rlpx.ts b/packages/devp2p/src/rlpx/rlpx.ts index d42aee0046..9420132e41 100644 --- a/packages/devp2p/src/rlpx/rlpx.ts +++ b/packages/devp2p/src/rlpx/rlpx.ts @@ -36,7 +36,7 @@ export class RLPx extends EventEmitter { private _debug: Debugger protected _timeout: number protected _maxPeers: number - protected _clientId: Uint8Array + public readonly clientId: Uint8Array protected _remoteClientIdFilter?: string[] protected _capabilities: Capabilities[] protected _common: Common @@ -61,7 +61,7 @@ export class RLPx extends EventEmitter { this._timeout = options.timeout ?? 10000 // 10 sec * 1000 this._maxPeers = options.maxPeers ?? 10 - this._clientId = options.clientId + this.clientId = options.clientId ? options.clientId : utf8ToBytes(`ethereumjs-devp2p/${os.platform()}-${os.arch()}/nodejs`) @@ -207,7 +207,7 @@ export class RLPx extends EventEmitter { privateKey: this._privateKey, id: this.id, timeout: this._timeout, - clientId: this._clientId, + clientId: this.clientId, remoteClientIdFilter: this._remoteClientIdFilter, capabilities: this._capabilities, common: this._common, From 584f5ef8ea73b39f25983bcf881e8907d0b3b364 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:01:14 -0700 Subject: [PATCH 13/23] Update names and access specifiers of Mac class fields --- packages/devp2p/src/rlpx/mac.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/devp2p/src/rlpx/mac.ts b/packages/devp2p/src/rlpx/mac.ts index ca775b0acb..5419218603 100644 --- a/packages/devp2p/src/rlpx/mac.ts +++ b/packages/devp2p/src/rlpx/mac.ts @@ -6,8 +6,8 @@ import { xor } from '../util.js' type Hash = ReturnType export class MAC { - _hash: Hash - _secret: Uint8Array + protected _hash: Hash + protected _secret: Uint8Array constructor(secret: Uint8Array) { this._hash = keccak256.create() this._secret = secret From 8c73139e70e75b84b9f522ef7ab39d1d9d9062c2 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:03:16 -0700 Subject: [PATCH 14/23] Update names and access specifiers of ECIES class fields --- packages/devp2p/src/rlpx/ecies.ts | 36 +++++++++++++++---------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/packages/devp2p/src/rlpx/ecies.ts b/packages/devp2p/src/rlpx/ecies.ts index 026880de28..dd921ca1bd 100644 --- a/packages/devp2p/src/rlpx/ecies.ts +++ b/packages/devp2p/src/rlpx/ecies.ts @@ -58,24 +58,24 @@ function concatKDF(keyMaterial: Uint8Array, keyLength: number) { } export class ECIES { - _privateKey: Uint8Array - _publicKey: Uint8Array - _remotePublicKey: Uint8Array | null - _nonce: Uint8Array - _remoteNonce: Uint8Array | null = null - _initMsg: Uint8Array | null | undefined = null - _remoteInitMsg: Uint8Array | null = null - _gotEIP8Auth: boolean = false - _gotEIP8Ack: boolean = false - _ingressAes: Decipher | null = null - _egressAes: Decipher | null = null - _ingressMac: MAC | null = null - _egressMac: MAC | null = null - _ephemeralPrivateKey: Uint8Array - _ephemeralPublicKey: Uint8Array - _remoteEphemeralPublicKey: Uint8Array | null = null // we don't need store this key, but why don't? - _ephemeralSharedSecret: Uint8Array | null = null - _bodySize: number | null = null + protected _privateKey: Uint8Array + protected _publicKey: Uint8Array + protected _remotePublicKey: Uint8Array | null + protected _nonce: Uint8Array + protected _remoteNonce: Uint8Array | null = null + protected _initMsg: Uint8Array | null | undefined = null + protected _remoteInitMsg: Uint8Array | null = null + protected _gotEIP8Auth: boolean = false + protected _gotEIP8Ack: boolean = false + protected _ingressAes: Decipher | null = null + protected _egressAes: Decipher | null = null + protected _ingressMac: MAC | null = null + protected _egressMac: MAC | null = null + protected _ephemeralPrivateKey: Uint8Array + protected _ephemeralPublicKey: Uint8Array + protected _remoteEphemeralPublicKey: Uint8Array | null = null // we don't need store this key, but why don't? + protected _ephemeralSharedSecret: Uint8Array | null = null + protected _bodySize: number | null = null constructor(privateKey: Uint8Array, id: Uint8Array, remoteId: Uint8Array) { this._privateKey = privateKey From 12d266d1bb5e2f9fe8359b7484360e514ece6815 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:10:29 -0700 Subject: [PATCH 15/23] Update names and access specifiers of Peer class fields --- packages/devp2p/src/rlpx/peer.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/devp2p/src/rlpx/peer.ts b/packages/devp2p/src/rlpx/peer.ts index d867ac2323..42cdf34128 100644 --- a/packages/devp2p/src/rlpx/peer.ts +++ b/packages/devp2p/src/rlpx/peer.ts @@ -169,8 +169,10 @@ export class Peer extends EventEmitter { _sendAck() { if (this._closed) return this._logger( + // @ts-ignore `Send ack (EIP8: ${this._eciesSession._gotEIP8Auth}) to ${this._socket.remoteAddress}:${this._socket.remotePort}` ) + // @ts-ignore if (this._eciesSession._gotEIP8Auth) { const ackEIP8 = this._eciesSession.createAckEIP8() if (!ackEIP8) return @@ -300,10 +302,12 @@ export class Peer extends EventEmitter { _handleAuth() { const bytesCount = this._nextPacketSize const parseData = this._socketData.subarray(0, bytesCount) + // @ts-ignore if (!this._eciesSession._gotEIP8Auth) { if (parseData.subarray(0, 1) === hexToBytes('0x04')) { this._eciesSession.parseAuthPlain(parseData) } else { + // @ts-ignore this._eciesSession._gotEIP8Auth = true this._nextPacketSize = bytesToInt(this._socketData.subarray(0, 2)) + 2 return @@ -323,6 +327,7 @@ export class Peer extends EventEmitter { _handleAck() { const bytesCount = this._nextPacketSize const parseData = this._socketData.subarray(0, bytesCount) + // @ts-ignore if (!this._eciesSession._gotEIP8Ack) { if (parseData.subarray(0, 1) === hexToBytes('0x04')) { this._eciesSession.parseAckPlain(parseData) @@ -330,6 +335,7 @@ export class Peer extends EventEmitter { `Received ack (old format) from ${this._socket.remoteAddress}:${this._socket.remotePort}` ) } else { + // @ts-ignore this._eciesSession._gotEIP8Ack = true this._nextPacketSize = bytesToInt(this._socketData.subarray(0, 2)) + 2 return From 00c2cacbbbf9c9de471e1f7ea2dd853cd69e485c Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:12:22 -0700 Subject: [PATCH 16/23] Ignore accessibility errors in examples --- packages/devp2p/examples/peer-communication-les.cts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/devp2p/examples/peer-communication-les.cts b/packages/devp2p/examples/peer-communication-les.cts index 1a8ae50a25..b622b2c8e8 100644 --- a/packages/devp2p/examples/peer-communication-les.cts +++ b/packages/devp2p/examples/peer-communication-les.cts @@ -34,6 +34,7 @@ const REMOTE_CLIENTID_FILTER = [ 'prichain', ] +// @ts-ignore const getPeerAddr = (peer: Peer) => `${peer._socket.remoteAddress}:${peer._socket.remotePort}` // DPT From aa10a2e8fc4028d46118c66ed988bd58b0b49b6a Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:34:56 -0700 Subject: [PATCH 17/23] Update example --- packages/devp2p/examples/peer-communication.cts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/devp2p/examples/peer-communication.cts b/packages/devp2p/examples/peer-communication.cts index e1906a6157..236a466319 100644 --- a/packages/devp2p/examples/peer-communication.cts +++ b/packages/devp2p/examples/peer-communication.cts @@ -49,6 +49,7 @@ const CHECK_BLOCK_HEADER = RLP.decode( '0xf90219a0d44a4d33e28d7ea9edd12b69bd32b394587eee498b0e2543ce2bad1877ffbeaca01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347941ad91ee08f21be3de0ba2ba6918e714da6b45836a0fdec060ee45e55da9e36060fc95dddd0bdc47e447224666a895d9f0dc9adaa0ca0092d9fcc02ca9b372daec726704ce720d3aa366739868f4820ecaabadb9ac309a0974fee017515a46303f467b6fd50872994db1b0ea64d3455bad93ff9678aced9b90100356050004c5c89691add79838a01d4c302419252a4d3c96e9273908b7ee84660886c070607b4928c416a1800746a0d1dbb442d0baf06eea321422263726748600cc200e82aec08336863514d12d665718016989189c116bc0947046cc6718110586c11464a189000a11a41cc96991970153d88840768170244197e164c6204249b9091a0052ac85088c8108a4418dd2903690a036722623888ea14e90458a390a305a2342cb02766094f68c4100036330719848b48411614686717ab6068a46318204232429dc42020608802ceecd66c3c33a3a1fc6e82522049470328a4a81ba07c6604228ba94f008476005087a6804463696b41002650c0fdf548448a90408717ca31b6d618e883bad42083be153b83bdfbb1846078104798307834383639373636353666366532303530366636663663a0ae1de0acd35a98e211c7e276ad7524bb84a5e1b8d33dd7d1c052b095b564e8b888cca66773148b6e12' ) +// @ts-ignore const getPeerAddr = (peer: Peer) => `${peer._socket.remoteAddress}:${peer._socket.remotePort}` // DPT From 40b15a11546c22a7c992314e2e794b1c7e68d32e Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:40:21 -0700 Subject: [PATCH 18/23] Update names and access specifiers of class fields in protocol subpackage --- packages/devp2p/src/protocol/eth.ts | 14 +++++++------- packages/devp2p/src/protocol/les.ts | 4 ++-- packages/devp2p/src/protocol/protocol.ts | 14 +++++++------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/devp2p/src/protocol/eth.ts b/packages/devp2p/src/protocol/eth.ts index 2f6b8301b8..3b2c2f0a94 100644 --- a/packages/devp2p/src/protocol/eth.ts +++ b/packages/devp2p/src/protocol/eth.ts @@ -20,15 +20,15 @@ import type { SendMethod } from '../types.js' import type { Input } from '@ethereumjs/rlp' export class ETH extends Protocol { - _status: ETH.StatusMsg | null = null - _peerStatus: ETH.StatusMsg | null = null - DEBUG: boolean = false + protected _status: ETH.StatusMsg | null = null + protected _peerStatus: ETH.StatusMsg | null = null + private DEBUG: boolean = false // Eth64 - _hardfork: string = 'chainstart' - _latestBlock = BigInt(0) - _forkHash: string = '' - _nextForkBlock = BigInt(0) + protected _hardfork: string = 'chainstart' + protected _latestBlock = BigInt(0) + protected _forkHash: string = '' + protected _nextForkBlock = BigInt(0) constructor(version: number, peer: Peer, send: SendMethod) { super(peer, send, ProtocolType.ETH, version, ETH.MESSAGE_CODES) diff --git a/packages/devp2p/src/protocol/les.ts b/packages/devp2p/src/protocol/les.ts index a91c96eeaa..e71bdaa3fd 100644 --- a/packages/devp2p/src/protocol/les.ts +++ b/packages/devp2p/src/protocol/les.ts @@ -21,8 +21,8 @@ import type { Input, NestedUint8Array } from '@ethereumjs/rlp' export const DEFAULT_ANNOUNCE_TYPE = 1 export class LES extends Protocol { - _status: LES.Status | null = null - _peerStatus: LES.Status | null = null + protected _status: LES.Status | null = null + protected _peerStatus: LES.Status | null = null constructor(version: number, peer: Peer, send: SendMethod) { super(peer, send, ProtocolType.LES, version, LES.MESSAGE_CODES) diff --git a/packages/devp2p/src/protocol/protocol.ts b/packages/devp2p/src/protocol/protocol.ts index f52bef2ce2..eba782ac4f 100644 --- a/packages/devp2p/src/protocol/protocol.ts +++ b/packages/devp2p/src/protocol/protocol.ts @@ -12,13 +12,13 @@ const { debug: createDebugLogger } = debugDefault type MessageCodes = { [key: number | string]: number | string } export abstract class Protocol extends EventEmitter { - _version: number - _peer: Peer - _send: SendMethod - _statusTimeoutId?: NodeJS.Timeout - _messageCodes: MessageCodes - _debug: Debugger - _verbose: boolean + protected _version: number + protected _peer: Peer + protected _send: SendMethod + protected _statusTimeoutId?: NodeJS.Timeout + protected _messageCodes: MessageCodes + private _debug: Debugger + protected _verbose: boolean /** * Will be set to the first successfully connected peer to allow for From 6c84f17b5bc741ce949c824bf9c2b30f76075613 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:46:56 -0700 Subject: [PATCH 19/23] Update names and access specifiers of class fields in ext subpackage --- packages/devp2p/src/ext/kbucket.ts | 46 +++++++++++++++--------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/packages/devp2p/src/ext/kbucket.ts b/packages/devp2p/src/ext/kbucket.ts index 1252453352..c3f72fe687 100644 --- a/packages/devp2p/src/ext/kbucket.ts +++ b/packages/devp2p/src/ext/kbucket.ts @@ -55,13 +55,13 @@ type KBucketNode = { * @extends EventEmitter */ export class KBucket extends EventEmitter { - localNodeId: Uint8Array - numberOfNodesPerKBucket: number - numberOfNodesToPing: number + protected _localNodeId: Uint8Array + protected _numberOfNodesPerKBucket: number + protected _numberOfNodesToPing: number distance: (firstId: Uint8Array, secondId: Uint8Array) => number arbiter: (incumbent: Contact, candidate: Contact) => Contact - metadata: object - root: KBucketNode + protected _metadata: object + protected _root: KBucketNode /** * * @param {KBucketOptions} options @@ -69,15 +69,15 @@ export class KBucket extends EventEmitter { constructor(options: KBucketOptions = {}) { super() - this.localNodeId = options.localNodeId ?? randomBytes(20) - this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket ?? 20 - this.numberOfNodesToPing = options.numberOfNodesToPing ?? 3 + this._localNodeId = options.localNodeId ?? randomBytes(20) + this._numberOfNodesPerKBucket = options.numberOfNodesPerKBucket ?? 20 + this._numberOfNodesToPing = options.numberOfNodesToPing ?? 3 this.distance = options.distance ?? KBucket.distance // use an arbiter from options or vectorClock arbiter by default this.arbiter = options.arbiter ?? KBucket.arbiter - this.metadata = Object.assign({}, options.metadata) + this._metadata = Object.assign({}, options.metadata) - this.root = createNode() + this._root = createNode() } /** @@ -126,7 +126,7 @@ export class KBucket extends EventEmitter { } let bitIndex = 0 - let node = this.root + let node = this._root while (node.contacts === null) { // this is not a leaf node but an inner node with 'low' and 'high' @@ -142,7 +142,7 @@ export class KBucket extends EventEmitter { return this } - if (node.contacts.length < this.numberOfNodesPerKBucket) { + if (node.contacts.length < this._numberOfNodesPerKBucket) { node.contacts.push(contact as Contact) this.emit('added', contact) return this @@ -151,11 +151,11 @@ export class KBucket extends EventEmitter { // the bucket is full if (node.dontSplit !== undefined) { // we are not allowed to split the bucket - // we need to ping the first this.numberOfNodesToPing + // we need to ping the first this._numberOfNodesToPing // in order to determine if they are alive // only if one of the pinged nodes does not respond, can the new contact // be added (this prevents DoS flodding with new invalid contacts) - this.emit('ping', node.contacts.slice(0, this.numberOfNodesToPing), contact) + this.emit('ping', node.contacts.slice(0, this._numberOfNodesToPing), contact) return this } @@ -182,7 +182,7 @@ export class KBucket extends EventEmitter { let contacts: Contact[] = [] - for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n; ) { + for (let nodes = [this._root], bitIndex = 0; nodes.length > 0 && contacts.length < n; ) { const node = nodes.pop()! if (node.contacts === null) { const detNode = this._determineNode(node, id, bitIndex++) @@ -204,7 +204,7 @@ export class KBucket extends EventEmitter { */ count(): number { let count = 0 - for (const nodes = [this.root]; nodes.length > 0; ) { + for (const nodes = [this._root]; nodes.length > 0; ) { const node = nodes.pop()! if (node.contacts === null) nodes.push(node.right!, node.left!) else count += node.contacts.length @@ -217,7 +217,7 @@ export class KBucket extends EventEmitter { * Return left leaf if `id` at `bitIndex` is 0, right leaf otherwise * * @param {KBucketNode} node internal object that has 2 leafs: left and right - * @param {Uint8Array} id Id to compare localNodeId with. + * @param {Uint8Array} id Id to compare _localNodeId with. * @param {Number} bitIndex Integer (Default: 0) The bit index to which bit * to check in the id Uint8Array. * @return {KBucketNode} left leaf if id at bitIndex is 0, right leaf otherwise. @@ -267,7 +267,7 @@ export class KBucket extends EventEmitter { get(id: Uint8Array): Contact | null { let bitIndex = 0 - let node = this.root + let node = this._root while (node.contacts === null) { node = this._determineNode(node, id, bitIndex++) } @@ -302,7 +302,7 @@ export class KBucket extends EventEmitter { */ remove(id: Uint8Array): KBucket { let bitIndex = 0 - let node = this.root + let node = this._root while (node.contacts === null) { node = this._determineNode(node, id, bitIndex++) @@ -320,7 +320,7 @@ export class KBucket extends EventEmitter { /** * Splits the node, redistributes contacts to the new nodes, and marks the * node that was split as an inner node of the binary tree of nodes by - * setting this.root.contacts = null + * setting this._root.contacts = null * * @param {object} node node for splitting * @param {number} bitIndex the bitIndex to which byte to check in the @@ -340,7 +340,7 @@ export class KBucket extends EventEmitter { // don't split the "far away" node // we check where the local node would end up and mark the other one as // "dontSplit" (i.e. "far away") - const detNode = this._determineNode(node, this.localNodeId, bitIndex) + const detNode = this._determineNode(node, this._localNodeId, bitIndex) const otherNode = node.left === detNode ? node.right : node.left otherNode.dontSplit = true } @@ -354,7 +354,7 @@ export class KBucket extends EventEmitter { */ toArray(): Contact[] { let result: Contact[] = [] - for (const nodes = [this.root]; nodes.length > 0; ) { + for (const nodes = [this._root]; nodes.length > 0; ) { const node = nodes.pop()! if (node.contacts === null) nodes.push(node.right!, node.left!) else result = result.concat(node.contacts) @@ -370,7 +370,7 @@ export class KBucket extends EventEmitter { * @return {Contact} All of the contacts in the tree, as an iterable */ *toIterable(): Iterable { - for (const nodes = [this.root]; nodes.length > 0; ) { + for (const nodes = [this._root]; nodes.length > 0; ) { const node = nodes.pop()! if (node.contacts === null) { nodes.push(node.right!, node.left!) From e8e7f2242d7be3ddd7f4754232d7fee69e0235ef Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 11:54:08 -0700 Subject: [PATCH 20/23] Update names and access specifiers of class fields in dpt subpackage --- packages/devp2p/src/dpt/ban-list.ts | 10 ++--- packages/devp2p/src/dpt/dpt.ts | 60 ++++++++++++++--------------- packages/devp2p/src/dpt/kbucket.ts | 4 +- packages/devp2p/src/dpt/server.ts | 16 ++++---- 4 files changed, 45 insertions(+), 45 deletions(-) diff --git a/packages/devp2p/src/dpt/ban-list.ts b/packages/devp2p/src/dpt/ban-list.ts index 4188148f02..5d9cf408ac 100644 --- a/packages/devp2p/src/dpt/ban-list.ts +++ b/packages/devp2p/src/dpt/ban-list.ts @@ -14,19 +14,19 @@ const debug = createDebugLogger('devp2p:dpt:ban-list') const verbose = createDebugLogger('verbose').enabled export class BanList { - private lru: LRUCache + private _lru: LRUCache constructor() { - this.lru = new LRU({ max: 10000 }) + this._lru = new LRU({ max: 10000 }) } 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}`) + this._lru.set(key, true, { ttl: maxAge }) + debug(`Added peer ${formatLogId(key, verbose)}, size: ${this._lru.size}`) } } has(obj: string | Uint8Array | PeerInfo): boolean { - return KBucket.getKeys(obj).some((key: string) => Boolean(this.lru.get(key))) + return KBucket.getKeys(obj).some((key: string) => Boolean(this._lru.get(key))) } } diff --git a/packages/devp2p/src/dpt/dpt.ts b/packages/devp2p/src/dpt/dpt.ts index 6b5a974e01..33d84ce6dc 100644 --- a/packages/devp2p/src/dpt/dpt.ts +++ b/packages/devp2p/src/dpt/dpt.ts @@ -15,27 +15,27 @@ import type { Debugger } from 'debug' const DEBUG_BASE_NAME = 'dpt' export class DPT extends EventEmitter { - privateKey: Uint8Array - banlist: BanList - dns: DNS - _debug: Debugger - - private _id: Uint8Array | undefined - private _kbucket: KBucket - private _server: DPTServer - private _refreshIntervalId: NodeJS.Timeout - private _refreshIntervalSelectionCounter: number = 0 - private _shouldFindNeighbours: boolean - private _shouldGetDnsPeers: boolean - private _dnsRefreshQuantity: number - private _dnsNetworks: string[] - private _dnsAddr: string + protected _privateKey: Uint8Array + protected _banlist: BanList + protected _dns: DNS + private _debug: Debugger + + public readonly id: Uint8Array | undefined + protected _kbucket: KBucket + protected _server: DPTServer + protected _refreshIntervalId: NodeJS.Timeout + protected _refreshIntervalSelectionCounter: number = 0 + protected _shouldFindNeighbours: boolean + protected _shouldGetDnsPeers: boolean + protected _dnsRefreshQuantity: number + protected _dnsNetworks: string[] + protected _dnsAddr: string constructor(privateKey: Uint8Array, options: DPTOptions) { super() - this.privateKey = privateKey - this._id = pk2id(secp256k1.getPublicKey(this.privateKey, false)) + this._privateKey = privateKey + this.id = pk2id(secp256k1.getPublicKey(this._privateKey, false)) this._shouldFindNeighbours = options.shouldFindNeighbours ?? true this._shouldGetDnsPeers = options.shouldGetDnsPeers ?? false // By default, tries to connect to 12 new peers every 3s @@ -43,15 +43,15 @@ export class DPT extends EventEmitter { this._dnsNetworks = options.dnsNetworks ?? [] this._dnsAddr = options.dnsAddr ?? '8.8.8.8' - this.dns = new DNS({ dnsServerAddress: this._dnsAddr }) - this.banlist = new BanList() + this._dns = new DNS({ dnsServerAddress: this._dnsAddr }) + this._banlist = new BanList() - this._kbucket = new KBucket(this._id) + this._kbucket = new KBucket(this.id) this._kbucket.on('added', (peer: PeerInfo) => this.emit('peer:added', peer)) this._kbucket.on('removed', (peer: PeerInfo) => this.emit('peer:removed', peer)) this._kbucket.on('ping', this._onKBucketPing.bind(this)) - this._server = new DPTServer(this, this.privateKey, { + this._server = new DPTServer(this, this._privateKey, { timeout: options.timeout, endpoint: options.endpoint, createSocket: options.createSocket, @@ -82,7 +82,7 @@ export class DPT extends EventEmitter { } _onKBucketPing(oldPeers: PeerInfo[], newPeer: PeerInfo): void { - if (this.banlist.has(newPeer)) return + if (this._banlist.has(newPeer)) return let count = 0 let err: Error | null = null @@ -90,13 +90,13 @@ export class DPT extends EventEmitter { this._server .ping(peer) .catch((_err: Error) => { - this.banlist.add(peer, 300000) // 5 min * 60 * 1000 + this._banlist.add(peer, 300000) // 5 min * 60 * 1000 this._kbucket.remove(peer) err = err ?? _err }) .then(() => { if (++count < oldPeers.length) return - if (err === null) this.banlist.add(newPeer, 300000) // 5 min * 60 * 1000 + if (err === null) this._banlist.add(newPeer, 300000) // 5 min * 60 * 1000 else this._kbucket.add(newPeer) }) } @@ -122,14 +122,14 @@ export class DPT extends EventEmitter { this.emit('error', error) return } - if (!this._id) return + if (!this.id) return if (this._shouldFindNeighbours) { - this._server.findneighbours(peer, this._id) + this._server.findneighbours(peer, this.id) } } async addPeer(obj: PeerInfo): Promise { - if (this.banlist.has(obj)) throw new Error('Peer is banned') + if (this._banlist.has(obj)) throw new Error('Peer is banned') this._debug(`attempt adding peer ${obj.address}:${obj.udpPort}`) // check k-bucket first @@ -143,7 +143,7 @@ export class DPT extends EventEmitter { this._kbucket.add(peer) return peer } catch (err: any) { - this.banlist.add(obj, 300000) // 5 min * 60 * 1000 + this._banlist.add(obj, 300000) // 5 min * 60 * 1000 throw err } } @@ -165,12 +165,12 @@ export class DPT extends EventEmitter { } banPeer(obj: string | PeerInfo | Uint8Array, maxAge?: number) { - this.banlist.add(obj, maxAge) + this._banlist.add(obj, maxAge) this._kbucket.remove(obj) } async getDnsPeers(): Promise { - return this.dns.getPeers(this._dnsRefreshQuantity, this._dnsNetworks) + return this._dns.getPeers(this._dnsRefreshQuantity, this._dnsNetworks) } async refresh(): Promise { diff --git a/packages/devp2p/src/dpt/kbucket.ts b/packages/devp2p/src/dpt/kbucket.ts index df310aa29c..a9d1891acf 100644 --- a/packages/devp2p/src/dpt/kbucket.ts +++ b/packages/devp2p/src/dpt/kbucket.ts @@ -9,8 +9,8 @@ const KBUCKET_SIZE = 16 const KBUCKET_CONCURRENCY = 3 export class KBucket extends EventEmitter { - _peers: Map = new Map() - _kbucket: _KBucket + protected _peers: Map = new Map() + protected _kbucket: _KBucket constructor(localNodeId: Uint8Array) { super() diff --git a/packages/devp2p/src/dpt/server.ts b/packages/devp2p/src/dpt/server.ts index 653579e366..92802c55d9 100644 --- a/packages/devp2p/src/dpt/server.ts +++ b/packages/devp2p/src/dpt/server.ts @@ -22,14 +22,14 @@ const verbose = createDebugLogger('verbose').enabled const VERSION = 0x04 export class Server extends EventEmitter { - _dpt: DPT - _privateKey: Uint8Array - _timeout: number - _endpoint: PeerInfo - _requests: Map - _requestsCache: LRUCache> - _socket: DgramSocket | null - _debug: Debugger + protected _dpt: DPT + protected _privateKey: Uint8Array + protected _timeout: number + protected _endpoint: PeerInfo + protected _requests: Map + protected _requestsCache: LRUCache> + protected _socket: DgramSocket | null + private _debug: Debugger constructor(dpt: DPT, privateKey: Uint8Array, options: DPTServerOptions) { super() From 2250869c6523adc4e5a38e159e37ba8aac15fdeb Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 12:01:08 -0700 Subject: [PATCH 21/23] Update names and access specifiers of class fields in dns subpackage --- packages/devp2p/src/dns/dns.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/devp2p/src/dns/dns.ts b/packages/devp2p/src/dns/dns.ts index bf56b4fda3..2569b831d8 100644 --- a/packages/devp2p/src/dns/dns.ts +++ b/packages/devp2p/src/dns/dns.ts @@ -21,8 +21,8 @@ type SearchContext = { } export class DNS { - private _DNSTreeCache: { [key: string]: string } - private readonly _errorTolerance: number = 10 + protected _DNSTreeCache: { [key: string]: string } + protected readonly _errorTolerance: number = 10 constructor(options: DNSOptions = {}) { this._DNSTreeCache = {} From 34a1ab928226f260522a115bf26d0498c33776b9 Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 12:28:30 -0700 Subject: [PATCH 22/23] Fix name of accessed field --- packages/devp2p/test/integration/util.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/devp2p/test/integration/util.ts b/packages/devp2p/test/integration/util.ts index 3c360c0dd9..7316e78704 100644 --- a/packages/devp2p/test/integration/util.ts +++ b/packages/devp2p/test/integration/util.ts @@ -84,7 +84,8 @@ export function getTestRLPXs( const dpts = getTestDPTs(numRLPXs, basePort) for (let i = 0; i < numRLPXs; ++i) { - const rlpx = new RLPx(dpts[i].privateKey, { + // @ts-ignore + const rlpx = new RLPx(dpts[i]._privateKey, { dpt: dpts[i], maxPeers, capabilities, From cc708e2199c892b4ada0613edc55f9ba15bce0dd Mon Sep 17 00:00:00 2001 From: Amir Date: Sun, 16 Jul 2023 12:28:57 -0700 Subject: [PATCH 23/23] Update tests --- packages/devp2p/test/integration/dpt-simulator.spec.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/devp2p/test/integration/dpt-simulator.spec.ts b/packages/devp2p/test/integration/dpt-simulator.spec.ts index 2e26073890..fc9f1ece28 100644 --- a/packages/devp2p/test/integration/dpt-simulator.spec.ts +++ b/packages/devp2p/test/integration/dpt-simulator.spec.ts @@ -56,7 +56,8 @@ describe('DPT simulator tests', () => { dpts[0].banPeer(peer) }) dpts[0].once('peer:removed', async (peer) => { - assert.equal(dpts[0].banlist.has(peer), true, 'ban-list should contain peer') + // @ts-ignore + assert.equal(dpts[0]._banlist.has(peer), true, 'ban-list should contain peer') assert.equal( dpts[0].getPeers().length, 0, @@ -141,7 +142,8 @@ describe('DPT simulator tests', () => { dpts[0].destroy() assert.ok(true, 'got peer from DNS') } - dpts[0].dns.__setNativeDNSModuleResolve(mockDns) + // @ts-ignore + dpts[0]._dns.__setNativeDNSModuleResolve(mockDns) await dpts[0].refresh() }) })