Skip to content

Commit

Permalink
feat!: update libp2p deps (#295)
Browse files Browse the repository at this point in the history
  • Loading branch information
wemeetagain committed Sep 11, 2024
1 parent ac0cc72 commit ead057d
Show file tree
Hide file tree
Showing 18 changed files with 271 additions and 256 deletions.
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"version": "0.0.0",
"description": "Discovery V5 monorepo",
"type": "module",
"workspaces": ["packages/*"],
"workspaces": [
"packages/*"
],
"scripts": {
"check-types": "lerna run check-types",
"build": "lerna run build",
Expand Down Expand Up @@ -38,5 +40,6 @@
"prettier": "^2.6.2",
"ts-node": "^10.8.1",
"typescript": "^4.7.3"
}
},
"packageManager": "yarn@1.22.22+sha256.c17d3797fb9a9115bf375e31bfd30058cac6bc9c3b8807a3d8cb2094794b51ca"
}
8 changes: 3 additions & 5 deletions packages/discv5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,11 @@
"url": "https://github.com/ChainSafe/discv5/issues"
},
"homepage": "https://github.com/ChainSafe/discv5#readme",
"devDependencies": {
"@libp2p/peer-id-factory": "^4.0.3"
},
"devDependencies": {},
"dependencies": {
"@chainsafe/enr": "^3.1.0",
"@libp2p/crypto": "^4.0.1",
"@libp2p/interface": "^1.1.1",
"@libp2p/crypto": "^5.0.0",
"@libp2p/interface": "^2.0.0",
"@multiformats/multiaddr": "^12.1.10",
"bcrypto": "^5.4.0",
"bigint-buffer": "^1.1.5",
Expand Down
9 changes: 4 additions & 5 deletions packages/discv5/src/libp2p/discv5.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import {
CustomEvent,
PeerDiscovery,
PeerDiscoveryEvents,
peerDiscoverySymbol,
PeerId,
PeerInfo,
PrivateKey,
TypedEventEmitter,
} from "@libp2p/interface";
import { Multiaddr, multiaddr } from "@multiformats/multiaddr";
Expand Down Expand Up @@ -58,7 +57,7 @@ export interface IDiscv5DiscoveryInputOptions extends Partial<IDiscv5Config> {
}

export interface IDiscv5DiscoveryOptions extends IDiscv5DiscoveryInputOptions {
peerId: PeerId;
privateKey: PrivateKey;
}

/**
Expand All @@ -77,7 +76,7 @@ export class Discv5Discovery extends TypedEventEmitter<PeerDiscoveryEvents> impl
super();
this.discv5 = Discv5.create({
enr: options.enr,
peerId: options.peerId,
privateKey: options.privateKey,
bindAddrs: {
ip4: options.bindAddrs.ip4 ? multiaddr(options.bindAddrs.ip4) : undefined,
ip6: options.bindAddrs.ip6 ? multiaddr(options.bindAddrs.ip6) : undefined,
Expand Down Expand Up @@ -142,7 +141,7 @@ export class Discv5Discovery extends TypedEventEmitter<PeerDiscoveryEvents> impl
this.dispatchEvent(
new CustomEvent<PeerInfo>("peer", {
detail: {
id: await enr.peerId(),
id: enr.peerId,
multiaddrs,
},
})
Expand Down
3 changes: 1 addition & 2 deletions packages/discv5/src/packet/encode.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { CodeError } from "@libp2p/interface";
import cipher from "bcrypto/lib/cipher.js";
import { toBigIntBE, toBufferBE } from "bigint-buffer";

import { bufferToNumber, fromHex, numberToBuffer, toHex } from "../util/index.js";
import { bufferToNumber, CodeError, fromHex, numberToBuffer, toHex } from "../util/index.js";
import {
AUTHDATA_SIZE_SIZE,
EPH_KEY_SIZE_SIZE,
Expand Down
27 changes: 9 additions & 18 deletions packages/discv5/src/service/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,8 @@ import { EventEmitter } from "events";
import debug from "debug";
import { randomBytes } from "@libp2p/crypto";
import { Multiaddr } from "@multiformats/multiaddr";
import { CodeError, PeerId } from "@libp2p/interface";
import {
createPeerIdFromPublicKey,
createPrivateKeyFromPeerId,
ENR,
NodeId,
MAX_RECORD_SIZE,
createNodeId,
SignableENR,
} from "@chainsafe/enr";
import { PeerId, PrivateKey } from "@libp2p/interface";
import { createPeerIdFromPublicKey, ENR, NodeId, MAX_RECORD_SIZE, createNodeId, SignableENR } from "@chainsafe/enr";

import { BindAddrs, IPMode, ITransportService, UDPTransportService } from "../transport/index.js";
import { MAX_PACKET_SIZE } from "../packet/index.js";
Expand Down Expand Up @@ -44,7 +36,7 @@ import {
RequestId,
} from "../message/index.js";
import { AddrVotes } from "./addrVotes.js";
import { toBuffer } from "../util/index.js";
import { CodeError, toBuffer } from "../util/index.js";
import { IDiscv5Config, defaultConfig } from "../config/index.js";
import { createNodeContact, getNodeAddress, getNodeId, INodeAddress, NodeContact } from "../session/nodeInfo.js";
import {
Expand Down Expand Up @@ -89,7 +81,7 @@ const log = debug("discv5:service");

export interface IDiscv5CreateOptions {
enr: SignableENRInput;
peerId: PeerId;
privateKey: PrivateKey;
bindAddrs: BindAddrs;
config?: Partial<IDiscv5Config>;
metricsRegistry?: MetricsRegister | null;
Expand Down Expand Up @@ -207,16 +199,15 @@ export class Discv5 extends (EventEmitter as { new (): Discv5EventEmitter }) {
* Convenience method to create a new discv5 service.
*
* @param enr the ENR record identifying the current node.
* @param peerId the PeerId with the keypair that identifies the enr
* @param privateKey the PrivateKey that identifies the enr
* @param multiaddr The multiaddr which contains the network interface and port to which the UDP server binds
*/
public static create(opts: IDiscv5CreateOptions): Discv5 {
const { enr, peerId, bindAddrs, config = {}, metricsRegistry, transport } = opts;
const { enr, privateKey, bindAddrs, config = {}, metricsRegistry, transport } = opts;
const fullConfig = { ...defaultConfig, ...config };
const metrics = metricsRegistry ? createDiscv5Metrics(metricsRegistry) : undefined;
const { type, privateKey } = createPrivateKeyFromPeerId(peerId);
const keypair = createKeypair({ type, privateKey });
const decodedEnr = typeof enr === "string" ? SignableENR.decodeTxt(enr, privateKey) : enr;
const keypair = createKeypair({ type: privateKey.type, privateKey: privateKey.raw });
const decodedEnr = typeof enr === "string" ? SignableENR.decodeTxt(enr, privateKey.raw) : enr;
const rateLimiter = opts.rateLimiterOpts && new RateLimiter(opts.rateLimiterOpts, metrics ?? null);
const sessionService = new SessionService(
fullConfig,
Expand Down Expand Up @@ -309,7 +300,7 @@ export class Discv5 extends (EventEmitter as { new (): Discv5EventEmitter }) {
return this.sessionService.keypair;
}

public peerId(): Promise<PeerId> {
public get peerId(): PeerId {
return createPeerIdFromPublicKey(this.keypair.type, this.keypair.publicKey);
}

Expand Down
3 changes: 1 addition & 2 deletions packages/discv5/src/service/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { EventEmitter } from "events";
import StrictEventEmitter from "strict-event-emitter-types";
import { CodeError } from "@libp2p/interface";
import { Multiaddr } from "@multiformats/multiaddr";
import { ENR, SequenceNumber, SignableENR } from "@chainsafe/enr";

Expand All @@ -14,7 +13,7 @@ import {
} from "../message/index.js";
import { INodeAddress, NodeContact } from "../session/nodeInfo.js";
import { ConnectionDirection } from "../session/index.js";
import { SocketAddress } from "../util/ip.js";
import { CodeError, SocketAddress } from "../util/index.js";

export interface IDiscv5Events {
/**
Expand Down
9 changes: 6 additions & 3 deletions packages/discv5/src/session/nodeInfo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Multiaddr, isMultiaddr } from "@multiformats/multiaddr";
import { peerIdFromString } from "@libp2p/peer-id";
import { createPublicKeyFromPeerId, ENR, NodeId, getV4Crypto } from "@chainsafe/enr";
import { ENR, NodeId, getV4Crypto } from "@chainsafe/enr";
import { createKeypair, IKeypair } from "../keypair/index.js";
import { IPMode } from "../transport/types.js";
import { getSocketAddressMultiaddrOnENR } from "../util/ip.js";
Expand Down Expand Up @@ -81,8 +81,11 @@ export function createNodeContact(input: ENR | Multiaddr, ipMode: IPMode): NodeC
throw new Error("Multiaddr must specify a peer id");
}
const peerId = peerIdFromString(peerIdStr);
const { type, publicKey } = createPublicKeyFromPeerId(peerId);
const keypair = createKeypair({ type, publicKey });
const publicKey = peerId.publicKey;
if (!publicKey) {
throw new Error("Peer ID must have a public key");
}
const keypair = createKeypair({ type: publicKey.type, publicKey: publicKey.raw });
const nodeId = getV4Crypto().nodeId(keypair.publicKey);
return {
type: INodeContactType.Raw,
Expand Down
7 changes: 7 additions & 0 deletions packages/discv5/src/util/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class CodeError extends Error {
code: string;
constructor(message: string, code: string) {
super(message);
this.code = code;
}
}
1 change: 1 addition & 0 deletions packages/discv5/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from "./timeoutMap.js";
export * from "./toBuffer.js";
export * from "./crypto.js";
export * from "./ip.js";
export * from "./error.js";
19 changes: 9 additions & 10 deletions packages/discv5/test/e2e/connect.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/* eslint-env mocha */
import { expect } from "chai";
import { privateKeyFromProtobuf } from "@libp2p/crypto/keys";
import { PrivateKey } from "@libp2p/interface";
import { multiaddr } from "@multiformats/multiaddr";
import { PeerId } from "@libp2p/interface";
import { createFromPrivKey } from "@libp2p/peer-id-factory";
import { unmarshalPrivateKey } from "@libp2p/crypto/keys";
import { SignableENR } from "@chainsafe/enr";
import { Discv5 } from "../../src/index.js";

Expand All @@ -14,23 +13,23 @@ describe("discv5 integration test", function () {
const nodes: Discv5[] = [];

type Node = {
peerId: PeerId;
privateKey: PrivateKey;
enr: SignableENR;
discv5: Discv5;
};
async function getDiscv5Node(): Promise<Node> {
const idx = nodeIdx++;
const port = portBase + idx;
const peerId = await getPeerId(idx);
const enr = SignableENR.createFromPeerId(peerId);
const privateKey = getPrivateKey(idx);
const enr = SignableENR.createFromPrivateKey(privateKey);

const bindAddrUdp = `/ip4/127.0.0.1/udp/${port}`;
const multiAddrUdp = multiaddr(bindAddrUdp);
enr.setLocationMultiaddr(multiAddrUdp);

const discv5 = Discv5.create({
enr,
peerId,
privateKey,
bindAddrs: { ip4: multiAddrUdp },
config: {
lookupTimeout: 2000,
Expand All @@ -41,7 +40,7 @@ describe("discv5 integration test", function () {

await discv5.start();

return { peerId, enr, discv5 };
return { privateKey, enr, discv5 };
}

// 2862ae92fa59042fd4d4a3e3bddb92b33a53b72be15deafce07dfbd7c3b12812
Expand Down Expand Up @@ -87,7 +86,7 @@ describe("discv5 integration test", function () {
});
});

async function getPeerId(i: number): Promise<PeerId> {
function getPrivateKey(i: number): PrivateKey {
const privKeysBase64 = [
"CAISIF9nhmNn+vOoMPdR+adfKwjSdgqrVGmAX0AWe6Tgjj/p",
"CAISIMSR1N4+3m62NGJ8pdgiUPzFR4vv8pZKG6q+iys+B2DL",
Expand All @@ -100,5 +99,5 @@ async function getPeerId(i: number): Promise<PeerId> {
"CAISIHRKcVKLTpKhQOEIPwQjH2xx/nvJWWLUCr90/NOuuZ+l",
"CAISIP3n7vFWZKye7duop0nhfttFJUXTVvQfd4q0dPpURLke",
];
return await createFromPrivKey(await unmarshalPrivateKey(Buffer.from(privKeysBase64[i], "base64")));
return privateKeyFromProtobuf(Buffer.from(privKeysBase64[i], "base64"));
}
19 changes: 8 additions & 11 deletions packages/discv5/test/e2e/mainnetBootnodes.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/* eslint-env mocha */
import { expect } from "chai";
import { generateKeyPair, privateKeyFromProtobuf } from "@libp2p/crypto/keys";
import { multiaddr } from "@multiformats/multiaddr";
import { createSecp256k1PeerId, createFromPrivKey } from "@libp2p/peer-id-factory";
import { unmarshalPrivateKey } from "@libp2p/crypto/keys";
import { ENR, SignableENR } from "@chainsafe/enr";
import { Discv5 } from "../../src/index.js";

Expand All @@ -11,7 +10,7 @@ let port = 9000;
describe("discv5 integration test", function () {
this.timeout("5min");

const RANDOM_PEER_ID = true; // Otherwise uses a fixed private key
const RANDOM_PRIVATE_KEY = true; // Otherwise uses a fixed private key
const bootnodesENRText = getMainnetBootnodesENRText();

for (const bindAddrs of [
Expand All @@ -30,19 +29,17 @@ describe("discv5 integration test", function () {
// ip6 test fails in github runner
if (process.env.CI && bindAddrs.ip6) this.skip();

const peerId = RANDOM_PEER_ID
? await createSecp256k1PeerId()
: await createFromPrivKey(
await unmarshalPrivateKey(
Buffer.from("080212205465237331224a07d9c7b9c458e0859f401ab49f01c971857d373a3e6f6fdf3a", "hex")
)
const privateKey = RANDOM_PRIVATE_KEY
? await generateKeyPair("secp256k1")
: privateKeyFromProtobuf(
Buffer.from("080212205465237331224a07d9c7b9c458e0859f401ab49f01c971857d373a3e6f6fdf3a", "hex")
);

const enr = SignableENR.createFromPeerId(peerId);
const enr = SignableENR.createFromPrivateKey(privateKey);

const discv5 = Discv5.create({
enr,
peerId,
privateKey,
bindAddrs,
config: {
lookupTimeout: 2000,
Expand Down
27 changes: 0 additions & 27 deletions packages/discv5/test/unit/keypair/index.test.ts

This file was deleted.

11 changes: 6 additions & 5 deletions packages/discv5/test/unit/service/service.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
/* eslint-env mocha */
import { expect } from "chai";
import { privateKeyFromRaw } from "@libp2p/crypto/keys";
import { multiaddr } from "@multiformats/multiaddr";
import { createPeerIdFromPrivateKey, SignableENR } from "@chainsafe/enr";
import { SignableENR } from "@chainsafe/enr";

import { Discv5 } from "../../../src/service/service.js";
import { generateKeypair } from "../../../src/keypair/index.js";

describe("Discv5", async () => {
const kp0 = generateKeypair("secp256k1");
const peerId0 = await createPeerIdFromPrivateKey(kp0.type, kp0.privateKey);
const privateKey0 = privateKeyFromRaw(kp0.privateKey);
const enr0 = SignableENR.createV4(kp0.privateKey);
const mu0 = multiaddr("/ip4/127.0.0.1/udp/40000");

const service0 = Discv5.create({ enr: enr0, peerId: peerId0, bindAddrs: { ip4: mu0 } });
const service0 = Discv5.create({ enr: enr0, privateKey: privateKey0, bindAddrs: { ip4: mu0 } });

beforeEach(async () => {
await service0.start();
Expand Down Expand Up @@ -41,7 +42,7 @@ describe("Discv5", async () => {
it("should complete a lookup to another node", async function () {
this.timeout(10000);
const kp1 = generateKeypair("secp256k1");
const peerId1 = await createPeerIdFromPrivateKey(kp1.type, kp1.privateKey);
const privateKey1 = privateKeyFromRaw(kp1.privateKey);
const enr1 = SignableENR.createV4(kp1.privateKey);
const mu1 = multiaddr("/ip4/127.0.0.1/udp/10360");
const addr1 = mu1.tuples();
Expand All @@ -53,7 +54,7 @@ describe("Discv5", async () => {
enr1.set("ip", addr1[0][1]);
enr1.set("udp", addr1[1][1]);
enr1.encode();
const service1 = Discv5.create({ enr: enr1, peerId: peerId1, bindAddrs: { ip4: mu1 } });
const service1 = Discv5.create({ enr: enr1, privateKey: privateKey1, bindAddrs: { ip4: mu1 } });
await service1.start();
for (let i = 0; i < 100; i++) {
const kp = generateKeypair("secp256k1");
Expand Down
Loading

0 comments on commit ead057d

Please sign in to comment.