diff --git a/.aegir.cjs b/.aegir.js similarity index 79% rename from .aegir.cjs rename to .aegir.js index 48d03697..6186529b 100644 --- a/.aegir.cjs +++ b/.aegir.js @@ -1,21 +1,20 @@ -'use strict' +import { WebSockets } from '@libp2p/websockets' +import { Mplex } from '@libp2p/mplex' +import { NOISE } from '@chainsafe/libp2p-noise' +import { pipe } from 'it-pipe' +import { createFromJSON } from '@libp2p/peer-id-factory' /** @type {import('aegir').PartialOptions} */ -module.exports = { +export default { build: { - bundlesizeMax: '253kB' + bundlesizeMax: '147kB' }, test: { before: async () => { const { createLibp2p } = await import('./dist/src/index.js') const { MULTIADDRS_WEBSOCKETS } = await import('./dist/test/fixtures/browser.js') - const { default: Peers } = await import('./dist/test/fixtures/peers.js') - const { WebSockets } = await import('@libp2p/websockets') - const { Mplex } = await import('@libp2p/mplex') - const { NOISE } = await import('@chainsafe/libp2p-noise') const { Plaintext } = await import('./dist/src/insecure/index.js') - const { pipe } = await import('it-pipe') - const { createFromJSON } = await import('@libp2p/peer-id-factory') + const { default: Peers } = await import('./dist/test/fixtures/peers.js') // Use the last peer const peerId = await createFromJSON(Peers[Peers.length - 1]) diff --git a/examples/libp2p-in-the-browser/package.json b/examples/libp2p-in-the-browser/package.json index 6f330dc2..f8ee1eef 100644 --- a/examples/libp2p-in-the-browser/package.json +++ b/examples/libp2p-in-the-browser/package.json @@ -3,9 +3,6 @@ "version": "1.0.0", "description": "A libp2p node running in the browser", "type": "module", - "browserslist": [ - "last 2 Chrome versions" - ], "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "vite" diff --git a/examples/libp2p-in-the-browser/vite.config.js b/examples/libp2p-in-the-browser/vite.config.js new file mode 100644 index 00000000..04ae6bed --- /dev/null +++ b/examples/libp2p-in-the-browser/vite.config.js @@ -0,0 +1,5 @@ +export default { + build: { + target: 'es2020' + } +} \ No newline at end of file diff --git a/examples/webrtc-direct/package.json b/examples/webrtc-direct/package.json index 03a33b62..57e79c6e 100644 --- a/examples/webrtc-direct/package.json +++ b/examples/webrtc-direct/package.json @@ -3,9 +3,6 @@ "version": "0.0.1", "private": true, "type": "module", - "browserslist": [ - "last 2 Chrome versions" - ], "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "vite" diff --git a/examples/webrtc-direct/vite.config.js b/examples/webrtc-direct/vite.config.js new file mode 100644 index 00000000..04ae6bed --- /dev/null +++ b/examples/webrtc-direct/vite.config.js @@ -0,0 +1,5 @@ +export default { + build: { + target: 'es2020' + } +} \ No newline at end of file diff --git a/package.json b/package.json index e1d74575..58efc772 100644 --- a/package.json +++ b/package.json @@ -76,36 +76,34 @@ ] }, "scripts": { + "clean": "aegir clean", "lint": "aegir lint", - "build": "tsc", - "postbuild": "mkdirp dist/src/circuit/pb dist/src/fetch/pb dist/src/identify/pb dist/src/insecure/pb && cp src/circuit/pb/*.js src/circuit/pb/*.d.ts dist/src/circuit/pb && cp src/fetch/pb/*.js src/fetch/pb/*.d.ts dist/src/fetch/pb && cp src/identify/pb/*.js src/identify/pb/*.d.ts dist/src/identify/pb && cp src/insecure/pb/*.js src/insecure/pb/*.d.ts dist/src/insecure/pb", - "generate": "run-s generate:proto:* generate:proto-types:*", - "generate:proto:circuit": "pbjs -t static-module -w es6 -r libp2p-circuit --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/circuit/protocol/index.js ./src/circuit/protocol/index.proto", - "generate:proto:fetch": "pbjs -t static-module -w es6 -r libp2p-fetch --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/fetch/proto.js ./src/fetch/proto.proto", - "generate:proto:identify": "pbjs -t static-module -w es6 -r libp2p-identify --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/identify/message.js ./src/identify/message.proto", - "generate:proto:plaintext": "pbjs -t static-module -w es6 -r libp2p-plaintext --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/insecure/proto.js ./src/insecure/proto.proto", - "generate:proto-types:circuit": "pbts -o src/circuit/protocol/index.d.ts src/circuit/protocol/index.js", - "generate:proto-types:fetch": "pbts -o src/fetch/proto.d.ts src/fetch/proto.js", - "generate:proto-types:identify": "pbts -o src/identify/message.d.ts src/identify/message.js", - "generate:proto-types:plaintext": "pbts -o src/insecure/proto.d.ts src/insecure/proto.js", - "pretest": "npm run build", + "dep-check": "aegir dep-check", + "build": "aegir build", + "generate": "run-s generate:proto:*", + "generate:proto:circuit": "protons ./src/circuit/pb/index.proto", + "generate:proto:fetch": "protons ./src/fetch/pb/proto.proto", + "generate:proto:identify": "protons ./src/identify/pb/message.proto", + "generate:proto:plaintext": "protons ./src/insecure/pb/proto.proto", "test": "aegir test", - "test:node": "npm run test -- -t node -f \"./dist/test/**/*.{node,spec}.js\" --cov", - "test:chrome": "npm run test -- -t browser -f \"./dist/test/**/*.spec.js\" --cov", - "test:chrome-webworker": "npm run test -- -t webworker -f \"./dist/test/**/*.spec.js\"", - "test:firefox": "npm run test -- -t browser -f \"./dist/test/**/*.spec.js\" -- --browser firefox", - "test:firefox-webworker": "npm run test -- -t webworker -f \"./dist/test/**/*.spec.js\" -- --browser firefox", + "test:node": "aegir test -t node -f \"./dist/test/**/*.{node,spec}.js\" --cov", + "test:chrome": "aegir test -t browser -f \"./dist/test/**/*.spec.js\" --cov", + "test:chrome-webworker": "aegir test -t webworker -f \"./dist/test/**/*.spec.js\"", + "test:firefox": "aegir test -t browser -f \"./dist/test/**/*.spec.js\" -- --browser firefox", + "test:firefox-webworker": "aegir test -t webworker -f \"./dist/test/**/*.spec.js\" -- --browser firefox", "test:examples": "cd examples && npm run test:all", - "test:interop": "npm run test -- -t node -f dist/test/interop.js" + "test:interop": "aegir test -t node -f dist/test/interop.js" }, "dependencies": { "@achingbrain/nat-port-mapper": "^1.0.0", "@libp2p/connection": "^1.1.4", "@libp2p/crypto": "^0.22.9", "@libp2p/interfaces": "^1.3.17", + "@libp2p/logger": "^1.1.3", "@libp2p/multistream-select": "^1.0.3", "@libp2p/peer-id": "^1.1.8", "@libp2p/peer-id-factory": "^1.0.8", + "@libp2p/peer-record": "^1.0.8", "@libp2p/peer-store": "^1.0.6", "@libp2p/utils": "^1.0.9", "@multiformats/mafmt": "^11.0.2", @@ -144,7 +142,7 @@ "p-retry": "^5.0.0", "p-settle": "^5.0.0", "private-ip": "^2.3.3", - "protobufjs": "^6.11.2", + "protons-runtime": "^1.0.2", "retimer": "^3.0.0", "sanitize-filename": "^1.6.3", "set-delayed-interval": "^1.0.0", @@ -165,11 +163,13 @@ "@libp2p/delegated-peer-routing": "^1.0.2", "@libp2p/floodsub": "^1.0.2", "@libp2p/interface-compliance-tests": "^1.1.20", - "@libp2p/interop": "^1.0.0", + "@libp2p/interop": "^1.0.3", "@libp2p/kad-dht": "^1.0.3", "@libp2p/mdns": "^1.0.3", "@libp2p/mplex": "^1.0.1", + "@libp2p/pubsub": "^1.2.14", "@libp2p/tcp": "^1.0.6", + "@libp2p/topology": "^1.1.7", "@libp2p/tracked-map": "^1.0.4", "@libp2p/webrtc-star": "^1.0.3", "@libp2p/websockets": "^1.0.3", @@ -179,10 +179,11 @@ "@types/p-fifo": "^1.0.0", "@types/varint": "^6.0.0", "@types/xsalsa20": "^1.1.0", - "aegir": "^36.1.3", + "aegir": "^37.0.9", "buffer": "^6.0.3", "cborg": "^1.8.1", "delay": "^5.0.0", + "execa": "^6.1.0", "go-libp2p": "^0.0.6", "into-stream": "^7.0.0", "ipfs-http-client": "^56.0.1", @@ -194,6 +195,7 @@ "p-event": "^5.0.1", "p-times": "^4.0.0", "p-wait-for": "^4.1.0", + "protons": "^3.0.2", "rimraf": "^3.0.2", "sinon": "^13.0.1", "ts-sinon": "^2.0.2" diff --git a/src/circuit/circuit/hop.ts b/src/circuit/circuit/hop.ts index 5440813a..8d055884 100644 --- a/src/circuit/circuit/hop.ts +++ b/src/circuit/circuit/hop.ts @@ -2,7 +2,7 @@ import { logger } from '@libp2p/logger' import errCode from 'err-code' import { validateAddrs } from './utils.js' import { StreamHandler } from './stream-handler.js' -import { CircuitRelay as CircuitPB, ICircuitRelay } from '../pb/index.js' +import { CircuitRelay as CircuitPB } from '../pb/index.js' import { pipe } from 'it-pipe' import { codes as Errors } from '../../errors.js' import { stop } from './stop.js' @@ -17,7 +17,7 @@ const log = logger('libp2p:circuit:hop') export interface HopRequest { connection: Connection - request: ICircuitRelay + request: CircuitPB streamHandler: StreamHandler circuit: Circuit connectionManager: ConnectionManager @@ -120,7 +120,7 @@ export async function handleHop (hopRequest: HopRequest) { export interface HopConfig { connection: Connection - request: ICircuitRelay + request: CircuitPB } /** @@ -153,7 +153,7 @@ export async function hop (options: HopConfig): Promise> { log('hop request failed with code %d, closing stream', response.code) streamHandler.close() - throw errCode(new Error(`HOP request failed with code ${response.code}`), Errors.ERR_HOP_REQUEST_FAILED) + throw errCode(new Error(`HOP request failed with code "${response.code ?? 'unknown'}"`), Errors.ERR_HOP_REQUEST_FAILED) } export interface CanHopOptions { diff --git a/src/circuit/circuit/stop.ts b/src/circuit/circuit/stop.ts index edef9672..dab6aab8 100644 --- a/src/circuit/circuit/stop.ts +++ b/src/circuit/circuit/stop.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import { CircuitRelay as CircuitPB, ICircuitRelay } from '../pb/index.js' +import { CircuitRelay as CircuitPB } from '../pb/index.js' import { RELAY_CODEC } from '../multicodec.js' import { StreamHandler } from './stream-handler.js' import { validateAddrs } from './utils.js' @@ -10,7 +10,7 @@ const log = logger('libp2p:circuit:stop') export interface HandleStopOptions { connection: Connection - request: ICircuitRelay + request: CircuitPB streamHandler: StreamHandler } @@ -44,7 +44,7 @@ export function handleStop (options: HandleStopOptions): Duplex | un export interface StopOptions { connection: Connection - request: ICircuitRelay + request: CircuitPB } /** diff --git a/src/circuit/circuit/stream-handler.ts b/src/circuit/circuit/stream-handler.ts index 8b55f36a..3d53bb4d 100644 --- a/src/circuit/circuit/stream-handler.ts +++ b/src/circuit/circuit/stream-handler.ts @@ -1,7 +1,7 @@ import { logger } from '@libp2p/logger' import * as lp from 'it-length-prefixed' import { Handshake, handshake } from 'it-handshake' -import { CircuitRelay, ICircuitRelay } from '../pb/index.js' +import { CircuitRelay } from '../pb/index.js' import type { Stream } from '@libp2p/interfaces/connection' import type { Source } from 'it-stream-types' @@ -53,10 +53,9 @@ export class StreamHandler { /** * Encode and write array of buffers */ - write (msg: ICircuitRelay) { + write (msg: CircuitRelay) { log('write message type %s', msg.type) - // @ts-expect-error lp.encode expects type type 'Buffer | BufferList', not 'Uint8Array' - this.shake.write(lp.encode.single(CircuitRelay.encode(msg).finish())) + this.shake.write(lp.encode.single(CircuitRelay.encode(msg)).slice()) } /** @@ -68,9 +67,9 @@ export class StreamHandler { } /** - * @param {ICircuitRelay} msg - An unencoded CircuitRelay protobuf message + * @param {CircuitRelay} msg - An unencoded CircuitRelay protobuf message */ - end (msg: ICircuitRelay) { + end (msg: CircuitRelay) { this.write(msg) this.close() } diff --git a/src/circuit/circuit/utils.ts b/src/circuit/circuit/utils.ts index b5fe34f2..21e5e293 100644 --- a/src/circuit/circuit/utils.ts +++ b/src/circuit/circuit/utils.ts @@ -1,5 +1,5 @@ import { Multiaddr } from '@multiformats/multiaddr' -import { CircuitRelay, ICircuitRelay } from '../pb/index.js' +import { CircuitRelay } from '../pb/index.js' import type { StreamHandler } from './stream-handler.js' /** @@ -15,7 +15,7 @@ function writeResponse (streamHandler: StreamHandler, status: CircuitRelay.Statu /** * Validate incomming HOP/STOP message */ -export function validateAddrs (msg: ICircuitRelay, streamHandler: StreamHandler) { +export function validateAddrs (msg: CircuitRelay, streamHandler: StreamHandler) { try { if (msg.dstPeer?.addrs != null) { msg.dstPeer.addrs.forEach((addr) => { diff --git a/src/circuit/pb/index.d.ts b/src/circuit/pb/index.d.ts deleted file mode 100644 index 68e4880b..00000000 --- a/src/circuit/pb/index.d.ts +++ /dev/null @@ -1,173 +0,0 @@ -import * as $protobuf from "protobufjs"; -/** Properties of a CircuitRelay. */ -export interface ICircuitRelay { - - /** CircuitRelay type */ - type?: (CircuitRelay.Type|null); - - /** CircuitRelay srcPeer */ - srcPeer?: (CircuitRelay.IPeer|null); - - /** CircuitRelay dstPeer */ - dstPeer?: (CircuitRelay.IPeer|null); - - /** CircuitRelay code */ - code?: (CircuitRelay.Status|null); -} - -/** Represents a CircuitRelay. */ -export class CircuitRelay implements ICircuitRelay { - - /** - * Constructs a new CircuitRelay. - * @param [p] Properties to set - */ - constructor(p?: ICircuitRelay); - - /** CircuitRelay type. */ - public type: CircuitRelay.Type; - - /** CircuitRelay srcPeer. */ - public srcPeer?: (CircuitRelay.IPeer|null); - - /** CircuitRelay dstPeer. */ - public dstPeer?: (CircuitRelay.IPeer|null); - - /** CircuitRelay code. */ - public code: CircuitRelay.Status; - - /** - * Encodes the specified CircuitRelay message. Does not implicitly {@link CircuitRelay.verify|verify} messages. - * @param m CircuitRelay message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: ICircuitRelay, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CircuitRelay message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns CircuitRelay - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): CircuitRelay; - - /** - * Creates a CircuitRelay message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns CircuitRelay - */ - public static fromObject(d: { [k: string]: any }): CircuitRelay; - - /** - * Creates a plain object from a CircuitRelay message. Also converts values to other types if specified. - * @param m CircuitRelay - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: CircuitRelay, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CircuitRelay to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; -} - -export namespace CircuitRelay { - - /** Status enum. */ - enum Status { - SUCCESS = 100, - HOP_SRC_ADDR_TOO_LONG = 220, - HOP_DST_ADDR_TOO_LONG = 221, - HOP_SRC_MULTIADDR_INVALID = 250, - HOP_DST_MULTIADDR_INVALID = 251, - HOP_NO_CONN_TO_DST = 260, - HOP_CANT_DIAL_DST = 261, - HOP_CANT_OPEN_DST_STREAM = 262, - HOP_CANT_SPEAK_RELAY = 270, - HOP_CANT_RELAY_TO_SELF = 280, - STOP_SRC_ADDR_TOO_LONG = 320, - STOP_DST_ADDR_TOO_LONG = 321, - STOP_SRC_MULTIADDR_INVALID = 350, - STOP_DST_MULTIADDR_INVALID = 351, - STOP_RELAY_REFUSED = 390, - MALFORMED_MESSAGE = 400 - } - - /** Type enum. */ - enum Type { - HOP = 1, - STOP = 2, - STATUS = 3, - CAN_HOP = 4 - } - - /** Properties of a Peer. */ - interface IPeer { - - /** Peer id */ - id: Uint8Array; - - /** Peer addrs */ - addrs?: (Uint8Array[]|null); - } - - /** Represents a Peer. */ - class Peer implements IPeer { - - /** - * Constructs a new Peer. - * @param [p] Properties to set - */ - constructor(p?: CircuitRelay.IPeer); - - /** Peer id. */ - public id: Uint8Array; - - /** Peer addrs. */ - public addrs: Uint8Array[]; - - /** - * Encodes the specified Peer message. Does not implicitly {@link CircuitRelay.Peer.verify|verify} messages. - * @param m Peer message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: CircuitRelay.IPeer, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Peer message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns Peer - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): CircuitRelay.Peer; - - /** - * Creates a Peer message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns Peer - */ - public static fromObject(d: { [k: string]: any }): CircuitRelay.Peer; - - /** - * Creates a plain object from a Peer message. Also converts values to other types if specified. - * @param m Peer - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: CircuitRelay.Peer, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Peer to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } -} diff --git a/src/circuit/pb/index.js b/src/circuit/pb/index.js deleted file mode 100644 index 2157d6de..00000000 --- a/src/circuit/pb/index.js +++ /dev/null @@ -1,528 +0,0 @@ -/*eslint-disable*/ -import $protobuf from "protobufjs/minimal.js"; - -// Common aliases -const $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -const $root = $protobuf.roots["libp2p-circuit"] || ($protobuf.roots["libp2p-circuit"] = {}); - -export const CircuitRelay = $root.CircuitRelay = (() => { - - /** - * Properties of a CircuitRelay. - * @exports ICircuitRelay - * @interface ICircuitRelay - * @property {CircuitRelay.Type|null} [type] CircuitRelay type - * @property {CircuitRelay.IPeer|null} [srcPeer] CircuitRelay srcPeer - * @property {CircuitRelay.IPeer|null} [dstPeer] CircuitRelay dstPeer - * @property {CircuitRelay.Status|null} [code] CircuitRelay code - */ - - /** - * Constructs a new CircuitRelay. - * @exports CircuitRelay - * @classdesc Represents a CircuitRelay. - * @implements ICircuitRelay - * @constructor - * @param {ICircuitRelay=} [p] Properties to set - */ - function CircuitRelay(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * CircuitRelay type. - * @member {CircuitRelay.Type} type - * @memberof CircuitRelay - * @instance - */ - CircuitRelay.prototype.type = 1; - - /** - * CircuitRelay srcPeer. - * @member {CircuitRelay.IPeer|null|undefined} srcPeer - * @memberof CircuitRelay - * @instance - */ - CircuitRelay.prototype.srcPeer = null; - - /** - * CircuitRelay dstPeer. - * @member {CircuitRelay.IPeer|null|undefined} dstPeer - * @memberof CircuitRelay - * @instance - */ - CircuitRelay.prototype.dstPeer = null; - - /** - * CircuitRelay code. - * @member {CircuitRelay.Status} code - * @memberof CircuitRelay - * @instance - */ - CircuitRelay.prototype.code = 100; - - /** - * Encodes the specified CircuitRelay message. Does not implicitly {@link CircuitRelay.verify|verify} messages. - * @function encode - * @memberof CircuitRelay - * @static - * @param {ICircuitRelay} m CircuitRelay message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CircuitRelay.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.type != null && Object.hasOwnProperty.call(m, "type")) - w.uint32(8).int32(m.type); - if (m.srcPeer != null && Object.hasOwnProperty.call(m, "srcPeer")) - $root.CircuitRelay.Peer.encode(m.srcPeer, w.uint32(18).fork()).ldelim(); - if (m.dstPeer != null && Object.hasOwnProperty.call(m, "dstPeer")) - $root.CircuitRelay.Peer.encode(m.dstPeer, w.uint32(26).fork()).ldelim(); - if (m.code != null && Object.hasOwnProperty.call(m, "code")) - w.uint32(32).int32(m.code); - return w; - }; - - /** - * Decodes a CircuitRelay message from the specified reader or buffer. - * @function decode - * @memberof CircuitRelay - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {CircuitRelay} CircuitRelay - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CircuitRelay.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.CircuitRelay(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.type = r.int32(); - break; - case 2: - m.srcPeer = $root.CircuitRelay.Peer.decode(r, r.uint32()); - break; - case 3: - m.dstPeer = $root.CircuitRelay.Peer.decode(r, r.uint32()); - break; - case 4: - m.code = r.int32(); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - - /** - * Creates a CircuitRelay message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof CircuitRelay - * @static - * @param {Object.} d Plain object - * @returns {CircuitRelay} CircuitRelay - */ - CircuitRelay.fromObject = function fromObject(d) { - if (d instanceof $root.CircuitRelay) - return d; - var m = new $root.CircuitRelay(); - switch (d.type) { - case "HOP": - case 1: - m.type = 1; - break; - case "STOP": - case 2: - m.type = 2; - break; - case "STATUS": - case 3: - m.type = 3; - break; - case "CAN_HOP": - case 4: - m.type = 4; - break; - } - if (d.srcPeer != null) { - if (typeof d.srcPeer !== "object") - throw TypeError(".CircuitRelay.srcPeer: object expected"); - m.srcPeer = $root.CircuitRelay.Peer.fromObject(d.srcPeer); - } - if (d.dstPeer != null) { - if (typeof d.dstPeer !== "object") - throw TypeError(".CircuitRelay.dstPeer: object expected"); - m.dstPeer = $root.CircuitRelay.Peer.fromObject(d.dstPeer); - } - switch (d.code) { - case "SUCCESS": - case 100: - m.code = 100; - break; - case "HOP_SRC_ADDR_TOO_LONG": - case 220: - m.code = 220; - break; - case "HOP_DST_ADDR_TOO_LONG": - case 221: - m.code = 221; - break; - case "HOP_SRC_MULTIADDR_INVALID": - case 250: - m.code = 250; - break; - case "HOP_DST_MULTIADDR_INVALID": - case 251: - m.code = 251; - break; - case "HOP_NO_CONN_TO_DST": - case 260: - m.code = 260; - break; - case "HOP_CANT_DIAL_DST": - case 261: - m.code = 261; - break; - case "HOP_CANT_OPEN_DST_STREAM": - case 262: - m.code = 262; - break; - case "HOP_CANT_SPEAK_RELAY": - case 270: - m.code = 270; - break; - case "HOP_CANT_RELAY_TO_SELF": - case 280: - m.code = 280; - break; - case "STOP_SRC_ADDR_TOO_LONG": - case 320: - m.code = 320; - break; - case "STOP_DST_ADDR_TOO_LONG": - case 321: - m.code = 321; - break; - case "STOP_SRC_MULTIADDR_INVALID": - case 350: - m.code = 350; - break; - case "STOP_DST_MULTIADDR_INVALID": - case 351: - m.code = 351; - break; - case "STOP_RELAY_REFUSED": - case 390: - m.code = 390; - break; - case "MALFORMED_MESSAGE": - case 400: - m.code = 400; - break; - } - return m; - }; - - /** - * Creates a plain object from a CircuitRelay message. Also converts values to other types if specified. - * @function toObject - * @memberof CircuitRelay - * @static - * @param {CircuitRelay} m CircuitRelay - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - CircuitRelay.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.defaults) { - d.type = o.enums === String ? "HOP" : 1; - d.srcPeer = null; - d.dstPeer = null; - d.code = o.enums === String ? "SUCCESS" : 100; - } - if (m.type != null && m.hasOwnProperty("type")) { - d.type = o.enums === String ? $root.CircuitRelay.Type[m.type] : m.type; - } - if (m.srcPeer != null && m.hasOwnProperty("srcPeer")) { - d.srcPeer = $root.CircuitRelay.Peer.toObject(m.srcPeer, o); - } - if (m.dstPeer != null && m.hasOwnProperty("dstPeer")) { - d.dstPeer = $root.CircuitRelay.Peer.toObject(m.dstPeer, o); - } - if (m.code != null && m.hasOwnProperty("code")) { - d.code = o.enums === String ? $root.CircuitRelay.Status[m.code] : m.code; - } - return d; - }; - - /** - * Converts this CircuitRelay to JSON. - * @function toJSON - * @memberof CircuitRelay - * @instance - * @returns {Object.} JSON object - */ - CircuitRelay.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Status enum. - * @name CircuitRelay.Status - * @enum {number} - * @property {number} SUCCESS=100 SUCCESS value - * @property {number} HOP_SRC_ADDR_TOO_LONG=220 HOP_SRC_ADDR_TOO_LONG value - * @property {number} HOP_DST_ADDR_TOO_LONG=221 HOP_DST_ADDR_TOO_LONG value - * @property {number} HOP_SRC_MULTIADDR_INVALID=250 HOP_SRC_MULTIADDR_INVALID value - * @property {number} HOP_DST_MULTIADDR_INVALID=251 HOP_DST_MULTIADDR_INVALID value - * @property {number} HOP_NO_CONN_TO_DST=260 HOP_NO_CONN_TO_DST value - * @property {number} HOP_CANT_DIAL_DST=261 HOP_CANT_DIAL_DST value - * @property {number} HOP_CANT_OPEN_DST_STREAM=262 HOP_CANT_OPEN_DST_STREAM value - * @property {number} HOP_CANT_SPEAK_RELAY=270 HOP_CANT_SPEAK_RELAY value - * @property {number} HOP_CANT_RELAY_TO_SELF=280 HOP_CANT_RELAY_TO_SELF value - * @property {number} STOP_SRC_ADDR_TOO_LONG=320 STOP_SRC_ADDR_TOO_LONG value - * @property {number} STOP_DST_ADDR_TOO_LONG=321 STOP_DST_ADDR_TOO_LONG value - * @property {number} STOP_SRC_MULTIADDR_INVALID=350 STOP_SRC_MULTIADDR_INVALID value - * @property {number} STOP_DST_MULTIADDR_INVALID=351 STOP_DST_MULTIADDR_INVALID value - * @property {number} STOP_RELAY_REFUSED=390 STOP_RELAY_REFUSED value - * @property {number} MALFORMED_MESSAGE=400 MALFORMED_MESSAGE value - */ - CircuitRelay.Status = (function() { - const valuesById = {}, values = Object.create(valuesById); - values[valuesById[100] = "SUCCESS"] = 100; - values[valuesById[220] = "HOP_SRC_ADDR_TOO_LONG"] = 220; - values[valuesById[221] = "HOP_DST_ADDR_TOO_LONG"] = 221; - values[valuesById[250] = "HOP_SRC_MULTIADDR_INVALID"] = 250; - values[valuesById[251] = "HOP_DST_MULTIADDR_INVALID"] = 251; - values[valuesById[260] = "HOP_NO_CONN_TO_DST"] = 260; - values[valuesById[261] = "HOP_CANT_DIAL_DST"] = 261; - values[valuesById[262] = "HOP_CANT_OPEN_DST_STREAM"] = 262; - values[valuesById[270] = "HOP_CANT_SPEAK_RELAY"] = 270; - values[valuesById[280] = "HOP_CANT_RELAY_TO_SELF"] = 280; - values[valuesById[320] = "STOP_SRC_ADDR_TOO_LONG"] = 320; - values[valuesById[321] = "STOP_DST_ADDR_TOO_LONG"] = 321; - values[valuesById[350] = "STOP_SRC_MULTIADDR_INVALID"] = 350; - values[valuesById[351] = "STOP_DST_MULTIADDR_INVALID"] = 351; - values[valuesById[390] = "STOP_RELAY_REFUSED"] = 390; - values[valuesById[400] = "MALFORMED_MESSAGE"] = 400; - return values; - })(); - - /** - * Type enum. - * @name CircuitRelay.Type - * @enum {number} - * @property {number} HOP=1 HOP value - * @property {number} STOP=2 STOP value - * @property {number} STATUS=3 STATUS value - * @property {number} CAN_HOP=4 CAN_HOP value - */ - CircuitRelay.Type = (function() { - const valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "HOP"] = 1; - values[valuesById[2] = "STOP"] = 2; - values[valuesById[3] = "STATUS"] = 3; - values[valuesById[4] = "CAN_HOP"] = 4; - return values; - })(); - - CircuitRelay.Peer = (function() { - - /** - * Properties of a Peer. - * @memberof CircuitRelay - * @interface IPeer - * @property {Uint8Array} id Peer id - * @property {Array.|null} [addrs] Peer addrs - */ - - /** - * Constructs a new Peer. - * @memberof CircuitRelay - * @classdesc Represents a Peer. - * @implements IPeer - * @constructor - * @param {CircuitRelay.IPeer=} [p] Properties to set - */ - function Peer(p) { - this.addrs = []; - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * Peer id. - * @member {Uint8Array} id - * @memberof CircuitRelay.Peer - * @instance - */ - Peer.prototype.id = $util.newBuffer([]); - - /** - * Peer addrs. - * @member {Array.} addrs - * @memberof CircuitRelay.Peer - * @instance - */ - Peer.prototype.addrs = $util.emptyArray; - - /** - * Encodes the specified Peer message. Does not implicitly {@link CircuitRelay.Peer.verify|verify} messages. - * @function encode - * @memberof CircuitRelay.Peer - * @static - * @param {CircuitRelay.IPeer} m Peer message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Peer.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - w.uint32(10).bytes(m.id); - if (m.addrs != null && m.addrs.length) { - for (var i = 0; i < m.addrs.length; ++i) - w.uint32(18).bytes(m.addrs[i]); - } - return w; - }; - - /** - * Decodes a Peer message from the specified reader or buffer. - * @function decode - * @memberof CircuitRelay.Peer - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {CircuitRelay.Peer} Peer - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Peer.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.CircuitRelay.Peer(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.id = r.bytes(); - break; - case 2: - if (!(m.addrs && m.addrs.length)) - m.addrs = []; - m.addrs.push(r.bytes()); - break; - default: - r.skipType(t & 7); - break; - } - } - if (!m.hasOwnProperty("id")) - throw $util.ProtocolError("missing required 'id'", { instance: m }); - return m; - }; - - /** - * Creates a Peer message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof CircuitRelay.Peer - * @static - * @param {Object.} d Plain object - * @returns {CircuitRelay.Peer} Peer - */ - Peer.fromObject = function fromObject(d) { - if (d instanceof $root.CircuitRelay.Peer) - return d; - var m = new $root.CircuitRelay.Peer(); - if (d.id != null) { - if (typeof d.id === "string") - $util.base64.decode(d.id, m.id = $util.newBuffer($util.base64.length(d.id)), 0); - else if (d.id.length) - m.id = d.id; - } - if (d.addrs) { - if (!Array.isArray(d.addrs)) - throw TypeError(".CircuitRelay.Peer.addrs: array expected"); - m.addrs = []; - for (var i = 0; i < d.addrs.length; ++i) { - if (typeof d.addrs[i] === "string") - $util.base64.decode(d.addrs[i], m.addrs[i] = $util.newBuffer($util.base64.length(d.addrs[i])), 0); - else if (d.addrs[i].length) - m.addrs[i] = d.addrs[i]; - } - } - return m; - }; - - /** - * Creates a plain object from a Peer message. Also converts values to other types if specified. - * @function toObject - * @memberof CircuitRelay.Peer - * @static - * @param {CircuitRelay.Peer} m Peer - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - Peer.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.arrays || o.defaults) { - d.addrs = []; - } - if (o.defaults) { - if (o.bytes === String) - d.id = ""; - else { - d.id = []; - if (o.bytes !== Array) - d.id = $util.newBuffer(d.id); - } - } - if (m.id != null && m.hasOwnProperty("id")) { - d.id = o.bytes === String ? $util.base64.encode(m.id, 0, m.id.length) : o.bytes === Array ? Array.prototype.slice.call(m.id) : m.id; - } - if (m.addrs && m.addrs.length) { - d.addrs = []; - for (var j = 0; j < m.addrs.length; ++j) { - d.addrs[j] = o.bytes === String ? $util.base64.encode(m.addrs[j], 0, m.addrs[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.addrs[j]) : m.addrs[j]; - } - } - return d; - }; - - /** - * Converts this Peer to JSON. - * @function toJSON - * @memberof CircuitRelay.Peer - * @instance - * @returns {Object.} JSON object - */ - Peer.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Peer; - })(); - - return CircuitRelay; -})(); - -export { $root as default }; diff --git a/src/circuit/pb/index.proto b/src/circuit/pb/index.proto index 259ad283..1eaec2e2 100644 --- a/src/circuit/pb/index.proto +++ b/src/circuit/pb/index.proto @@ -1,4 +1,4 @@ -syntax = "proto2"; +syntax = "proto3"; message CircuitRelay { diff --git a/src/circuit/pb/index.ts b/src/circuit/pb/index.ts new file mode 100644 index 00000000..5337cc4e --- /dev/null +++ b/src/circuit/pb/index.ts @@ -0,0 +1,88 @@ +/* eslint-disable import/export */ +/* eslint-disable @typescript-eslint/no-namespace */ + +import { enumeration, encodeMessage, decodeMessage, message, bytes } from 'protons-runtime' + +export interface CircuitRelay { + type?: CircuitRelay.Type + srcPeer?: CircuitRelay.Peer + dstPeer?: CircuitRelay.Peer + code?: CircuitRelay.Status +} + +export namespace CircuitRelay { + export enum Status { + SUCCESS = 'SUCCESS', + HOP_SRC_ADDR_TOO_LONG = 'HOP_SRC_ADDR_TOO_LONG', + HOP_DST_ADDR_TOO_LONG = 'HOP_DST_ADDR_TOO_LONG', + HOP_SRC_MULTIADDR_INVALID = 'HOP_SRC_MULTIADDR_INVALID', + HOP_DST_MULTIADDR_INVALID = 'HOP_DST_MULTIADDR_INVALID', + HOP_NO_CONN_TO_DST = 'HOP_NO_CONN_TO_DST', + HOP_CANT_DIAL_DST = 'HOP_CANT_DIAL_DST', + HOP_CANT_OPEN_DST_STREAM = 'HOP_CANT_OPEN_DST_STREAM', + HOP_CANT_SPEAK_RELAY = 'HOP_CANT_SPEAK_RELAY', + HOP_CANT_RELAY_TO_SELF = 'HOP_CANT_RELAY_TO_SELF', + STOP_SRC_ADDR_TOO_LONG = 'STOP_SRC_ADDR_TOO_LONG', + STOP_DST_ADDR_TOO_LONG = 'STOP_DST_ADDR_TOO_LONG', + STOP_SRC_MULTIADDR_INVALID = 'STOP_SRC_MULTIADDR_INVALID', + STOP_DST_MULTIADDR_INVALID = 'STOP_DST_MULTIADDR_INVALID', + STOP_RELAY_REFUSED = 'STOP_RELAY_REFUSED', + MALFORMED_MESSAGE = 'MALFORMED_MESSAGE' + } + + export namespace Status { + export const codec = () => { + return enumeration(Status) + } + } + export enum Type { + HOP = 'HOP', + STOP = 'STOP', + STATUS = 'STATUS', + CAN_HOP = 'CAN_HOP' + } + + export namespace Type { + export const codec = () => { + return enumeration(Type) + } + } + export interface Peer { + id: Uint8Array + addrs: Uint8Array[] + } + + export namespace Peer { + export const codec = () => { + return message({ + 1: { name: 'id', codec: bytes }, + 2: { name: 'addrs', codec: bytes, repeats: true } + }) + } + + export const encode = (obj: Peer): Uint8Array => { + return encodeMessage(obj, Peer.codec()) + } + + export const decode = (buf: Uint8Array): Peer => { + return decodeMessage(buf, Peer.codec()) + } + } + + export const codec = () => { + return message({ + 1: { name: 'type', codec: CircuitRelay.Type.codec(), optional: true }, + 2: { name: 'srcPeer', codec: CircuitRelay.Peer.codec(), optional: true }, + 3: { name: 'dstPeer', codec: CircuitRelay.Peer.codec(), optional: true }, + 4: { name: 'code', codec: CircuitRelay.Status.codec(), optional: true } + }) + } + + export const encode = (obj: CircuitRelay): Uint8Array => { + return encodeMessage(obj, CircuitRelay.codec()) + } + + export const decode = (buf: Uint8Array): CircuitRelay => { + return decodeMessage(buf, CircuitRelay.codec()) + } +} diff --git a/src/fetch/index.ts b/src/fetch/index.ts index 65f906db..69e14147 100644 --- a/src/fetch/index.ts +++ b/src/fetch/index.ts @@ -75,8 +75,7 @@ export class FetchService implements Startable { const shake = handshake(stream) // send message - const request = new FetchRequest({ identifier: key }) - shake.write(lp.encode.single(FetchRequest.encode(request).finish()).slice()) + shake.write(lp.encode.single(FetchRequest.encode({ identifier: key })).slice()) // read response // @ts-expect-error fromReader returns a Source which has no .next method @@ -109,21 +108,21 @@ export class FetchService implements Startable { // @ts-expect-error fromReader returns a Source which has no .next method const request = FetchRequest.decode((await lp.decode.fromReader(shake.reader).next()).value.slice()) - let response + let response: FetchResponse const lookup = this._getLookupFunction(request.identifier) if (lookup != null) { const data = await lookup(request.identifier) if (data != null) { - response = new FetchResponse({ status: FetchResponse.StatusCode.OK, data }) + response = { status: FetchResponse.StatusCode.OK, data } } else { - response = new FetchResponse({ status: FetchResponse.StatusCode.NOT_FOUND }) + response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) } } } else { const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier) - response = new FetchResponse({ status: FetchResponse.StatusCode.ERROR, data: errmsg }) + response = { status: FetchResponse.StatusCode.ERROR, data: errmsg } } - shake.write(lp.encode.single(FetchResponse.encode(response).finish()).slice()) + shake.write(lp.encode.single(FetchResponse.encode(response)).slice()) } /** diff --git a/src/fetch/pb/proto.d.ts b/src/fetch/pb/proto.d.ts deleted file mode 100644 index bf022f51..00000000 --- a/src/fetch/pb/proto.d.ts +++ /dev/null @@ -1,134 +0,0 @@ -import * as $protobuf from "protobufjs"; -/** Properties of a FetchRequest. */ -export interface IFetchRequest { - - /** FetchRequest identifier */ - identifier?: (string|null); -} - -/** Represents a FetchRequest. */ -export class FetchRequest implements IFetchRequest { - - /** - * Constructs a new FetchRequest. - * @param [p] Properties to set - */ - constructor(p?: IFetchRequest); - - /** FetchRequest identifier. */ - public identifier: string; - - /** - * Encodes the specified FetchRequest message. Does not implicitly {@link FetchRequest.verify|verify} messages. - * @param m FetchRequest message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: IFetchRequest, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FetchRequest message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns FetchRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): FetchRequest; - - /** - * Creates a FetchRequest message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns FetchRequest - */ - public static fromObject(d: { [k: string]: any }): FetchRequest; - - /** - * Creates a plain object from a FetchRequest message. Also converts values to other types if specified. - * @param m FetchRequest - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: FetchRequest, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FetchRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; -} - -/** Properties of a FetchResponse. */ -export interface IFetchResponse { - - /** FetchResponse status */ - status?: (FetchResponse.StatusCode|null); - - /** FetchResponse data */ - data?: (Uint8Array|null); -} - -/** Represents a FetchResponse. */ -export class FetchResponse implements IFetchResponse { - - /** - * Constructs a new FetchResponse. - * @param [p] Properties to set - */ - constructor(p?: IFetchResponse); - - /** FetchResponse status. */ - public status: FetchResponse.StatusCode; - - /** FetchResponse data. */ - public data: Uint8Array; - - /** - * Encodes the specified FetchResponse message. Does not implicitly {@link FetchResponse.verify|verify} messages. - * @param m FetchResponse message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: IFetchResponse, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FetchResponse message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns FetchResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): FetchResponse; - - /** - * Creates a FetchResponse message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns FetchResponse - */ - public static fromObject(d: { [k: string]: any }): FetchResponse; - - /** - * Creates a plain object from a FetchResponse message. Also converts values to other types if specified. - * @param m FetchResponse - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: FetchResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FetchResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; -} - -export namespace FetchResponse { - - /** StatusCode enum. */ - enum StatusCode { - OK = 0, - NOT_FOUND = 1, - ERROR = 2 - } -} diff --git a/src/fetch/pb/proto.js b/src/fetch/pb/proto.js deleted file mode 100644 index b77d6375..00000000 --- a/src/fetch/pb/proto.js +++ /dev/null @@ -1,331 +0,0 @@ -/*eslint-disable*/ -import $protobuf from "protobufjs/minimal.js"; - -// Common aliases -const $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -const $root = $protobuf.roots["libp2p-fetch"] || ($protobuf.roots["libp2p-fetch"] = {}); - -export const FetchRequest = $root.FetchRequest = (() => { - - /** - * Properties of a FetchRequest. - * @exports IFetchRequest - * @interface IFetchRequest - * @property {string|null} [identifier] FetchRequest identifier - */ - - /** - * Constructs a new FetchRequest. - * @exports FetchRequest - * @classdesc Represents a FetchRequest. - * @implements IFetchRequest - * @constructor - * @param {IFetchRequest=} [p] Properties to set - */ - function FetchRequest(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * FetchRequest identifier. - * @member {string} identifier - * @memberof FetchRequest - * @instance - */ - FetchRequest.prototype.identifier = ""; - - /** - * Encodes the specified FetchRequest message. Does not implicitly {@link FetchRequest.verify|verify} messages. - * @function encode - * @memberof FetchRequest - * @static - * @param {IFetchRequest} m FetchRequest message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FetchRequest.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.identifier != null && Object.hasOwnProperty.call(m, "identifier")) - w.uint32(10).string(m.identifier); - return w; - }; - - /** - * Decodes a FetchRequest message from the specified reader or buffer. - * @function decode - * @memberof FetchRequest - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {FetchRequest} FetchRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FetchRequest.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.FetchRequest(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.identifier = r.string(); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - - /** - * Creates a FetchRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof FetchRequest - * @static - * @param {Object.} d Plain object - * @returns {FetchRequest} FetchRequest - */ - FetchRequest.fromObject = function fromObject(d) { - if (d instanceof $root.FetchRequest) - return d; - var m = new $root.FetchRequest(); - if (d.identifier != null) { - m.identifier = String(d.identifier); - } - return m; - }; - - /** - * Creates a plain object from a FetchRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof FetchRequest - * @static - * @param {FetchRequest} m FetchRequest - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - FetchRequest.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.defaults) { - d.identifier = ""; - } - if (m.identifier != null && m.hasOwnProperty("identifier")) { - d.identifier = m.identifier; - } - return d; - }; - - /** - * Converts this FetchRequest to JSON. - * @function toJSON - * @memberof FetchRequest - * @instance - * @returns {Object.} JSON object - */ - FetchRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return FetchRequest; -})(); - -export const FetchResponse = $root.FetchResponse = (() => { - - /** - * Properties of a FetchResponse. - * @exports IFetchResponse - * @interface IFetchResponse - * @property {FetchResponse.StatusCode|null} [status] FetchResponse status - * @property {Uint8Array|null} [data] FetchResponse data - */ - - /** - * Constructs a new FetchResponse. - * @exports FetchResponse - * @classdesc Represents a FetchResponse. - * @implements IFetchResponse - * @constructor - * @param {IFetchResponse=} [p] Properties to set - */ - function FetchResponse(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * FetchResponse status. - * @member {FetchResponse.StatusCode} status - * @memberof FetchResponse - * @instance - */ - FetchResponse.prototype.status = 0; - - /** - * FetchResponse data. - * @member {Uint8Array} data - * @memberof FetchResponse - * @instance - */ - FetchResponse.prototype.data = $util.newBuffer([]); - - /** - * Encodes the specified FetchResponse message. Does not implicitly {@link FetchResponse.verify|verify} messages. - * @function encode - * @memberof FetchResponse - * @static - * @param {IFetchResponse} m FetchResponse message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FetchResponse.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.status != null && Object.hasOwnProperty.call(m, "status")) - w.uint32(8).int32(m.status); - if (m.data != null && Object.hasOwnProperty.call(m, "data")) - w.uint32(18).bytes(m.data); - return w; - }; - - /** - * Decodes a FetchResponse message from the specified reader or buffer. - * @function decode - * @memberof FetchResponse - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {FetchResponse} FetchResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FetchResponse.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.FetchResponse(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.status = r.int32(); - break; - case 2: - m.data = r.bytes(); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - - /** - * Creates a FetchResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof FetchResponse - * @static - * @param {Object.} d Plain object - * @returns {FetchResponse} FetchResponse - */ - FetchResponse.fromObject = function fromObject(d) { - if (d instanceof $root.FetchResponse) - return d; - var m = new $root.FetchResponse(); - switch (d.status) { - case "OK": - case 0: - m.status = 0; - break; - case "NOT_FOUND": - case 1: - m.status = 1; - break; - case "ERROR": - case 2: - m.status = 2; - break; - } - if (d.data != null) { - if (typeof d.data === "string") - $util.base64.decode(d.data, m.data = $util.newBuffer($util.base64.length(d.data)), 0); - else if (d.data.length) - m.data = d.data; - } - return m; - }; - - /** - * Creates a plain object from a FetchResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof FetchResponse - * @static - * @param {FetchResponse} m FetchResponse - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - FetchResponse.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.defaults) { - d.status = o.enums === String ? "OK" : 0; - if (o.bytes === String) - d.data = ""; - else { - d.data = []; - if (o.bytes !== Array) - d.data = $util.newBuffer(d.data); - } - } - if (m.status != null && m.hasOwnProperty("status")) { - d.status = o.enums === String ? $root.FetchResponse.StatusCode[m.status] : m.status; - } - if (m.data != null && m.hasOwnProperty("data")) { - d.data = o.bytes === String ? $util.base64.encode(m.data, 0, m.data.length) : o.bytes === Array ? Array.prototype.slice.call(m.data) : m.data; - } - return d; - }; - - /** - * Converts this FetchResponse to JSON. - * @function toJSON - * @memberof FetchResponse - * @instance - * @returns {Object.} JSON object - */ - FetchResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * StatusCode enum. - * @name FetchResponse.StatusCode - * @enum {number} - * @property {number} OK=0 OK value - * @property {number} NOT_FOUND=1 NOT_FOUND value - * @property {number} ERROR=2 ERROR value - */ - FetchResponse.StatusCode = (function() { - const valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OK"] = 0; - values[valuesById[1] = "NOT_FOUND"] = 1; - values[valuesById[2] = "ERROR"] = 2; - return values; - })(); - - return FetchResponse; -})(); - -export { $root as default }; diff --git a/src/fetch/pb/proto.ts b/src/fetch/pb/proto.ts new file mode 100644 index 00000000..b6c112ef --- /dev/null +++ b/src/fetch/pb/proto.ts @@ -0,0 +1,58 @@ +/* eslint-disable import/export */ +/* eslint-disable @typescript-eslint/no-namespace */ + +import { encodeMessage, decodeMessage, message, string, enumeration, bytes } from 'protons-runtime' + +export interface FetchRequest { + identifier: string +} + +export namespace FetchRequest { + export const codec = () => { + return message({ + 1: { name: 'identifier', codec: string } + }) + } + + export const encode = (obj: FetchRequest): Uint8Array => { + return encodeMessage(obj, FetchRequest.codec()) + } + + export const decode = (buf: Uint8Array): FetchRequest => { + return decodeMessage(buf, FetchRequest.codec()) + } +} + +export interface FetchResponse { + status: FetchResponse.StatusCode + data: Uint8Array +} + +export namespace FetchResponse { + export enum StatusCode { + OK = 'OK', + NOT_FOUND = 'NOT_FOUND', + ERROR = 'ERROR' + } + + export namespace StatusCode { + export const codec = () => { + return enumeration(StatusCode) + } + } + + export const codec = () => { + return message({ + 1: { name: 'status', codec: FetchResponse.StatusCode.codec() }, + 2: { name: 'data', codec: bytes } + }) + } + + export const encode = (obj: FetchResponse): Uint8Array => { + return encodeMessage(obj, FetchResponse.codec()) + } + + export const decode = (buf: Uint8Array): FetchResponse => { + return decodeMessage(buf, FetchResponse.codec()) + } +} diff --git a/src/identify/index.ts b/src/identify/index.ts index bfd3b033..5cbc4484 100644 --- a/src/identify/index.ts +++ b/src/identify/index.ts @@ -8,7 +8,7 @@ import drain from 'it-drain' import first from 'it-first' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import { Multiaddr, protocols } from '@multiformats/multiaddr' -import Message from './pb/message.js' +import { Identify } from './pb/message.js' import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record' import { MULTICODEC_IDENTIFY, @@ -132,11 +132,11 @@ export class IdentifyService implements Startable { const { stream } = await connection.newStream([this.identifyPushProtocolStr]) await pipe( - [Message.Identify.encode({ + [Identify.encode({ listenAddrs, signedPeerRecord, protocols - }).finish()], + })], lp.encode(), stream, drain @@ -194,9 +194,9 @@ export class IdentifyService implements Startable { throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED) } - let message + let message: Identify try { - message = Message.Identify.decode(data) + message = Identify.decode(data) } catch (err: any) { throw errCode(err, codes.ERR_INVALID_MESSAGE) } @@ -325,7 +325,7 @@ export class IdentifyService implements Startable { signedPeerRecord = envelope.marshal() } - const message = Message.Identify.encode({ + const message = Identify.encode({ protocolVersion: this.host.protocolVersion, agentVersion: this.host.agentVersion, publicKey, @@ -333,7 +333,7 @@ export class IdentifyService implements Startable { signedPeerRecord, observedAddr: connection.remoteAddr.bytes, protocols: peerData.protocols - }).finish() + }) await pipe( [message], @@ -352,7 +352,7 @@ export class IdentifyService implements Startable { async _handlePush (data: IncomingStreamData) { const { connection, stream } = data - let message + let message: Identify | undefined try { const data = await pipe( [], @@ -362,7 +362,7 @@ export class IdentifyService implements Startable { ) if (data != null) { - message = Message.Identify.decode(data) + message = Identify.decode(data) } } catch (err: any) { return log.error('received invalid message', err) @@ -442,4 +442,4 @@ export const multicodecs = { IDENTIFY_PUSH: MULTICODEC_IDENTIFY_PUSH } -export { Message } +export const Message = { Identify } diff --git a/src/identify/pb/message.d.ts b/src/identify/pb/message.d.ts deleted file mode 100644 index 561dbc55..00000000 --- a/src/identify/pb/message.d.ts +++ /dev/null @@ -1,110 +0,0 @@ -import * as $protobuf from "protobufjs"; -/** Properties of an Identify. */ -export interface IIdentify { - - /** Identify protocolVersion */ - protocolVersion?: (string|null); - - /** Identify agentVersion */ - agentVersion?: (string|null); - - /** Identify publicKey */ - publicKey?: (Uint8Array|null); - - /** Identify listenAddrs */ - listenAddrs?: (Uint8Array[]|null); - - /** Identify observedAddr */ - observedAddr?: (Uint8Array|null); - - /** Identify protocols */ - protocols?: (string[]|null); - - /** Identify signedPeerRecord */ - signedPeerRecord?: (Uint8Array|null); -} - -/** Represents an Identify. */ -export class Identify implements IIdentify { - - /** - * Constructs a new Identify. - * @param [p] Properties to set - */ - constructor(p?: IIdentify); - - /** Identify protocolVersion. */ - public protocolVersion?: (string|null); - - /** Identify agentVersion. */ - public agentVersion?: (string|null); - - /** Identify publicKey. */ - public publicKey?: (Uint8Array|null); - - /** Identify listenAddrs. */ - public listenAddrs: Uint8Array[]; - - /** Identify observedAddr. */ - public observedAddr?: (Uint8Array|null); - - /** Identify protocols. */ - public protocols: string[]; - - /** Identify signedPeerRecord. */ - public signedPeerRecord?: (Uint8Array|null); - - /** Identify _protocolVersion. */ - public _protocolVersion?: "protocolVersion"; - - /** Identify _agentVersion. */ - public _agentVersion?: "agentVersion"; - - /** Identify _publicKey. */ - public _publicKey?: "publicKey"; - - /** Identify _observedAddr. */ - public _observedAddr?: "observedAddr"; - - /** Identify _signedPeerRecord. */ - public _signedPeerRecord?: "signedPeerRecord"; - - /** - * Encodes the specified Identify message. Does not implicitly {@link Identify.verify|verify} messages. - * @param m Identify message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: IIdentify, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Identify message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns Identify - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Identify; - - /** - * Creates an Identify message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns Identify - */ - public static fromObject(d: { [k: string]: any }): Identify; - - /** - * Creates a plain object from an Identify message. Also converts values to other types if specified. - * @param m Identify - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: Identify, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Identify to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; -} diff --git a/src/identify/pb/message.js b/src/identify/pb/message.js deleted file mode 100644 index 80764cad..00000000 --- a/src/identify/pb/message.js +++ /dev/null @@ -1,369 +0,0 @@ -/*eslint-disable*/ -import $protobuf from "protobufjs/minimal.js"; - -// Common aliases -const $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -const $root = $protobuf.roots["libp2p-identify"] || ($protobuf.roots["libp2p-identify"] = {}); - -export const Identify = $root.Identify = (() => { - - /** - * Properties of an Identify. - * @exports IIdentify - * @interface IIdentify - * @property {string|null} [protocolVersion] Identify protocolVersion - * @property {string|null} [agentVersion] Identify agentVersion - * @property {Uint8Array|null} [publicKey] Identify publicKey - * @property {Array.|null} [listenAddrs] Identify listenAddrs - * @property {Uint8Array|null} [observedAddr] Identify observedAddr - * @property {Array.|null} [protocols] Identify protocols - * @property {Uint8Array|null} [signedPeerRecord] Identify signedPeerRecord - */ - - /** - * Constructs a new Identify. - * @exports Identify - * @classdesc Represents an Identify. - * @implements IIdentify - * @constructor - * @param {IIdentify=} [p] Properties to set - */ - function Identify(p) { - this.listenAddrs = []; - this.protocols = []; - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * Identify protocolVersion. - * @member {string|null|undefined} protocolVersion - * @memberof Identify - * @instance - */ - Identify.prototype.protocolVersion = null; - - /** - * Identify agentVersion. - * @member {string|null|undefined} agentVersion - * @memberof Identify - * @instance - */ - Identify.prototype.agentVersion = null; - - /** - * Identify publicKey. - * @member {Uint8Array|null|undefined} publicKey - * @memberof Identify - * @instance - */ - Identify.prototype.publicKey = null; - - /** - * Identify listenAddrs. - * @member {Array.} listenAddrs - * @memberof Identify - * @instance - */ - Identify.prototype.listenAddrs = $util.emptyArray; - - /** - * Identify observedAddr. - * @member {Uint8Array|null|undefined} observedAddr - * @memberof Identify - * @instance - */ - Identify.prototype.observedAddr = null; - - /** - * Identify protocols. - * @member {Array.} protocols - * @memberof Identify - * @instance - */ - Identify.prototype.protocols = $util.emptyArray; - - /** - * Identify signedPeerRecord. - * @member {Uint8Array|null|undefined} signedPeerRecord - * @memberof Identify - * @instance - */ - Identify.prototype.signedPeerRecord = null; - - // OneOf field names bound to virtual getters and setters - let $oneOfFields; - - /** - * Identify _protocolVersion. - * @member {"protocolVersion"|undefined} _protocolVersion - * @memberof Identify - * @instance - */ - Object.defineProperty(Identify.prototype, "_protocolVersion", { - get: $util.oneOfGetter($oneOfFields = ["protocolVersion"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Identify _agentVersion. - * @member {"agentVersion"|undefined} _agentVersion - * @memberof Identify - * @instance - */ - Object.defineProperty(Identify.prototype, "_agentVersion", { - get: $util.oneOfGetter($oneOfFields = ["agentVersion"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Identify _publicKey. - * @member {"publicKey"|undefined} _publicKey - * @memberof Identify - * @instance - */ - Object.defineProperty(Identify.prototype, "_publicKey", { - get: $util.oneOfGetter($oneOfFields = ["publicKey"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Identify _observedAddr. - * @member {"observedAddr"|undefined} _observedAddr - * @memberof Identify - * @instance - */ - Object.defineProperty(Identify.prototype, "_observedAddr", { - get: $util.oneOfGetter($oneOfFields = ["observedAddr"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Identify _signedPeerRecord. - * @member {"signedPeerRecord"|undefined} _signedPeerRecord - * @memberof Identify - * @instance - */ - Object.defineProperty(Identify.prototype, "_signedPeerRecord", { - get: $util.oneOfGetter($oneOfFields = ["signedPeerRecord"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Encodes the specified Identify message. Does not implicitly {@link Identify.verify|verify} messages. - * @function encode - * @memberof Identify - * @static - * @param {IIdentify} m Identify message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Identify.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.publicKey != null && Object.hasOwnProperty.call(m, "publicKey")) - w.uint32(10).bytes(m.publicKey); - if (m.listenAddrs != null && m.listenAddrs.length) { - for (var i = 0; i < m.listenAddrs.length; ++i) - w.uint32(18).bytes(m.listenAddrs[i]); - } - if (m.protocols != null && m.protocols.length) { - for (var i = 0; i < m.protocols.length; ++i) - w.uint32(26).string(m.protocols[i]); - } - if (m.observedAddr != null && Object.hasOwnProperty.call(m, "observedAddr")) - w.uint32(34).bytes(m.observedAddr); - if (m.protocolVersion != null && Object.hasOwnProperty.call(m, "protocolVersion")) - w.uint32(42).string(m.protocolVersion); - if (m.agentVersion != null && Object.hasOwnProperty.call(m, "agentVersion")) - w.uint32(50).string(m.agentVersion); - if (m.signedPeerRecord != null && Object.hasOwnProperty.call(m, "signedPeerRecord")) - w.uint32(66).bytes(m.signedPeerRecord); - return w; - }; - - /** - * Decodes an Identify message from the specified reader or buffer. - * @function decode - * @memberof Identify - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {Identify} Identify - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Identify.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.Identify(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 5: - m.protocolVersion = r.string(); - break; - case 6: - m.agentVersion = r.string(); - break; - case 1: - m.publicKey = r.bytes(); - break; - case 2: - if (!(m.listenAddrs && m.listenAddrs.length)) - m.listenAddrs = []; - m.listenAddrs.push(r.bytes()); - break; - case 4: - m.observedAddr = r.bytes(); - break; - case 3: - if (!(m.protocols && m.protocols.length)) - m.protocols = []; - m.protocols.push(r.string()); - break; - case 8: - m.signedPeerRecord = r.bytes(); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - - /** - * Creates an Identify message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof Identify - * @static - * @param {Object.} d Plain object - * @returns {Identify} Identify - */ - Identify.fromObject = function fromObject(d) { - if (d instanceof $root.Identify) - return d; - var m = new $root.Identify(); - if (d.protocolVersion != null) { - m.protocolVersion = String(d.protocolVersion); - } - if (d.agentVersion != null) { - m.agentVersion = String(d.agentVersion); - } - if (d.publicKey != null) { - if (typeof d.publicKey === "string") - $util.base64.decode(d.publicKey, m.publicKey = $util.newBuffer($util.base64.length(d.publicKey)), 0); - else if (d.publicKey.length) - m.publicKey = d.publicKey; - } - if (d.listenAddrs) { - if (!Array.isArray(d.listenAddrs)) - throw TypeError(".Identify.listenAddrs: array expected"); - m.listenAddrs = []; - for (var i = 0; i < d.listenAddrs.length; ++i) { - if (typeof d.listenAddrs[i] === "string") - $util.base64.decode(d.listenAddrs[i], m.listenAddrs[i] = $util.newBuffer($util.base64.length(d.listenAddrs[i])), 0); - else if (d.listenAddrs[i].length) - m.listenAddrs[i] = d.listenAddrs[i]; - } - } - if (d.observedAddr != null) { - if (typeof d.observedAddr === "string") - $util.base64.decode(d.observedAddr, m.observedAddr = $util.newBuffer($util.base64.length(d.observedAddr)), 0); - else if (d.observedAddr.length) - m.observedAddr = d.observedAddr; - } - if (d.protocols) { - if (!Array.isArray(d.protocols)) - throw TypeError(".Identify.protocols: array expected"); - m.protocols = []; - for (var i = 0; i < d.protocols.length; ++i) { - m.protocols[i] = String(d.protocols[i]); - } - } - if (d.signedPeerRecord != null) { - if (typeof d.signedPeerRecord === "string") - $util.base64.decode(d.signedPeerRecord, m.signedPeerRecord = $util.newBuffer($util.base64.length(d.signedPeerRecord)), 0); - else if (d.signedPeerRecord.length) - m.signedPeerRecord = d.signedPeerRecord; - } - return m; - }; - - /** - * Creates a plain object from an Identify message. Also converts values to other types if specified. - * @function toObject - * @memberof Identify - * @static - * @param {Identify} m Identify - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - Identify.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.arrays || o.defaults) { - d.listenAddrs = []; - d.protocols = []; - } - if (m.publicKey != null && m.hasOwnProperty("publicKey")) { - d.publicKey = o.bytes === String ? $util.base64.encode(m.publicKey, 0, m.publicKey.length) : o.bytes === Array ? Array.prototype.slice.call(m.publicKey) : m.publicKey; - if (o.oneofs) - d._publicKey = "publicKey"; - } - if (m.listenAddrs && m.listenAddrs.length) { - d.listenAddrs = []; - for (var j = 0; j < m.listenAddrs.length; ++j) { - d.listenAddrs[j] = o.bytes === String ? $util.base64.encode(m.listenAddrs[j], 0, m.listenAddrs[j].length) : o.bytes === Array ? Array.prototype.slice.call(m.listenAddrs[j]) : m.listenAddrs[j]; - } - } - if (m.protocols && m.protocols.length) { - d.protocols = []; - for (var j = 0; j < m.protocols.length; ++j) { - d.protocols[j] = m.protocols[j]; - } - } - if (m.observedAddr != null && m.hasOwnProperty("observedAddr")) { - d.observedAddr = o.bytes === String ? $util.base64.encode(m.observedAddr, 0, m.observedAddr.length) : o.bytes === Array ? Array.prototype.slice.call(m.observedAddr) : m.observedAddr; - if (o.oneofs) - d._observedAddr = "observedAddr"; - } - if (m.protocolVersion != null && m.hasOwnProperty("protocolVersion")) { - d.protocolVersion = m.protocolVersion; - if (o.oneofs) - d._protocolVersion = "protocolVersion"; - } - if (m.agentVersion != null && m.hasOwnProperty("agentVersion")) { - d.agentVersion = m.agentVersion; - if (o.oneofs) - d._agentVersion = "agentVersion"; - } - if (m.signedPeerRecord != null && m.hasOwnProperty("signedPeerRecord")) { - d.signedPeerRecord = o.bytes === String ? $util.base64.encode(m.signedPeerRecord, 0, m.signedPeerRecord.length) : o.bytes === Array ? Array.prototype.slice.call(m.signedPeerRecord) : m.signedPeerRecord; - if (o.oneofs) - d._signedPeerRecord = "signedPeerRecord"; - } - return d; - }; - - /** - * Converts this Identify to JSON. - * @function toJSON - * @memberof Identify - * @instance - * @returns {Object.} JSON object - */ - Identify.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Identify; -})(); - -export { $root as default }; diff --git a/src/identify/pb/message.ts b/src/identify/pb/message.ts new file mode 100644 index 00000000..72701356 --- /dev/null +++ b/src/identify/pb/message.ts @@ -0,0 +1,36 @@ +/* eslint-disable import/export */ +/* eslint-disable @typescript-eslint/no-namespace */ + +import { encodeMessage, decodeMessage, message, string, bytes } from 'protons-runtime' + +export interface Identify { + protocolVersion?: string + agentVersion?: string + publicKey?: Uint8Array + listenAddrs: Uint8Array[] + observedAddr?: Uint8Array + protocols: string[] + signedPeerRecord?: Uint8Array +} + +export namespace Identify { + export const codec = () => { + return message({ + 5: { name: 'protocolVersion', codec: string, optional: true }, + 6: { name: 'agentVersion', codec: string, optional: true }, + 1: { name: 'publicKey', codec: bytes, optional: true }, + 2: { name: 'listenAddrs', codec: bytes, repeats: true }, + 4: { name: 'observedAddr', codec: bytes, optional: true }, + 3: { name: 'protocols', codec: string, repeats: true }, + 8: { name: 'signedPeerRecord', codec: bytes, optional: true } + }) + } + + export const encode = (obj: Identify): Uint8Array => { + return encodeMessage(obj, Identify.codec()) + } + + export const decode = (buf: Uint8Array): Identify => { + return decodeMessage(buf, Identify.codec()) + } +} diff --git a/src/insecure/index.ts b/src/insecure/index.ts index 3c941bef..76dc0ca3 100644 --- a/src/insecure/index.ts +++ b/src/insecure/index.ts @@ -2,7 +2,7 @@ import { logger } from '@libp2p/logger' import { handshake } from 'it-handshake' import * as lp from 'it-length-prefixed' import { UnexpectedPeerError, InvalidCryptoExchangeError } from '@libp2p/interfaces/connection-encrypter/errors' -import { Exchange, IExchange, KeyType } from './pb/proto.js' +import { Exchange, KeyType } from './pb/proto.js' import type { PeerId } from '@libp2p/interfaces/peer-id' import { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id' import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interfaces/connection-encrypter' @@ -11,8 +11,8 @@ import type { Duplex } from 'it-stream-types' const log = logger('libp2p:plaintext') const PROTOCOL = '/plaintext/2.0.0' -function lpEncodeExchange (exchange: IExchange) { - const pb = Exchange.encode(exchange).finish() +function lpEncodeExchange (exchange: Exchange) { + const pb = Exchange.encode(exchange) return lp.encode.single(pb) } @@ -37,7 +37,7 @@ async function encrypt (localId: PeerId, conn: Duplex, remoteId?: Pe id: localId.toBytes(), pubkey: { Type: type, - Data: localId.publicKey + Data: localId.publicKey ?? new Uint8Array(0) } }).slice() ) @@ -52,6 +52,10 @@ async function encrypt (localId: PeerId, conn: Duplex, remoteId?: Pe let peerId try { + if (id.pubkey == null) { + throw new Error('Public key missing') + } + if (id.pubkey.Data.length === 0) { throw new Error('Public key data too short') } diff --git a/src/insecure/pb/proto.d.ts b/src/insecure/pb/proto.d.ts deleted file mode 100644 index 191c8669..00000000 --- a/src/insecure/pb/proto.d.ts +++ /dev/null @@ -1,134 +0,0 @@ -import * as $protobuf from "protobufjs"; -/** Properties of an Exchange. */ -export interface IExchange { - - /** Exchange id */ - id?: (Uint8Array|null); - - /** Exchange pubkey */ - pubkey?: (IPublicKey|null); -} - -/** Represents an Exchange. */ -export class Exchange implements IExchange { - - /** - * Constructs a new Exchange. - * @param [p] Properties to set - */ - constructor(p?: IExchange); - - /** Exchange id. */ - public id?: (Uint8Array|null); - - /** Exchange pubkey. */ - public pubkey?: (IPublicKey|null); - - /** Exchange _id. */ - public _id?: "id"; - - /** Exchange _pubkey. */ - public _pubkey?: "pubkey"; - - /** - * Encodes the specified Exchange message. Does not implicitly {@link Exchange.verify|verify} messages. - * @param m Exchange message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: IExchange, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Exchange message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns Exchange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): Exchange; - - /** - * Creates an Exchange message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns Exchange - */ - public static fromObject(d: { [k: string]: any }): Exchange; - - /** - * Creates a plain object from an Exchange message. Also converts values to other types if specified. - * @param m Exchange - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: Exchange, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Exchange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; -} - -/** KeyType enum. */ -export enum KeyType { - RSA = 0, - Ed25519 = 1, - Secp256k1 = 2, - ECDSA = 3 -} - -/** Represents a PublicKey. */ -export class PublicKey implements IPublicKey { - - /** - * Constructs a new PublicKey. - * @param [p] Properties to set - */ - constructor(p?: IPublicKey); - - /** PublicKey Type. */ - public Type: KeyType; - - /** PublicKey Data. */ - public Data: Uint8Array; - - /** - * Encodes the specified PublicKey message. Does not implicitly {@link PublicKey.verify|verify} messages. - * @param m PublicKey message or plain object to encode - * @param [w] Writer to encode to - * @returns Writer - */ - public static encode(m: IPublicKey, w?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a PublicKey message from the specified reader or buffer. - * @param r Reader or buffer to decode from - * @param [l] Message length if known beforehand - * @returns PublicKey - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): PublicKey; - - /** - * Creates a PublicKey message from a plain object. Also converts values to their respective internal types. - * @param d Plain object - * @returns PublicKey - */ - public static fromObject(d: { [k: string]: any }): PublicKey; - - /** - * Creates a plain object from a PublicKey message. Also converts values to other types if specified. - * @param m PublicKey - * @param [o] Conversion options - * @returns Plain object - */ - public static toObject(m: PublicKey, o?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this PublicKey to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; -} diff --git a/src/insecure/pb/proto.js b/src/insecure/pb/proto.js deleted file mode 100644 index 54fa39cf..00000000 --- a/src/insecure/pb/proto.js +++ /dev/null @@ -1,388 +0,0 @@ -/*eslint-disable*/ -import $protobuf from "protobufjs/minimal.js"; - -// Common aliases -const $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -const $root = $protobuf.roots["libp2p-plaintext"] || ($protobuf.roots["libp2p-plaintext"] = {}); - -export const Exchange = $root.Exchange = (() => { - - /** - * Properties of an Exchange. - * @exports IExchange - * @interface IExchange - * @property {Uint8Array|null} [id] Exchange id - * @property {IPublicKey|null} [pubkey] Exchange pubkey - */ - - /** - * Constructs a new Exchange. - * @exports Exchange - * @classdesc Represents an Exchange. - * @implements IExchange - * @constructor - * @param {IExchange=} [p] Properties to set - */ - function Exchange(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * Exchange id. - * @member {Uint8Array|null|undefined} id - * @memberof Exchange - * @instance - */ - Exchange.prototype.id = null; - - /** - * Exchange pubkey. - * @member {IPublicKey|null|undefined} pubkey - * @memberof Exchange - * @instance - */ - Exchange.prototype.pubkey = null; - - // OneOf field names bound to virtual getters and setters - let $oneOfFields; - - /** - * Exchange _id. - * @member {"id"|undefined} _id - * @memberof Exchange - * @instance - */ - Object.defineProperty(Exchange.prototype, "_id", { - get: $util.oneOfGetter($oneOfFields = ["id"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Exchange _pubkey. - * @member {"pubkey"|undefined} _pubkey - * @memberof Exchange - * @instance - */ - Object.defineProperty(Exchange.prototype, "_pubkey", { - get: $util.oneOfGetter($oneOfFields = ["pubkey"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Encodes the specified Exchange message. Does not implicitly {@link Exchange.verify|verify} messages. - * @function encode - * @memberof Exchange - * @static - * @param {IExchange} m Exchange message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Exchange.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.id != null && Object.hasOwnProperty.call(m, "id")) - w.uint32(10).bytes(m.id); - if (m.pubkey != null && Object.hasOwnProperty.call(m, "pubkey")) - $root.PublicKey.encode(m.pubkey, w.uint32(18).fork()).ldelim(); - return w; - }; - - /** - * Decodes an Exchange message from the specified reader or buffer. - * @function decode - * @memberof Exchange - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {Exchange} Exchange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Exchange.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.Exchange(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.id = r.bytes(); - break; - case 2: - m.pubkey = $root.PublicKey.decode(r, r.uint32()); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - - /** - * Creates an Exchange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof Exchange - * @static - * @param {Object.} d Plain object - * @returns {Exchange} Exchange - */ - Exchange.fromObject = function fromObject(d) { - if (d instanceof $root.Exchange) - return d; - var m = new $root.Exchange(); - if (d.id != null) { - if (typeof d.id === "string") - $util.base64.decode(d.id, m.id = $util.newBuffer($util.base64.length(d.id)), 0); - else if (d.id.length) - m.id = d.id; - } - if (d.pubkey != null) { - if (typeof d.pubkey !== "object") - throw TypeError(".Exchange.pubkey: object expected"); - m.pubkey = $root.PublicKey.fromObject(d.pubkey); - } - return m; - }; - - /** - * Creates a plain object from an Exchange message. Also converts values to other types if specified. - * @function toObject - * @memberof Exchange - * @static - * @param {Exchange} m Exchange - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - Exchange.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (m.id != null && m.hasOwnProperty("id")) { - d.id = o.bytes === String ? $util.base64.encode(m.id, 0, m.id.length) : o.bytes === Array ? Array.prototype.slice.call(m.id) : m.id; - if (o.oneofs) - d._id = "id"; - } - if (m.pubkey != null && m.hasOwnProperty("pubkey")) { - d.pubkey = $root.PublicKey.toObject(m.pubkey, o); - if (o.oneofs) - d._pubkey = "pubkey"; - } - return d; - }; - - /** - * Converts this Exchange to JSON. - * @function toJSON - * @memberof Exchange - * @instance - * @returns {Object.} JSON object - */ - Exchange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Exchange; -})(); - -/** - * KeyType enum. - * @exports KeyType - * @enum {number} - * @property {number} RSA=0 RSA value - * @property {number} Ed25519=1 Ed25519 value - * @property {number} Secp256k1=2 Secp256k1 value - * @property {number} ECDSA=3 ECDSA value - */ -export const KeyType = $root.KeyType = (() => { - const valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "RSA"] = 0; - values[valuesById[1] = "Ed25519"] = 1; - values[valuesById[2] = "Secp256k1"] = 2; - values[valuesById[3] = "ECDSA"] = 3; - return values; -})(); - -export const PublicKey = $root.PublicKey = (() => { - - /** - * Properties of a PublicKey. - * @exports IPublicKey - * @interface IPublicKey - * @property {KeyType|null} [Type] PublicKey Type - * @property {Uint8Array|null} [Data] PublicKey Data - */ - - /** - * Constructs a new PublicKey. - * @exports PublicKey - * @classdesc Represents a PublicKey. - * @implements IPublicKey - * @constructor - * @param {IPublicKey=} [p] Properties to set - */ - function PublicKey(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - - /** - * PublicKey Type. - * @member {KeyType} Type - * @memberof PublicKey - * @instance - */ - PublicKey.prototype.Type = 0; - - /** - * PublicKey Data. - * @member {Uint8Array} Data - * @memberof PublicKey - * @instance - */ - PublicKey.prototype.Data = $util.newBuffer([]); - - /** - * Encodes the specified PublicKey message. Does not implicitly {@link PublicKey.verify|verify} messages. - * @function encode - * @memberof PublicKey - * @static - * @param {IPublicKey} m PublicKey message or plain object to encode - * @param {$protobuf.Writer} [w] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - PublicKey.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.Type != null && Object.hasOwnProperty.call(m, "Type")) - w.uint32(8).int32(m.Type); - if (m.Data != null && Object.hasOwnProperty.call(m, "Data")) - w.uint32(18).bytes(m.Data); - return w; - }; - - /** - * Decodes a PublicKey message from the specified reader or buffer. - * @function decode - * @memberof PublicKey - * @static - * @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from - * @param {number} [l] Message length if known beforehand - * @returns {PublicKey} PublicKey - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - PublicKey.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.PublicKey(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.Type = r.int32(); - break; - case 2: - m.Data = r.bytes(); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - - /** - * Creates a PublicKey message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof PublicKey - * @static - * @param {Object.} d Plain object - * @returns {PublicKey} PublicKey - */ - PublicKey.fromObject = function fromObject(d) { - if (d instanceof $root.PublicKey) - return d; - var m = new $root.PublicKey(); - switch (d.Type) { - case "RSA": - case 0: - m.Type = 0; - break; - case "Ed25519": - case 1: - m.Type = 1; - break; - case "Secp256k1": - case 2: - m.Type = 2; - break; - case "ECDSA": - case 3: - m.Type = 3; - break; - } - if (d.Data != null) { - if (typeof d.Data === "string") - $util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0); - else if (d.Data.length) - m.Data = d.Data; - } - return m; - }; - - /** - * Creates a plain object from a PublicKey message. Also converts values to other types if specified. - * @function toObject - * @memberof PublicKey - * @static - * @param {PublicKey} m PublicKey - * @param {$protobuf.IConversionOptions} [o] Conversion options - * @returns {Object.} Plain object - */ - PublicKey.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.defaults) { - d.Type = o.enums === String ? "RSA" : 0; - if (o.bytes === String) - d.Data = ""; - else { - d.Data = []; - if (o.bytes !== Array) - d.Data = $util.newBuffer(d.Data); - } - } - if (m.Type != null && m.hasOwnProperty("Type")) { - d.Type = o.enums === String ? $root.KeyType[m.Type] : m.Type; - } - if (m.Data != null && m.hasOwnProperty("Data")) { - d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data; - } - return d; - }; - - /** - * Converts this PublicKey to JSON. - * @function toJSON - * @memberof PublicKey - * @instance - * @returns {Object.} JSON object - */ - PublicKey.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return PublicKey; -})(); - -export { $root as default }; diff --git a/src/insecure/pb/proto.ts b/src/insecure/pb/proto.ts new file mode 100644 index 00000000..03909f9e --- /dev/null +++ b/src/insecure/pb/proto.ts @@ -0,0 +1,61 @@ +/* eslint-disable import/export */ +/* eslint-disable @typescript-eslint/no-namespace */ + +import { encodeMessage, decodeMessage, message, bytes, enumeration } from 'protons-runtime' + +export interface Exchange { + id?: Uint8Array + pubkey?: PublicKey +} + +export namespace Exchange { + export const codec = () => { + return message({ + 1: { name: 'id', codec: bytes, optional: true }, + 2: { name: 'pubkey', codec: PublicKey.codec(), optional: true } + }) + } + + export const encode = (obj: Exchange): Uint8Array => { + return encodeMessage(obj, Exchange.codec()) + } + + export const decode = (buf: Uint8Array): Exchange => { + return decodeMessage(buf, Exchange.codec()) + } +} + +export enum KeyType { + RSA = 'RSA', + Ed25519 = 'Ed25519', + Secp256k1 = 'Secp256k1', + ECDSA = 'ECDSA' +} + +export namespace KeyType { + export const codec = () => { + return enumeration(KeyType) + } +} + +export interface PublicKey { + Type: KeyType + Data: Uint8Array +} + +export namespace PublicKey { + export const codec = () => { + return message({ + 1: { name: 'Type', codec: KeyType.codec() }, + 2: { name: 'Data', codec: bytes } + }) + } + + export const encode = (obj: PublicKey): Uint8Array => { + return encodeMessage(obj, PublicKey.codec()) + } + + export const decode = (buf: Uint8Array): PublicKey => { + return decodeMessage(buf, PublicKey.codec()) + } +} diff --git a/src/keychain/index.ts b/src/keychain/index.ts index b95cfb8a..b2b99126 100644 --- a/src/keychain/index.ts +++ b/src/keychain/index.ts @@ -171,7 +171,7 @@ export class KeyChain { /** * Generates the options for a keychain. A random salt is produced. * - * @returns {Object} + * @returns {object} */ static generateOptions (): KeyChainInit { const options = Object.assign({}, defaultOptions) @@ -184,7 +184,7 @@ export class KeyChain { * Gets an object that can encrypt/decrypt protected data. * The default options for a keychain. * - * @returns {Object} + * @returns {object} */ static get options () { return defaultOptions diff --git a/test/addresses/address-manager.spec.ts b/test/addresses/address-manager.spec.ts index a667e6d9..55e5326f 100644 --- a/test/addresses/address-manager.spec.ts +++ b/test/addresses/address-manager.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { Multiaddr, protocols } from '@multiformats/multiaddr' import { AddressFilter, DefaultAddressManager } from '../../src/address-manager/index.js' import { createNode } from '../utils/creators/peer.js' diff --git a/test/addresses/addresses.node.ts b/test/addresses/addresses.node.ts index d656dde8..836a0f11 100644 --- a/test/addresses/addresses.node.ts +++ b/test/addresses/addresses.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { Multiaddr, protocols } from '@multiformats/multiaddr' import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback' diff --git a/test/configuration/protocol-prefix.node.ts b/test/configuration/protocol-prefix.node.ts index 3b9ab32c..a48bbee1 100644 --- a/test/configuration/protocol-prefix.node.ts +++ b/test/configuration/protocol-prefix.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import mergeOptions from 'merge-options' import { validateConfig } from '../../src/config.js' import { createLibp2pNode, Libp2pNode } from '../../src/libp2p.js' diff --git a/test/configuration/pubsub.spec.ts b/test/configuration/pubsub.spec.ts index 762a3fcc..dc20cb5b 100644 --- a/test/configuration/pubsub.spec.ts +++ b/test/configuration/pubsub.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import mergeOptions from 'merge-options' import pDefer from 'p-defer' import delay from 'delay' diff --git a/test/connection-manager/auto-dialler.spec.ts b/test/connection-manager/auto-dialler.spec.ts index 0ed22920..066e535a 100644 --- a/test/connection-manager/auto-dialler.spec.ts +++ b/test/connection-manager/auto-dialler.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { AutoDialler } from '../../src/connection-manager/auto-dialler.js' import pWaitFor from 'p-wait-for' import delay from 'delay' diff --git a/test/connection-manager/index.node.ts b/test/connection-manager/index.node.ts index 6eaacf87..89d69d72 100644 --- a/test/connection-manager/index.node.ts +++ b/test/connection-manager/index.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { createNode, createPeerId } from '../utils/creators/peer.js' import { mockConnection, mockDuplex, mockMultiaddrConnection, mockUpgrader } from '@libp2p/interface-compliance-tests/mocks' import { createBaseOptions } from '../utils/base-options.browser.js' diff --git a/test/connection-manager/index.spec.ts b/test/connection-manager/index.spec.ts index 6f6dba91..85891f7e 100644 --- a/test/connection-manager/index.spec.ts +++ b/test/connection-manager/index.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { createNode } from '../utils/creators/peer.js' import { createBaseOptions } from '../utils/base-options.browser.js' diff --git a/test/content-routing/content-routing.node.ts b/test/content-routing/content-routing.node.ts index 25f429dc..8ced7d6f 100644 --- a/test/content-routing/content-routing.node.ts +++ b/test/content-routing/content-routing.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import nock from 'nock' import sinon from 'sinon' import pDefer from 'p-defer' diff --git a/test/content-routing/dht/configuration.node.ts b/test/content-routing/dht/configuration.node.ts index 57b58c90..26f87e62 100644 --- a/test/content-routing/dht/configuration.node.ts +++ b/test/content-routing/dht/configuration.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { createLibp2p, Libp2p } from '../../../src/index.js' import { createSubsystemOptions } from './utils.js' diff --git a/test/content-routing/dht/operation.node.ts b/test/content-routing/dht/operation.node.ts index e3fa534b..7ec3087e 100644 --- a/test/content-routing/dht/operation.node.ts +++ b/test/content-routing/dht/operation.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { Multiaddr } from '@multiformats/multiaddr' import pWaitFor from 'p-wait-for' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' diff --git a/test/core/encryption.spec.ts b/test/core/encryption.spec.ts index 6d2ac817..a2cca6a5 100644 --- a/test/core/encryption.spec.ts +++ b/test/core/encryption.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { WebSockets } from '@libp2p/websockets' import { NOISE } from '@chainsafe/libp2p-noise' import { createLibp2p, Libp2pOptions } from '../../src/index.js' diff --git a/test/core/listening.node.ts b/test/core/listening.node.ts index 04f81c91..26b0162e 100644 --- a/test/core/listening.node.ts +++ b/test/core/listening.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { TCP } from '@libp2p/tcp' import { NOISE } from '@chainsafe/libp2p-noise' import { createPeerId } from '../utils/creators/peer.js' diff --git a/test/core/ping.node.ts b/test/core/ping.node.ts index 45d5d519..8b64ffba 100644 --- a/test/core/ping.node.ts +++ b/test/core/ping.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import pTimes from 'p-times' import { pipe } from 'it-pipe' import { createNode, populateAddressBooks } from '../utils/creators/peer.js' diff --git a/test/dialing/dial-request.spec.ts b/test/dialing/dial-request.spec.ts index c41d8636..c5b56371 100644 --- a/test/dialing/dial-request.spec.ts +++ b/test/dialing/dial-request.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { AbortError } from '@libp2p/interfaces/errors' import pDefer from 'p-defer' diff --git a/test/dialing/direct.node.ts b/test/dialing/direct.node.ts index e9298500..a544b768 100644 --- a/test/dialing/direct.node.ts +++ b/test/dialing/direct.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { TCP } from '@libp2p/tcp' import { Mplex } from '@libp2p/mplex' diff --git a/test/dialing/direct.spec.ts b/test/dialing/direct.spec.ts index b6e698da..fb2f978d 100644 --- a/test/dialing/direct.spec.ts +++ b/test/dialing/direct.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import pDefer from 'p-defer' import delay from 'delay' diff --git a/test/dialing/resolver.spec.ts b/test/dialing/resolver.spec.ts index 9c0fc270..1dead4ae 100644 --- a/test/dialing/resolver.spec.ts +++ b/test/dialing/resolver.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { Multiaddr } from '@multiformats/multiaddr' import { codes as ErrorCodes } from '../../src/errors.js' diff --git a/test/fetch/fetch.node.ts b/test/fetch/fetch.node.ts index 2da2cd81..c33b73a7 100644 --- a/test/fetch/fetch.node.ts +++ b/test/fetch/fetch.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { createLibp2pNode, Libp2pNode } from '../../src/libp2p.js' import { TCP } from '@libp2p/tcp' import { Mplex } from '@libp2p/mplex' diff --git a/test/identify/index.spec.ts b/test/identify/index.spec.ts index 0297a5af..bbe81306 100644 --- a/test/identify/index.spec.ts +++ b/test/identify/index.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { Multiaddr } from '@multiformats/multiaddr' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' @@ -218,7 +218,7 @@ describe('Identify', () => { signedPeerRecord, observedAddr: connection.remoteAddr.bytes, protocols: [] - }).finish() + }) await pipe( [message], diff --git a/test/insecure/plaintext.spec.ts b/test/insecure/plaintext.spec.ts index d4198dab..2ad62faa 100644 --- a/test/insecure/plaintext.spec.ts +++ b/test/insecure/plaintext.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import Peers from '../fixtures/peers.js' import { Plaintext } from '../../src/insecure/index.js' diff --git a/test/interop.ts b/test/interop.ts index e457dc36..901dc684 100644 --- a/test/interop.ts +++ b/test/interop.ts @@ -8,7 +8,7 @@ import { TCP } from '@libp2p/tcp' import { Multiaddr } from '@multiformats/multiaddr' import { KadDHT } from '@libp2p/kad-dht' import { path as p2pd } from 'go-libp2p' -import execa from 'execa' +import { execa } from 'execa' import pDefer from 'p-defer' import { logger } from '@libp2p/logger' import { Mplex } from '@libp2p/mplex' diff --git a/test/keychain/cms-interop.spec.ts b/test/keychain/cms-interop.spec.ts index 32748acc..5a3494c7 100644 --- a/test/keychain/cms-interop.spec.ts +++ b/test/keychain/cms-interop.spec.ts @@ -1,7 +1,7 @@ /* eslint max-nested-callbacks: ["error", 8] */ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import { MemoryDatastore } from 'datastore-core/memory' diff --git a/test/keychain/keychain.spec.ts b/test/keychain/keychain.spec.ts index 6a176ea4..fc7feb79 100644 --- a/test/keychain/keychain.spec.ts +++ b/test/keychain/keychain.spec.ts @@ -1,7 +1,7 @@ /* eslint max-nested-callbacks: ["error", 8] */ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import { toString as uint8ArrayToString } from 'uint8arrays/to-string' import { createNode } from '../utils/creators/peer.js' diff --git a/test/keychain/peerid.spec.ts b/test/keychain/peerid.spec.ts index 6d5d1354..c776bd90 100644 --- a/test/keychain/peerid.spec.ts +++ b/test/keychain/peerid.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { base58btc } from 'multiformats/bases/base58' import { supportedKeys, unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' diff --git a/test/metrics/index.node.ts b/test/metrics/index.node.ts index 96871db4..0f382dc1 100644 --- a/test/metrics/index.node.ts +++ b/test/metrics/index.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { randomBytes } from '@libp2p/crypto' import { pipe } from 'it-pipe' diff --git a/test/metrics/index.spec.ts b/test/metrics/index.spec.ts index c63fe14d..2efe63ee 100644 --- a/test/metrics/index.spec.ts +++ b/test/metrics/index.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { randomBytes } from '@libp2p/crypto' import { duplexPair } from 'it-pair/duplex' diff --git a/test/nat-manager/nat-manager.node.ts b/test/nat-manager/nat-manager.node.ts index 3a610410..440cb295 100644 --- a/test/nat-manager/nat-manager.node.ts +++ b/test/nat-manager/nat-manager.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { DefaultAddressManager } from '../../src/address-manager/index.js' import { DefaultTransportManager, FaultTolerance } from '../../src/transport-manager.js' import { TCP } from '@libp2p/tcp' diff --git a/test/peer-discovery/index.node.ts b/test/peer-discovery/index.node.ts index 23af1eb7..7701b470 100644 --- a/test/peer-discovery/index.node.ts +++ b/test/peer-discovery/index.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import defer from 'p-defer' import { Bootstrap } from '@libp2p/bootstrap' diff --git a/test/peer-discovery/index.spec.ts b/test/peer-discovery/index.spec.ts index f58fded8..a7d7cf82 100644 --- a/test/peer-discovery/index.spec.ts +++ b/test/peer-discovery/index.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import defer from 'p-defer' import { Multiaddr } from '@multiformats/multiaddr' diff --git a/test/peer-routing/peer-routing.node.ts b/test/peer-routing/peer-routing.node.ts index db94d643..4472c878 100644 --- a/test/peer-routing/peer-routing.node.ts +++ b/test/peer-routing/peer-routing.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import nock from 'nock' import sinon from 'sinon' import intoStream from 'into-stream' diff --git a/test/pnet/index.spec.ts b/test/pnet/index.spec.ts index 1cf1f3c1..d1105bb7 100644 --- a/test/pnet/index.spec.ts +++ b/test/pnet/index.spec.ts @@ -1,5 +1,5 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { pipe } from 'it-pipe' import all from 'it-all' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' diff --git a/test/registrar/registrar.spec.ts b/test/registrar/registrar.spec.ts index 6ed291b3..25f49c73 100644 --- a/test/registrar/registrar.spec.ts +++ b/test/registrar/registrar.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import pDefer from 'p-defer' import { MemoryDatastore } from 'datastore-core/memory' import { createTopology } from '@libp2p/topology' diff --git a/test/relay/auto-relay.node.ts b/test/relay/auto-relay.node.ts index 53e8a1b2..8b3b2a46 100644 --- a/test/relay/auto-relay.node.ts +++ b/test/relay/auto-relay.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import defer from 'p-defer' import pWaitFor from 'p-wait-for' import sinon from 'sinon' diff --git a/test/relay/relay.node.ts b/test/relay/relay.node.ts index 7061f5db..aaf82796 100644 --- a/test/relay/relay.node.ts +++ b/test/relay/relay.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { Multiaddr } from '@multiformats/multiaddr' import { pipe } from 'it-pipe' diff --git a/test/transports/transport-manager.node.ts b/test/transports/transport-manager.node.ts index 0098382e..fd931bb9 100644 --- a/test/transports/transport-manager.node.ts +++ b/test/transports/transport-manager.node.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import { MemoryDatastore } from 'datastore-core/memory' import { DefaultAddressManager } from '../../src/address-manager/index.js' import { DefaultTransportManager } from '../../src/transport-manager.js' diff --git a/test/transports/transport-manager.spec.ts b/test/transports/transport-manager.spec.ts index 0edb29d3..19d0902d 100644 --- a/test/transports/transport-manager.spec.ts +++ b/test/transports/transport-manager.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { Multiaddr } from '@multiformats/multiaddr' import { WebSockets } from '@libp2p/websockets' diff --git a/test/upgrading/upgrader.spec.ts b/test/upgrading/upgrader.spec.ts index 6afb6cfc..536b2c53 100644 --- a/test/upgrading/upgrader.spec.ts +++ b/test/upgrading/upgrader.spec.ts @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import { expect } from 'aegir/utils/chai.js' +import { expect } from 'aegir/chai' import sinon from 'sinon' import { Mplex } from '@libp2p/mplex' import { Multiaddr } from '@multiformats/multiaddr' diff --git a/tsconfig.json b/tsconfig.json index 63499404..fe4fd056 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,10 +1,7 @@ { "extends": "aegir/src/config/tsconfig.aegir.json", "compilerOptions": { - "outDir": "dist", - "emitDeclarationOnly": false, - "module": "ES2020", - "lib": ["ES2021", "ES2021.Promise", "ES2021.String", "ES2020.BigInt", "DOM", "DOM.Iterable"] + "outDir": "dist" }, "include": [ "src",