Skip to content

Commit

Permalink
Use async version of crypto.randomBytes() (#4075)
Browse files Browse the repository at this point in the history
* Use async version of crypto.randomBytes()

* Use promisify node util

* Compute randomBytesAsync once

Co-authored-by: dapplion <35266934+dapplion@users.noreply.github.com>
  • Loading branch information
twoeths and dapplion authored Jun 3, 2022
1 parent c8d5c56 commit adc9906
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions packages/lodestar/src/network/peers/discover.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import crypto from "node:crypto";
import {promisify} from "node:util";
import LibP2p from "libp2p";
import PeerId from "peer-id";
import {Multiaddr} from "multiaddr";
Expand All @@ -18,6 +19,8 @@ const MAX_CACHED_ENRS = 100;
/** Max age a cached ENR will be considered for dial */
const MAX_CACHED_ENR_AGE_MS = 5 * 60 * 1000;

const randomBytesAsync = promisify(crypto.randomBytes);

export type PeerDiscoveryOpts = {
maxPeers: number;
discv5FirstQueryDelayMs: number;
Expand Down Expand Up @@ -226,13 +229,14 @@ export class PeerDiscovery {
this.metrics?.discovery.findNodeQueryRequests.inc({action: "start"});
}

const randomNodeId = crypto.randomBytes(64).toString("hex");

// Use async version to prevent blocking the event loop
// Time to completion of this function is not critical, in case this async call add extra lag
const randomNodeId = await randomBytesAsync(64);
this.randomNodeQuery = {code: QueryStatusCode.Active, count: 0};
const timer = this.metrics?.discovery.findNodeQueryTime.startTimer();

try {
const enrs = await this.discv5.findNode(randomNodeId);
const enrs = await this.discv5.findNode(randomNodeId.toString("hex"));
this.metrics?.discovery.findNodeQueryEnrCount.inc(enrs.length);
} catch (e) {
this.logger.error("Error on discv5.findNode()", {}, e as Error);
Expand Down

0 comments on commit adc9906

Please sign in to comment.