From 0c7563da38d804b76d0a0073e31cd199c044ba1d Mon Sep 17 00:00:00 2001 From: tabcat Date: Wed, 4 Jan 2023 22:05:20 -0600 Subject: [PATCH 1/4] chore: replace err-code with CodeError chore: upgrade @libp2p/interfaces to v3.2.0 chore: remove err-code from deps replace errCode imports with CodeError replace errCode implementations with CodeError --- package.json | 3 +- src/circuit/transport.ts | 6 +-- src/components.ts | 26 ++++++------- src/config.ts | 8 ++-- src/connection-manager/dialer/dial-request.ts | 10 ++--- src/connection-manager/dialer/index.ts | 12 +++--- src/connection-manager/index.ts | 8 ++-- src/connection/index.ts | 6 +-- src/content-routing/index.ts | 16 ++++---- src/content-routing/utils.ts | 4 +- src/dht/dht-content-routing.ts | 4 +- src/dht/dht-peer-routing.ts | 4 +- src/dht/dummy-dht.ts | 24 ++++++------ src/fetch/index.ts | 12 +++--- src/get-peer.ts | 6 +-- src/identify/index.ts | 14 +++---- src/libp2p.ts | 10 ++--- src/nat-manager.ts | 4 +- src/peer-routing.ts | 10 ++--- src/ping/index.ts | 4 +- src/pnet/index.ts | 6 +-- src/pubsub/dummy-pubsub.ts | 18 ++++----- src/registrar.ts | 8 ++-- src/transport-manager.ts | 12 +++--- src/upgrader.ts | 38 +++++++++---------- 25 files changed, 136 insertions(+), 137 deletions(-) diff --git a/package.json b/package.json index 304988af69..3469332edf 100644 --- a/package.json +++ b/package.json @@ -114,7 +114,7 @@ "@libp2p/interface-registrar": "^2.0.3", "@libp2p/interface-stream-muxer": "^3.0.0", "@libp2p/interface-transport": "^2.1.0", - "@libp2p/interfaces": "^3.0.3", + "@libp2p/interfaces": "^3.2.0", "@libp2p/keychain": "^1.0.0", "@libp2p/logger": "^2.0.1", "@libp2p/multistream-select": "^3.0.0", @@ -130,7 +130,6 @@ "abortable-iterator": "^4.0.2", "any-signal": "^3.0.0", "datastore-core": "^8.0.1", - "err-code": "^3.0.1", "events": "^3.3.0", "hashlru": "^2.3.0", "interface-datastore": "^7.0.0", diff --git a/src/circuit/transport.ts b/src/circuit/transport.ts index f1957dd855..9ea8f6b1f1 100644 --- a/src/circuit/transport.ts +++ b/src/circuit/transport.ts @@ -1,7 +1,7 @@ import * as CircuitV2 from './pb/index.js' import { ReservationStore } from './reservation-store.js' import { logger } from '@libp2p/logger' -import createError from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import * as mafmt from '@multiformats/mafmt' import { multiaddr } from '@multiformats/multiaddr' import { codes } from '../errors.js' @@ -208,7 +208,7 @@ export class Circuit implements Transport, Startable { if (relayId == null || destinationId == null) { const errMsg = 'Circuit relay dial failed as addresses did not have peer id' log.error(errMsg) - throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL) + throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL) } const relayPeer = peerIdFromString(relayId) @@ -262,7 +262,7 @@ export class Circuit implements Transport, Startable { const status = await hopstr.read() if (status.status !== CircuitV2.Status.OK) { - throw createError(new Error(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`), codes.ERR_HOP_REQUEST_FAILED) + throw new CodeError(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`, codes.ERR_HOP_REQUEST_FAILED) } // TODO: do something with limit and transient connection diff --git a/src/components.ts b/src/components.ts index 0db9fed1a2..fe463df932 100644 --- a/src/components.ts +++ b/src/components.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection' import type { ContentRouting } from '@libp2p/interface-content-routing' import type { AddressManager } from '@libp2p/interface-address-manager' @@ -156,7 +156,7 @@ export class DefaultComponents implements Components, Startable { get peerId (): PeerId { if (this._peerId == null) { - throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('peerId not set', 'ERR_SERVICE_MISSING') } return this._peerId @@ -168,7 +168,7 @@ export class DefaultComponents implements Components, Startable { get addressManager (): AddressManager { if (this._addressManager == null) { - throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('addressManager not set', 'ERR_SERVICE_MISSING') } return this._addressManager @@ -180,7 +180,7 @@ export class DefaultComponents implements Components, Startable { get peerStore (): PeerStore { if (this._peerStore == null) { - throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('peerStore not set', 'ERR_SERVICE_MISSING') } return this._peerStore @@ -192,7 +192,7 @@ export class DefaultComponents implements Components, Startable { get upgrader (): Upgrader { if (this._upgrader == null) { - throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('upgrader not set', 'ERR_SERVICE_MISSING') } return this._upgrader @@ -204,7 +204,7 @@ export class DefaultComponents implements Components, Startable { get registrar (): Registrar { if (this._registrar == null) { - throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('registrar not set', 'ERR_SERVICE_MISSING') } return this._registrar @@ -216,7 +216,7 @@ export class DefaultComponents implements Components, Startable { get connectionManager (): ConnectionManager { if (this._connectionManager == null) { - throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('connectionManager not set', 'ERR_SERVICE_MISSING') } return this._connectionManager @@ -228,7 +228,7 @@ export class DefaultComponents implements Components, Startable { get transportManager (): TransportManager { if (this._transportManager == null) { - throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('transportManager not set', 'ERR_SERVICE_MISSING') } return this._transportManager @@ -240,7 +240,7 @@ export class DefaultComponents implements Components, Startable { get connectionGater (): ConnectionGater { if (this._connectionGater == null) { - throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('connectionGater not set', 'ERR_SERVICE_MISSING') } return this._connectionGater @@ -252,7 +252,7 @@ export class DefaultComponents implements Components, Startable { get contentRouting (): ContentRouting { if (this._contentRouting == null) { - throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('contentRouting not set', 'ERR_SERVICE_MISSING') } return this._contentRouting @@ -264,7 +264,7 @@ export class DefaultComponents implements Components, Startable { get peerRouting (): PeerRouting { if (this._peerRouting == null) { - throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('peerRouting not set', 'ERR_SERVICE_MISSING') } return this._peerRouting @@ -276,7 +276,7 @@ export class DefaultComponents implements Components, Startable { get datastore (): Datastore { if (this._datastore == null) { - throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('datastore not set', 'ERR_SERVICE_MISSING') } return this._datastore @@ -296,7 +296,7 @@ export class DefaultComponents implements Components, Startable { get dialer (): Dialer { if (this._dialer == null) { - throw errCode(new Error('dialer not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('dialer not set', 'ERR_SERVICE_MISSING') } return this._dialer diff --git a/src/config.ts b/src/config.ts index 925b2f105f..7896142b3f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -8,7 +8,7 @@ import { FaultTolerance } from '@libp2p/interface-transport' import type { Multiaddr } from '@multiformats/multiaddr' import type { Libp2pInit } from './index.js' import { codes, messages } from './errors.js' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import type { RecursivePartial } from '@libp2p/interfaces' import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe' @@ -95,15 +95,15 @@ export function validateConfig (opts: RecursivePartial): Libp2pInit const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts) if (resultingOptions.transports == null || resultingOptions.transports.length < 1) { - throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED) + throw new CodeError(messages.ERR_TRANSPORTS_REQUIRED, codes.ERR_TRANSPORTS_REQUIRED) } if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) { - throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED) + throw new CodeError(messages.CONN_ENCRYPTION_REQUIRED, codes.CONN_ENCRYPTION_REQUIRED) } if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef - throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED) + throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED) } // Append user agent version to default AGENT_VERSION depending on the environment diff --git a/src/connection-manager/dialer/dial-request.ts b/src/connection-manager/dialer/dial-request.ts index 77d1a306a9..6605a97c8c 100644 --- a/src/connection-manager/dialer/dial-request.ts +++ b/src/connection-manager/dialer/dial-request.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { anySignal } from 'any-signal' import FIFO from 'p-fifo' import { setMaxListeners } from 'events' @@ -50,7 +50,7 @@ export class DialRequest { // If no tokens are available, throw if (tokens.length < 1) { - throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS) + throw new CodeError('No dial tokens available', codes.ERR_NO_DIAL_TOKENS) } const tokenHolder = new FIFO() @@ -87,12 +87,12 @@ export class DialRequest { // End attempt once another attempt succeeded if (done) { this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0]) - throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED) + throw new CodeError('dialAction already succeeded', codes.ERR_ALREADY_SUCCEEDED) } const controller = dialAbortControllers[i] if (controller == null) { - throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS) + throw new CodeError('dialAction did not come with an AbortController', codes.ERR_INVALID_PARAMETERS) } let conn try { @@ -116,7 +116,7 @@ export class DialRequest { // Notify Promise.any that attempt was not successful // to prevent from returning undefined despite there // were successful dial attempts - throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED) + throw new CodeError('dialAction led to empty object', codes.ERR_TRANSPORT_DIAL_FAILED) } else { // This dial succeeded, don't attempt anything else done = true diff --git a/src/connection-manager/dialer/index.ts b/src/connection-manager/dialer/index.ts index 4aa81e971d..7e6a1f0a7c 100644 --- a/src/connection-manager/dialer/index.ts +++ b/src/connection-manager/dialer/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { isMultiaddr, Multiaddr, Resolver, multiaddr, resolvers } from '@multiformats/multiaddr' import { TimeoutController } from 'timeout-abort-controller' import { anySignal } from 'any-signal' @@ -155,7 +155,7 @@ export class DefaultDialer implements Startable, Dialer { if (peerId != null) { if (this.components.peerId.equals(peerId)) { - throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF) + throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF) } if (multiaddr != null) { @@ -164,7 +164,7 @@ export class DefaultDialer implements Startable, Dialer { } if (await this.components.connectionGater.denyDialPeer(peerId)) { - throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED) + throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED) } } @@ -194,7 +194,7 @@ export class DefaultDialer implements Startable, Dialer { } if (dialTarget.addrs.length === 0) { - throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES) + throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES) } // try to join an in-flight dial for this peer if one is available @@ -266,7 +266,7 @@ export class DefaultDialer implements Startable, Dialer { addrs = [...new Set(addrs.map(ma => ma.toString()))].map(ma => multiaddr(ma)) if (addrs.length > this.maxAddrsToDial) { - throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES) + throw new CodeError('dial with more addresses than allowed', codes.ERR_TOO_MANY_ADDRESSES) } const peerId = isPeerId(peerIdOrMultiaddr.peerId) ? peerIdOrMultiaddr.peerId : undefined @@ -323,7 +323,7 @@ export class DefaultDialer implements Startable, Dialer { */ const dialAction: DialAction = async (addr, options = {}) => { if (options.signal?.aborted === true) { - throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED) + throw new CodeError('already aborted', codes.ERR_ALREADY_ABORTED) } return await this.components.transportManager.dial(addr, options).catch(err => { diff --git a/src/connection-manager/index.ts b/src/connection-manager/index.ts index c22e59ec5b..4304021368 100644 --- a/src/connection-manager/index.ts +++ b/src/connection-manager/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import mergeOptions from 'merge-options' import { LatencyMonitor, SummaryObject } from './latency-monitor.js' import type { AbortOptions } from '@libp2p/interfaces' @@ -168,7 +168,7 @@ export class DefaultConnectionManager extends EventEmitter { if (this.stat.status === CLOSING) { - throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED') + throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED') } if (this.stat.status === CLOSED) { - throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED') + throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED') } if (!Array.isArray(protocols)) { diff --git a/src/content-routing/index.ts b/src/content-routing/index.ts index 0834100048..c142b8b958 100644 --- a/src/content-routing/index.ts +++ b/src/content-routing/index.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' import { storeAddresses, @@ -52,7 +52,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async * findProviders (key: CID, options: AbortOptions = {}) { if (this.routers.length === 0) { - throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No content this.routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } yield * pipe( @@ -71,7 +71,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async provide (key: CID, options: AbortOptions = {}) { if (this.routers.length === 0) { - throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } await Promise.all(this.routers.map(async (router) => await router.provide(key, options))) @@ -82,7 +82,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions) { if (!this.isStarted()) { - throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) + throw new CodeError(messages.NOT_STARTED_YET, codes.DHT_NOT_STARTED) } const dht = this.components.dht @@ -98,7 +98,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async get (key: Uint8Array, options?: AbortOptions): Promise { if (!this.isStarted()) { - throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) + throw new CodeError(messages.NOT_STARTED_YET, codes.DHT_NOT_STARTED) } const dht = this.components.dht @@ -111,7 +111,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { } } - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } /** @@ -119,7 +119,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async * getMany (key: Uint8Array, nVals: number, options: AbortOptions) { // eslint-disable-line require-await if (!this.isStarted()) { - throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) + throw new CodeError(messages.NOT_STARTED_YET, codes.DHT_NOT_STARTED) } if (nVals == null || nVals === 0) { @@ -144,7 +144,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { } if (gotValues === 0) { - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } } } diff --git a/src/content-routing/utils.ts b/src/content-routing/utils.ts index bc6fa84b92..f43671b3f9 100644 --- a/src/content-routing/utils.ts +++ b/src/content-routing/utils.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import filter from 'it-filter' import map from 'it-map' import type { Source } from 'it-stream-types' @@ -49,6 +49,6 @@ export async function * requirePeers (source: Source, min: number = 1) } if (seen < min) { - throw errCode(new Error('not found'), 'NOT_FOUND') + throw new CodeError('not found', 'NOT_FOUND') } } diff --git a/src/dht/dht-content-routing.ts b/src/dht/dht-content-routing.ts index f520db4546..5ac721d686 100644 --- a/src/dht/dht-content-routing.ts +++ b/src/dht/dht-content-routing.ts @@ -1,5 +1,5 @@ import drain from 'it-drain' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import type { DHT } from '@libp2p/interface-dht' import type { ContentRouting } from '@libp2p/interface-content-routing' import type { CID } from 'multiformats/cid' @@ -38,6 +38,6 @@ export class DHTContentRouting implements ContentRouting { } } - throw errCode(new Error('Not found'), 'ERR_NOT_FOUND') + throw new CodeError('Not found', 'ERR_NOT_FOUND') } } diff --git a/src/dht/dht-peer-routing.ts b/src/dht/dht-peer-routing.ts index e1d5ddafb3..866eb81424 100644 --- a/src/dht/dht-peer-routing.ts +++ b/src/dht/dht-peer-routing.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' import type { PeerRouting } from '@libp2p/interface-peer-routing' import type { DHT } from '@libp2p/interface-dht' @@ -22,7 +22,7 @@ export class DHTPeerRouting implements PeerRouting { } } - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}) { diff --git a/src/dht/dummy-dht.ts b/src/dht/dummy-dht.ts index 3f37be345e..2c00576710 100644 --- a/src/dht/dummy-dht.ts +++ b/src/dht/dummy-dht.ts @@ -1,6 +1,6 @@ import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht' import type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' import { EventEmitter } from '@libp2p/interfaces/events' import { symbol } from '@libp2p/interface-peer-discovery' @@ -15,46 +15,46 @@ export class DummyDHT extends EventEmitter implements DualD } get wan (): SingleDHT { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } get lan (): SingleDHT { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } get (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } findProviders (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } findPeer (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } getClosestPeers (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } provide (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } put (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } async getMode (): Promise<'client' | 'server'> { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } async setMode (): Promise { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } async refreshRoutingTable (): Promise { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } } diff --git a/src/fetch/index.ts b/src/fetch/index.ts index 08d8a3e973..bb2bf4e48f 100644 --- a/src/fetch/index.ts +++ b/src/fetch/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from '../errors.js' import * as lp from 'it-length-prefixed' import { FetchRequest, FetchResponse } from './pb/proto.js' @@ -134,7 +134,7 @@ export class FetchService implements Startable { const buf = await first(source) if (buf == null) { - throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE) + throw new CodeError('No data received', codes.ERR_INVALID_MESSAGE) } const response = FetchResponse.decode(buf) @@ -151,11 +151,11 @@ export class FetchService implements Startable { case (FetchResponse.StatusCode.ERROR): { log('received status for %s error', key) const errmsg = uint8arrayToString(response.data) - throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS) + throw new CodeError('Error in fetch protocol response: ' + errmsg, codes.ERR_INVALID_PARAMETERS) } default: { log('received status for %s unknown', key) - throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE) + throw new CodeError('Unknown response status', codes.ERR_INVALID_MESSAGE) } } } @@ -189,7 +189,7 @@ export class FetchService implements Startable { const buf = await first(source) if (buf == null) { - throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE) + throw new CodeError('No data received', codes.ERR_INVALID_MESSAGE) } // for await (const buf of source) { @@ -245,7 +245,7 @@ export class FetchService implements Startable { */ registerLookupFunction (prefix: string, lookup: LookupFunction) { if (this.lookupFunctions.has(prefix)) { - throw errCode(new Error("Fetch protocol handler for key prefix '" + prefix + "' already registered"), codes.ERR_KEY_ALREADY_EXISTS) + throw new CodeError("Fetch protocol handler for key prefix '" + prefix + "' already registered", codes.ERR_KEY_ALREADY_EXISTS) } this.lookupFunctions.set(prefix, lookup) diff --git a/src/get-peer.ts b/src/get-peer.ts index 316ca2c057..ed8e544876 100644 --- a/src/get-peer.ts +++ b/src/get-peer.ts @@ -1,7 +1,7 @@ import { peerIdFromString } from '@libp2p/peer-id' import type { Multiaddr } from '@multiformats/multiaddr' import { isMultiaddr } from '@multiformats/multiaddr' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from './errors.js' import { isPeerId } from '@libp2p/interface-peer-id' import type { PeerId } from '@libp2p/interface-peer-id' @@ -25,8 +25,8 @@ export function getPeerAddress (peer: PeerId | Multiaddr): { peerId?: PeerId, mu } } - throw errCode( - new Error(`${peer} is not a PeerId or a Multiaddr`), // eslint-disable-line @typescript-eslint/restrict-template-expressions + throw new CodeError( + `${peer} is not a PeerId or a Multiaddr`, // eslint-disable-line @typescript-eslint/restrict-template-expressions codes.ERR_INVALID_MULTIADDR ) } diff --git a/src/identify/index.ts b/src/identify/index.ts index 6c01b23252..ace83ba249 100644 --- a/src/identify/index.ts +++ b/src/identify/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import * as lp from 'it-length-prefixed' import { pipe } from 'it-pipe' import first from 'it-first' @@ -272,13 +272,13 @@ export class IdentifyService implements Startable { ) if (data == null) { - throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED) + throw new CodeError('No data could be retrieved', codes.ERR_CONNECTION_ENDED) } try { return Identify.decode(data) } catch (err: any) { - throw errCode(err, codes.ERR_INVALID_MESSAGE) + throw new CodeError(String(err), codes.ERR_INVALID_MESSAGE) } } finally { if (timeoutController != null) { @@ -310,17 +310,17 @@ export class IdentifyService implements Startable { } = message if (publicKey == null) { - throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY) + throw new CodeError('public key was missing from identify message', codes.ERR_MISSING_PUBLIC_KEY) } const id = await peerIdFromKeys(publicKey) if (!connection.remotePeer.equals(id)) { - throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER) + throw new CodeError('identified peer does not match the expected peer', codes.ERR_INVALID_PEER) } if (this.components.peerId.equals(id)) { - throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER) + throw new CodeError('identified peer is our own peer id?', codes.ERR_INVALID_PEER) } // Get the observedAddr if there is one @@ -333,7 +333,7 @@ export class IdentifyService implements Startable { const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN) if (!envelope.peerId.equals(id)) { - throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER) + throw new CodeError('identified peer does not match the expected peer', codes.ERR_INVALID_PEER) } if (await this.components.peerStore.addressBook.consumePeerRecord(envelope)) { diff --git a/src/libp2p.ts b/src/libp2p.ts index 2f15c2538e..b58a0f0f58 100644 --- a/src/libp2p.ts +++ b/src/libp2p.ts @@ -42,7 +42,7 @@ import type { PeerStore } from '@libp2p/interface-peer-store' import type { DualDHT } from '@libp2p/interface-dht' import { concat as uint8ArrayConcat } from 'uint8arrays/concat' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { unmarshalPublicKey } from '@libp2p/crypto/keys' import type { Metrics } from '@libp2p/interface-metrics' import { DummyDHT } from './dht/dummy-dht.js' @@ -378,13 +378,13 @@ export class Libp2pNode extends EventEmitter implements Libp2p { async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}) { if (protocols == null) { - throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) + throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) } protocols = Array.isArray(protocols) ? protocols : [protocols] if (protocols.length === 0) { - throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) + throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) } const connection = await this.dial(peer, options) @@ -425,7 +425,7 @@ export class Libp2pNode extends EventEmitter implements Libp2p { } if (this.dht == null) { - throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('Public key was not in the peer store and the DHT is not enabled', codes.ERR_NO_ROUTERS_AVAILABLE) } const peerKey = uint8ArrayConcat([ @@ -444,7 +444,7 @@ export class Libp2pNode extends EventEmitter implements Libp2p { } } - throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD) + throw new CodeError(`Node not responding with its public key: ${peer.toString()}`, codes.ERR_INVALID_RECORD) } async fetch (peer: PeerId | Multiaddr, key: string, options: AbortOptions = {}): Promise { diff --git a/src/nat-manager.ts b/src/nat-manager.ts index 2486ee23c7..0f2bdcc4cb 100644 --- a/src/nat-manager.ts +++ b/src/nat-manager.ts @@ -4,7 +4,7 @@ import { fromNodeAddress } from '@multiformats/multiaddr' import { isBrowser } from 'wherearewe' import isPrivateIp from 'private-ip' import * as pkg from './version.js' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from './errors.js' import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback' import type { Startable } from '@libp2p/interfaces/startable' @@ -94,7 +94,7 @@ export class NatManager implements Startable { this.gateway = init.gateway if (this.ttl < DEFAULT_TTL) { - throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS) + throw new CodeError(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`, codes.ERR_INVALID_PARAMETERS) } } diff --git a/src/peer-routing.ts b/src/peer-routing.ts index 23eb1a2c7c..5f71a77758 100644 --- a/src/peer-routing.ts +++ b/src/peer-routing.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes, messages } from './errors.js' import { storeAddresses, @@ -141,11 +141,11 @@ export class DefaultPeerRouting implements PeerRouting, Startable { */ async findPeer (id: PeerId, options?: AbortOptions): Promise { if (this.routers.length === 0) { - throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } if (id.toString() === this.components.peerId.toString()) { - throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF) + throw new CodeError('Should not try to find self', codes.ERR_FIND_SELF) } const output = await pipe( @@ -167,7 +167,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable { return output } - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } /** @@ -175,7 +175,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable { */ async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable { if (this.routers.length === 0) { - throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } yield * pipe( diff --git a/src/ping/index.ts b/src/ping/index.ts index 6e25da93f9..3850231b6b 100644 --- a/src/ping/index.ts +++ b/src/ping/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from '../errors.js' import { randomBytes } from '@libp2p/crypto' import { pipe } from 'it-pipe' @@ -119,7 +119,7 @@ export class PingService implements Startable { const end = Date.now() if (result == null || !uint8ArrayEquals(data, result.subarray())) { - throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK) + throw new CodeError('Received wrong ping ack', codes.ERR_WRONG_PING_ACK) } return end - start diff --git a/src/pnet/index.ts b/src/pnet/index.ts index da364de961..b40247367e 100644 --- a/src/pnet/index.ts +++ b/src/pnet/index.ts @@ -24,7 +24,7 @@ import { logger } from '@libp2p/logger' import { pipe } from 'it-pipe' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { duplexPair } from 'it-pair/duplex' import { randomBytes } from '@libp2p/crypto' import * as Errors from './errors.js' @@ -81,7 +81,7 @@ class PreSharedKeyConnectionProtector implements ConnectionProtector { } if (connection == null) { - throw errCode(new Error(Errors.NO_HANDSHAKE_CONNECTION), codes.ERR_INVALID_PARAMETERS) + throw new CodeError(Errors.NO_HANDSHAKE_CONNECTION, codes.ERR_INVALID_PARAMETERS) } // Exchange nonces @@ -94,7 +94,7 @@ class PreSharedKeyConnectionProtector implements ConnectionProtector { const result = await shake.reader.next(NONCE_LENGTH) if (result.value == null) { - throw errCode(new Error(Errors.STREAM_ENDED), codes.ERR_INVALID_PARAMETERS) + throw new CodeError(Errors.STREAM_ENDED, codes.ERR_INVALID_PARAMETERS) } const remoteNonce = result.value.slice() diff --git a/src/pubsub/dummy-pubsub.ts b/src/pubsub/dummy-pubsub.ts index 3334dee8f1..d104a5b501 100644 --- a/src/pubsub/dummy-pubsub.ts +++ b/src/pubsub/dummy-pubsub.ts @@ -1,7 +1,7 @@ import { EventEmitter } from '@libp2p/interfaces/events' import type { PeerId } from '@libp2p/interface-peer-id' import type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign, TopicValidatorFn } from '@libp2p/interface-pubsub' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' export class DummyPubSub extends EventEmitter implements PubSub { @@ -20,34 +20,34 @@ export class DummyPubSub extends EventEmitter implements PubSub { } get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } get multicodecs (): string[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } getPeers (): PeerId[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } getTopics (): string[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } subscribe (): void { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } unsubscribe (): void { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } getSubscribers (): PeerId[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } async publish (): Promise { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } } diff --git a/src/registrar.ts b/src/registrar.ts index 75121edc04..6b9f52a762 100644 --- a/src/registrar.ts +++ b/src/registrar.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from './errors.js' import { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar' import merge from 'merge-options' @@ -55,7 +55,7 @@ export class DefaultRegistrar implements Registrar { const handler = this.handlers.get(protocol) if (handler == null) { - throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL) + throw new CodeError(`No handler registered for protocol ${protocol}`, codes.ERR_NO_HANDLER_FOR_PROTOCOL) } return handler @@ -78,7 +78,7 @@ export class DefaultRegistrar implements Registrar { */ async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise { if (this.handlers.has(protocol)) { - throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED) + throw new CodeError(`Handler already registered for protocol ${protocol}`, codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED) } const options = merge.bind({ ignoreUndefined: true })({ @@ -116,7 +116,7 @@ export class DefaultRegistrar implements Registrar { async register (protocol: string, topology: Topology): Promise { if (!isTopology(topology)) { log.error('topology must be an instance of interfaces/topology') - throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS) + throw new CodeError('topology must be an instance of interfaces/topology', codes.ERR_INVALID_PARAMETERS) } // Create topology diff --git a/src/transport-manager.ts b/src/transport-manager.ts index fc4a0dbdb5..823c7df3a7 100644 --- a/src/transport-manager.ts +++ b/src/transport-manager.ts @@ -1,6 +1,6 @@ import { logger } from '@libp2p/logger' import { codes } from './errors.js' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { FaultTolerance } from '@libp2p/interface-transport' import type { Listener, Transport, TransportManager, TransportManagerEvents, Upgrader } from '@libp2p/interface-transport' import type { Multiaddr } from '@multiformats/multiaddr' @@ -51,11 +51,11 @@ export class DefaultTransportManager extends EventEmitter r.status === 'fulfilled') if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) { - throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES) + throw new CodeError(`Transport (${key}) could not listen on any available address`, codes.ERR_NO_VALID_ADDRESSES) } } @@ -233,7 +233,7 @@ export class DefaultTransportManager extends EventEmitter implements Upg const accept = await this.components.connectionManager.acceptIncomingConnection(maConn) if (!accept) { - throw errCode(new Error('connection denied'), codes.ERR_CONNECTION_DENIED) + throw new CodeError('connection denied', codes.ERR_CONNECTION_DENIED) } let encryptedConn @@ -157,7 +157,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg maConn.sink = abortableStream.sink if (await this.components.connectionGater.denyInboundConnection(maConn)) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptConnection', codes.ERR_CONNECTION_INTERCEPTED) } this.components.metrics?.trackMultiaddrConnection(maConn) @@ -190,13 +190,13 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } } else { const idStr = maConn.remoteAddr.getPeerId() if (idStr == null) { - throw errCode(new Error('inbound connection that skipped encryption must have a peer id'), codes.ERR_INVALID_MULTIADDR) + throw new CodeError('inbound connection that skipped encryption must have a peer id', codes.ERR_INVALID_MULTIADDR) } const remotePeerId = peerIdFromString(idStr) @@ -226,7 +226,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } log('Successfully upgraded inbound connection') @@ -256,7 +256,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg remotePeerId = peerIdFromString(idStr) if (await this.components.connectionGater.denyOutboundConnection(remotePeerId, maConn)) { - throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by connectionGater.denyOutboundConnection', codes.ERR_CONNECTION_INTERCEPTED) } } @@ -297,11 +297,11 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } } else { if (remotePeerId == null) { - throw errCode(new Error('Encryption was skipped but no peer id was passed'), codes.ERR_INVALID_PEER) + throw new CodeError('Encryption was skipped but no peer id was passed', codes.ERR_INVALID_PEER) } cryptoProtocol = 'native' @@ -330,7 +330,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } log('Successfully upgraded outbound connection') @@ -386,7 +386,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg const streamCount = countStreams(protocol, 'inbound', connection) if (streamCount === incomingLimit) { - muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol "${protocol}" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS)) + muxedStream.abort(new CodeError(`Too many inbound protocol streams for protocol "${protocol}" - limit ${incomingLimit}`, codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS)) return } @@ -422,7 +422,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg newStream = async (protocols: string[], options: AbortOptions = {}): Promise => { if (muxer == null) { - throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE) + throw new CodeError('Stream is not multiplexed', codes.ERR_MUXER_UNAVAILABLE) } log('%s: starting new stream on %s', direction, protocols) @@ -448,7 +448,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg const streamCount = countStreams(protocol, 'outbound', connection) if (streamCount === outgoingLimit) { - const err = errCode(new Error(`Too many outbound protocol streams for protocol "${protocol}" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS) + const err = new CodeError(`Too many outbound protocol streams for protocol "${protocol}" - limit ${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS) muxedStream.abort(err) throw err @@ -478,7 +478,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg throw err } - throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL) + throw new CodeError(String(err), codes.ERR_UNSUPPORTED_PROTOCOL) } finally { if (controller != null) { controller.clear() @@ -523,7 +523,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg maConn.timeline.upgraded = Date.now() const errConnectionNotMultiplexed = () => { - throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED) + throw new CodeError('connection is not multiplexed', codes.ERR_CONNECTION_NOT_MULTIPLEXED) } // Create the connection @@ -589,7 +589,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg protocol } } catch (err: any) { - throw errCode(err, codes.ERR_ENCRYPTION_FAILED) + throw new CodeError(String(err), codes.ERR_ENCRYPTION_FAILED) } } @@ -618,7 +618,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg protocol } } catch (err: any) { - throw errCode(err, codes.ERR_ENCRYPTION_FAILED) + throw new CodeError(String(err), codes.ERR_ENCRYPTION_FAILED) } } @@ -638,7 +638,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg return { stream, muxerFactory } } catch (err: any) { log.error('error multiplexing outbound stream', err) - throw errCode(err, codes.ERR_MUXER_UNAVAILABLE) + throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE) } } @@ -657,7 +657,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg return { stream, muxerFactory } } catch (err: any) { log.error('error multiplexing inbound stream', err) - throw errCode(err, codes.ERR_MUXER_UNAVAILABLE) + throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE) } } } From a511be5231988c325ffec7a9e6924253db5eb738 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Mon, 20 Mar 2023 10:34:19 +0000 Subject: [PATCH 2/4] chore: update error creation --- src/fetch/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fetch/index.ts b/src/fetch/index.ts index 9cde304481..75dba5bb64 100644 --- a/src/fetch/index.ts +++ b/src/fetch/index.ts @@ -245,7 +245,7 @@ export class FetchService implements Startable { */ registerLookupFunction (prefix: string, lookup: LookupFunction): void { if (this.lookupFunctions.has(prefix)) { - throw new CodeError("Fetch protocol handler for key prefix '" + prefix + "' already registered", codes.ERR_KEY_ALREADY_EXISTS) + throw new CodeError(`Fetch protocol handler for key prefix '${prefix}' already registered`, codes.ERR_KEY_ALREADY_EXISTS) } this.lookupFunctions.set(prefix, lookup) From 79e57ac929b93e862ed8da1c6725f881ce9249dc Mon Sep 17 00:00:00 2001 From: achingbrain Date: Mon, 20 Mar 2023 12:20:55 +0000 Subject: [PATCH 3/4] chore: remove err-code --- src/circuit/transport/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/circuit/transport/index.ts b/src/circuit/transport/index.ts index a76e320fc8..2643bd7d43 100644 --- a/src/circuit/transport/index.ts +++ b/src/circuit/transport/index.ts @@ -1,6 +1,5 @@ import { StopMessage, HopMessage, Status } from '../pb/index.js' import { logger } from '@libp2p/logger' -import createError from 'err-code' import * as mafmt from '@multiformats/mafmt' import { multiaddr } from '@multiformats/multiaddr' import { codes } from '../../errors.js' @@ -23,6 +22,7 @@ import type { ContentRouting } from '@libp2p/interface-content-routing' import { CIRCUIT_PROTO_CODE, RELAY_V2_HOP_CODEC, RELAY_V2_STOP_CODEC } from '../constants.js' import { RelayStoreInit, ReservationStore } from './reservation-store.js' import { RelayDiscovery, RelayDiscoveryComponents } from './discovery.js' +import { CodeError } from '@libp2p/interfaces/errors' const log = logger('libp2p:circuit-relay:transport') @@ -154,7 +154,7 @@ class CircuitRelayTransport implements Transport { if (ma.protoCodes().filter(code => code === CIRCUIT_PROTO_CODE).length !== 1) { const errMsg = 'Invalid circuit relay address' log.error(errMsg, ma) - throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL) + throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL) } // Check the multiaddr to see if it contains a relay and a destination peer @@ -167,7 +167,7 @@ class CircuitRelayTransport implements Transport { if (relayId == null || destinationId == null) { const errMsg = 'Circuit relay dial failed as addresses did not have peer id' log.error(errMsg) - throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL) + throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL) } const relayPeer = peerIdFromString(relayId) From 9a94ac72f094989ef739d17062c3e23587d7c9d6 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Mon, 20 Mar 2023 12:31:00 +0000 Subject: [PATCH 4/4] chore: fix another instance --- src/circuit/transport/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/circuit/transport/index.ts b/src/circuit/transport/index.ts index 2643bd7d43..d95233ee36 100644 --- a/src/circuit/transport/index.ts +++ b/src/circuit/transport/index.ts @@ -223,7 +223,7 @@ class CircuitRelayTransport implements Transport { const status = await hopstr.read() if (status.status !== Status.OK) { - throw createError(new Error(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`), codes.ERR_HOP_REQUEST_FAILED) + throw new CodeError(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`, codes.ERR_HOP_REQUEST_FAILED) } // TODO: do something with limit and transient connection