Skip to content

Commit

Permalink
Replace remaining NodeId parameters with ENR (#684)
Browse files Browse the repository at this point in the history
* network: replace remaining ENR parameters

* fix tests
  • Loading branch information
ScottyPoi authored Dec 6, 2024
1 parent 83f7f76 commit af6a9b9
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 50 deletions.
12 changes: 6 additions & 6 deletions packages/cli/src/rpc/modules/portal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ enr: ENR,
message: 'invalid node id',
}
}
const res = await this._history.sendFindNodes(enr, distances)
const res = await this._history.sendFindNodes(ENR.decodeTxt(enr), distances)
if (!res) {
return []
}
Expand All @@ -630,7 +630,7 @@ enr: ENR,
message: 'invalid node id',
}
}
const res = await this._state.sendFindNodes(enr, distances)
const res = await this._state.sendFindNodes(ENR.decodeTxt(enr), distances)
if (!res) {
return []
}
Expand All @@ -649,7 +649,7 @@ enr: ENR,
message: 'invalid node id',
}
}
const res = await this._beacon.sendFindNodes(enr, distances)
const res = await this._beacon.sendFindNodes(ENR.decodeTxt(enr), distances)
if (!res) {
return []
}
Expand Down Expand Up @@ -782,7 +782,7 @@ enr: ENR,
this.logger.extend('findContent')(
`received request to send request to ${shortId(nodeId)} for contentKey ${contentKey}`,
)
const res = await this._history.sendFindContent(enr, hexToBytes(contentKey))
const res = await this._history.sendFindContent(ENR.decodeTxt(enr), hexToBytes(contentKey))
if (res === undefined) {
this.logger.extend('findContent')(`request returned undefined`)
return undefined
Expand Down Expand Up @@ -814,7 +814,7 @@ enr: ENR,
this.logger.extend('findContent')(
`received request to send request to ${shortId(nodeId)} for contentKey ${contentKey}`,
)
const res = await this._state.sendFindContent(nodeId, hexToBytes(contentKey))
const res = await this._state.sendFindContent(ENR.decodeTxt(enr), hexToBytes(contentKey))
if (res === undefined) {
this.logger.extend('findContent')(`request returned type: ENRS`)
return { enrs: [] }
Expand Down Expand Up @@ -847,7 +847,7 @@ enr: ENR,
}
}

const res = await this._beacon.sendFindContent(nodeId, hexToBytes(contentKey))
const res = await this._beacon.sendFindContent(ENR.decodeTxt(enr), hexToBytes(contentKey))

if (res === undefined) {
this.logger.extend('findContent')(`request returned type: ENRS`)
Expand Down
19 changes: 10 additions & 9 deletions packages/portalnetwork/src/networks/beacon/beacon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,10 @@ export class BeaconLightClientNetwork extends BaseNetwork {
private getBootstrap = async (nodeId: string, network: NetworkId) => {
// We check the network ID because NodeAdded is emitted regardless of network
if (network !== NetworkId.BeaconChainNetwork) return
const enr = getENR(this.routingTable, nodeId)
if (enr === undefined) return
const decoded = await this.sendFindContent(
nodeId,
enr,
concatBytes(
new Uint8Array([BeaconLightClientNetworkContentType.LightClientBootstrap]),
LightClientBootstrapKey.serialize({ blockHash: hexToBytes(this.trustedBlockRoot!) }),
Expand Down Expand Up @@ -185,7 +187,9 @@ export class BeaconLightClientNetwork extends BaseNetwork {
this.logger.extend('BOOTSTRAP')(
`Requesting recent LightClientUpdates from ${shortId(nodeId, this.routingTable)}`,
)
const range = await this.sendFindContent(nodeId, rangeKey)
const enr = getENR(this.routingTable, nodeId)
if (enr === undefined) return
const range = await this.sendFindContent(enr, rangeKey)
if (range === undefined || 'enrs' in range) return // If we don't get a range, exit early

const updates = LightClientUpdatesByRange.deserialize(range.content as Uint8Array)
Expand Down Expand Up @@ -236,7 +240,9 @@ export class BeaconLightClientNetwork extends BaseNetwork {
`found a consensus bootstrap candidate ${results[x][0]}`,
)
for (const vote of votes) {
const res = await this.sendFindContent(vote[0], bootstrapKey)
const enr = getENR(this.routingTable, vote[0])
if (enr === undefined) continue
const res = await this.sendFindContent(enr, bootstrapKey)
if (res !== undefined && 'content' in res) {
try {
const fork = this.beaconConfig.forkDigest2ForkName(
Expand Down Expand Up @@ -426,14 +432,9 @@ export class BeaconLightClientNetwork extends BaseNetwork {
}

public sendFindContent = async (
dstId: string,
enr: ENR,
key: Uint8Array,
): Promise<ContentLookupResponse | undefined> => {
const enr = getENR(this.routingTable, dstId)
if (enr === undefined) {
this.logger(`No ENR found for ${shortId(dstId)}. FINDCONTENT aborted.`)
return undefined
}
this.portal.metrics?.findContentMessagesSent.inc()
const findContentMsg: FindContentMessage = { contentKey: key }
const payload = PortalWireMessageType.serialize({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class UltralightTransport implements LightClientTransport {
decoded = await this.network.findContentLocally(rangeKey)
if (decoded === undefined || bytesToHex(decoded) === '0x') {
const res = await this.network.sendFindContent(
this.network.routingTable.random()!.nodeId,
this.network.routingTable.random()!,
rangeKey,
)
if (res !== undefined && 'content' in res)
Expand Down Expand Up @@ -109,7 +109,7 @@ export class UltralightTransport implements LightClientTransport {

// Try to get optimistic update from Portal Network
const decoded = await this.network.sendFindContent(
this.network.routingTable.random()!.nodeId,
this.network.routingTable.random()!,
concatBytes(
new Uint8Array([BeaconLightClientNetworkContentType.LightClientOptimisticUpdate]),
LightClientOptimisticUpdateKey.serialize({
Expand Down Expand Up @@ -176,7 +176,7 @@ export class UltralightTransport implements LightClientTransport {
}
// Try to get finality update from Portal Network
const decoded = await this.network.sendFindContent(
this.network.routingTable.random()!.nodeId,
this.network.routingTable.random()!,
concatBytes(
new Uint8Array([BeaconLightClientNetworkContentType.LightClientFinalityUpdate]),
LightClientFinalityUpdateKey.serialize({ finalitySlot: nextFinalitySlot }),
Expand Down
2 changes: 1 addition & 1 deletion packages/portalnetwork/src/networks/contentLookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export class ContentLookup {
this.pending.add(peer.enr.encodeTxt())
this.logger(`Requesting content from ${shortId(peer.enr.nodeId)}`)
try {
const res = await this.network.sendFindContent!(peer.enr.encodeTxt(), this.contentKey)
const res = await this.network.sendFindContent!(peer.enr, this.contentKey)
this.pending.delete(peer.enr.encodeTxt())
if (this.finished) {
this.logger(`Response from ${shortId(peer.enr.nodeId)} arrived after lookup finished`)
Expand Down
9 changes: 2 additions & 7 deletions packages/portalnetwork/src/networks/history/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
RequestCode,
decodeHistoryNetworkContentKey,
decodeReceipts,
getENR,
reassembleBlock,
saveReceipts,
shortId,
Expand All @@ -31,6 +30,7 @@ import { getContentKey, verifyPreCapellaHeaderProof, verifyPreMergeHeaderProof }

import type { Debugger } from 'debug'
import type { BaseNetworkConfig, ContentLookupResponse, FindContentMessage } from '../../index.js'
import type { ENR } from '@chainsafe/enr'
export class HistoryNetwork extends BaseNetwork {
networkId: NetworkId.HistoryNetwork
networkName = 'HistoryNetwork'
Expand Down Expand Up @@ -195,12 +195,7 @@ export class HistoryNetwork extends BaseNetwork {
* @param networkId subnetwork ID on which content is being sought
* @returns the value of the FOUNDCONTENT response or undefined
*/
public sendFindContent = async (dstId: string, key: Uint8Array) => {
const enr = getENR(this.routingTable, dstId)
if (enr === undefined) {
this.logger(`No ENR found for ${shortId(dstId)}. FINDCONTENT aborted.`)
return undefined
}
public sendFindContent = async (enr: ENR, key: Uint8Array) => {
this.portal.metrics?.findContentMessagesSent.inc()
const findContentMsg: FindContentMessage = { contentKey: key }
const payload = PortalWireMessageType.serialize({
Expand Down
16 changes: 3 additions & 13 deletions packages/portalnetwork/src/networks/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
arrayByteLength,
encodeWithVariantPrefix,
generateRandomNodeIdAtDistance,
getENR,
randUint16,
shortId,
} from '../index.js'
Expand Down Expand Up @@ -304,22 +303,13 @@ export abstract class BaseNetwork extends EventEmitter {
* @param networkId subnetwork id for message being
* @returns a {@link `NodesMessage`} or undefined
*/
public sendFindNodes = async (dstId: string, distances: number[]) => {
public sendFindNodes = async (enr: ENR, distances: number[]) => {
this.portal.metrics?.findNodesMessagesSent.inc()
const findNodesMsg: FindNodesMessage = { distances }
const payload = PortalWireMessageType.serialize({
selector: MessageCodes.FINDNODES,
value: findNodesMsg,
})
let enr
try {
enr = getENR(this.routingTable, dstId)
} catch (err: any) {
// TODO: Find source of "cannot read properties of undefined (reading 'getWithPending')" error
}
if (enr === undefined) {
return
}
const res = await this.sendMessage(enr, payload, this.networkId)
if (bytesToInt(res.slice(0, 1)) === MessageCodes.NODES) {
this.portal.metrics?.nodesMessagesReceived.inc()
Expand Down Expand Up @@ -735,7 +725,7 @@ export abstract class BaseNetwork extends EventEmitter {
abstract findContentLocally: (contentKey: Uint8Array) => Promise<Uint8Array | undefined>

abstract sendFindContent?: (
dstId: string,
enr: ENR,
key: Uint8Array,
) => Promise<ContentLookupResponse | undefined>

Expand Down Expand Up @@ -823,7 +813,7 @@ export abstract class BaseNetwork extends EventEmitter {
for (let x = 239; x < 256; x++) {
// Ask for nodes in all log2distances 239 - 256
if (this.routingTable.valuesOfDistance(x).length === 0) {
await this.sendFindNodes(enr.nodeId, [x])
await this.sendFindNodes(enr, [x])
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/portalnetwork/src/networks/nodeLookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class NodeLookup {
})

const queryPromise = async () => {
const response = await this.network.sendFindNodes(peer.encodeTxt(), [distanceToTarget])
const response = await this.network.sendFindNodes(peer, [distanceToTarget])
if (!response?.enrs) return

for (const enr of response.enrs) {
Expand Down
10 changes: 3 additions & 7 deletions packages/portalnetwork/src/networks/state/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
} from '@ethereumjs/util'
import debug from 'debug'

import { getENR, shortId } from '../../util/util.js'
import { shortId } from '../../util/util.js'
import { RequestCode } from '../../wire/index.js'
import {
ContentMessageType,
Expand Down Expand Up @@ -44,6 +44,7 @@ import type { Debugger } from 'debug'
import type { FindContentMessage } from '../../wire/types.js'
import type { BaseNetworkConfig, ContentLookupResponse } from '../index.js'
import type { TNibbles } from './types.js'
import type { ENR } from '@chainsafe/enr'

export class StateNetwork extends BaseNetwork {
networkId: NetworkId.StateNetwork
Expand All @@ -69,12 +70,7 @@ export class StateNetwork extends BaseNetwork {
* @param key content key defined by the subnetwork spec
* @returns the value of the FOUNDCONTENT response or undefined
*/
public sendFindContent = async (dstId: string, key: Uint8Array) => {
const enr = getENR(this.routingTable, dstId)
if (enr === undefined) {
this.logger(`No ENR found for ${shortId(dstId)}. FINDCONTENT aborted.`)
return
}
public sendFindContent = async (enr: ENR, key: Uint8Array) => {
this.portal.metrics?.findContentMessagesSent.inc()
const findContentMsg: FindContentMessage = { contentKey: key }
const payload = PortalWireMessageType.serialize({
Expand Down
4 changes: 2 additions & 2 deletions packages/portalnetwork/test/integration/beacon.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ describe('Find Content tests', () => {
hexToBytes(optimisticUpdate.content_value),
)
const res = await network2.sendFindContent(
node1.discv5.enr.nodeId,
node1.discv5.enr.toENR(),
concatBytes(
new Uint8Array([0x13]),
LightClientOptimisticUpdateKey.serialize({ signatureSlot: 6718463n }),
Expand Down Expand Up @@ -238,7 +238,7 @@ describe('Find Content tests', () => {
await network1.storeUpdateRange(hexToBytes(updatesByRange.content_value))

const res = await network2.sendFindContent(
node1.discv5.enr.nodeId,
node1.discv5.enr.toENR(),
hexToBytes(updatesByRange.content_key),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ describe('FindContent', async () => {
await network1.sendPing(network2?.enr!.toENR())

const res = await network2.sendFindContent(
node1.discv5.enr.nodeId,
node1.discv5.enr.toENR(),
getContentKey(HistoryNetworkContentType.BlockHeaderByNumber, BigInt(testBlockData[29].number)),
)
const headerWithProof = BlockHeaderWithProof.deserialize(res!['content'] as Uint8Array)
Expand Down

0 comments on commit af6a9b9

Please sign in to comment.