@libp2p/circuit-relay-v2 4.0.6-d1ff510bb → 4.1.0-8cebf6322
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js.map +1 -1
- package/package.json +9 -9
package/dist/index.min.js.map
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../../../node_modules/main-event/src/index.ts", "../../interface/src/errors.ts", "../../interface/src/events.ts", "../../interface/src/peer-id.ts", "../../interface/src/peer-store.ts", "../../interface/src/startable.ts", "../../interface/src/transport.ts", "../../interface/src/index.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/multiformats/src/bases/base10.ts", "../../../node_modules/multiformats/src/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/multiformats/src/basics.ts", "../../../node_modules/uint8arrays/src/util/bases.ts", "../../../node_modules/uint8arrays/src/from-string.ts", "../../../node_modules/uint8arrays/src/to-string.ts", "../../crypto/src/keys/rsa/der.ts", "../../crypto/src/keys/ecdsa/index.ts", "../../crypto/src/keys/ecdsa/utils.ts", "../../crypto/src/keys/ecdsa/ecdsa.ts", "../../../node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/@noble/hashes/src/_u64.ts", "../../../node_modules/@noble/hashes/src/sha2.ts", "../../../node_modules/@noble/curves/src/utils.ts", "../../../node_modules/@noble/curves/src/abstract/modular.ts", "../../../node_modules/@noble/curves/src/abstract/curve.ts", "../../../node_modules/@noble/curves/src/abstract/edwards.ts", "../../../node_modules/@noble/curves/src/ed25519.ts", "../../crypto/src/errors.ts", "../../crypto/src/webcrypto/webcrypto.browser.ts", "../../crypto/src/webcrypto/index.ts", "../../crypto/src/keys/ed25519/index.browser.ts", "../../crypto/src/util.ts", "../../crypto/src/keys/ed25519/ed25519.ts", "../../crypto/src/keys/ed25519/utils.ts", "../../../node_modules/uint8-varint/src/index.ts", "../../../node_modules/protons-runtime/src/utils/float.ts", "../../../node_modules/protons-runtime/src/utils/longbits.ts", "../../../node_modules/protons-runtime/src/utils/utf8.ts", "../../../node_modules/protons-runtime/src/utils/reader.ts", "../../../node_modules/protons-runtime/src/decode.ts", "../../../node_modules/protons-runtime/src/utils/pool.ts", "../../../node_modules/protons-runtime/src/utils/writer.ts", "../../../node_modules/protons-runtime/src/encode.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../../node_modules/protons-runtime/src/index.ts", "../../crypto/src/keys/keys.ts", "../../crypto/src/keys/rsa/utils.ts", "../../crypto/src/keys/rsa/rsa.ts", "../../crypto/src/keys/rsa/index.browser.ts", "../../../node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/@noble/curves/src/secp256k1.ts", "../../crypto/src/keys/secp256k1/index.browser.ts", "../../crypto/src/keys/secp256k1/secp256k1.ts", "../../crypto/src/keys/secp256k1/utils.ts", "../../crypto/src/keys/index.ts", "../../peer-id/src/peer-id.ts", "../../peer-id/src/index.ts", "../../peer-record/src/envelope/envelope.ts", "../../peer-record/src/envelope/errors.ts", "../../peer-record/src/envelope/index.ts", "../../../node_modules/@multiformats/multiaddr/src/errors.ts", "../../../node_modules/@chainsafe/is-ip/src/parser.ts", "../../../node_modules/@chainsafe/is-ip/src/parse.ts", "../../../node_modules/@chainsafe/is-ip/src/is-ip.ts", "../../../node_modules/@multiformats/multiaddr/src/utils.ts", "../../../node_modules/@multiformats/multiaddr/src/validation.ts", "../../../node_modules/@multiformats/multiaddr/src/registry.ts", "../../../node_modules/@multiformats/multiaddr/src/components.ts", "../../../node_modules/@multiformats/multiaddr/src/multiaddr.ts", "../../../node_modules/@multiformats/multiaddr/src/index.ts", "../../../node_modules/@sindresorhus/fnv1a/index.js", "../../utils/src/filters/hashes.ts", "../../utils/src/filters/fingerprint.ts", "../../utils/src/filters/utils.ts", "../../utils/src/filters/bucket.ts", "../../utils/src/filters/cuckoo-filter.ts", "../../utils/src/filters/scalable-cuckoo-filter.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "
|
|
3
|
+
"sources": ["../src/index.ts", "../../../node_modules/main-event/src/index.ts", "../../interface/src/errors.ts", "../../interface/src/events.ts", "../../interface/src/peer-id.ts", "../../interface/src/peer-store.ts", "../../interface/src/startable.ts", "../../interface/src/transport.ts", "../../interface/src/index.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/multiformats/src/bases/base10.ts", "../../../node_modules/multiformats/src/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/multiformats/src/basics.ts", "../../../node_modules/uint8arrays/src/util/bases.ts", "../../../node_modules/uint8arrays/src/from-string.ts", "../../../node_modules/uint8arrays/src/to-string.ts", "../../crypto/src/keys/rsa/der.ts", "../../crypto/src/keys/ecdsa/index.ts", "../../crypto/src/keys/ecdsa/utils.ts", "../../crypto/src/keys/ecdsa/ecdsa.ts", "../../../node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/@noble/hashes/src/_u64.ts", "../../../node_modules/@noble/hashes/src/sha2.ts", "../../../node_modules/@noble/curves/src/utils.ts", "../../../node_modules/@noble/curves/src/abstract/modular.ts", "../../../node_modules/@noble/curves/src/abstract/curve.ts", "../../../node_modules/@noble/curves/src/abstract/edwards.ts", "../../../node_modules/@noble/curves/src/ed25519.ts", "../../crypto/src/errors.ts", "../../crypto/src/webcrypto/webcrypto.browser.ts", "../../crypto/src/webcrypto/index.ts", "../../crypto/src/keys/ed25519/index.browser.ts", "../../crypto/src/util.ts", "../../crypto/src/keys/ed25519/ed25519.ts", "../../crypto/src/keys/ed25519/utils.ts", "../../../node_modules/uint8-varint/src/index.ts", "../../../node_modules/protons-runtime/src/utils/float.ts", "../../../node_modules/protons-runtime/src/utils/longbits.ts", "../../../node_modules/protons-runtime/src/utils/utf8.ts", "../../../node_modules/protons-runtime/src/utils/reader.ts", "../../../node_modules/protons-runtime/src/decode.ts", "../../../node_modules/protons-runtime/src/utils/pool.ts", "../../../node_modules/protons-runtime/src/utils/writer.ts", "../../../node_modules/protons-runtime/src/encode.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../../node_modules/protons-runtime/src/index.ts", "../../crypto/src/keys/keys.ts", "../../crypto/src/keys/rsa/utils.ts", "../../crypto/src/keys/rsa/rsa.ts", "../../crypto/src/keys/rsa/index.browser.ts", "../../../node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/@noble/curves/src/secp256k1.ts", "../../crypto/src/keys/secp256k1/index.browser.ts", "../../crypto/src/keys/secp256k1/secp256k1.ts", "../../crypto/src/keys/secp256k1/utils.ts", "../../crypto/src/keys/index.ts", "../../peer-id/src/peer-id.ts", "../../peer-id/src/index.ts", "../../peer-record/src/envelope/envelope.ts", "../../peer-record/src/envelope/errors.ts", "../../peer-record/src/envelope/index.ts", "../../../node_modules/@multiformats/multiaddr/src/errors.ts", "../../../node_modules/@chainsafe/is-ip/src/parser.ts", "../../../node_modules/@chainsafe/is-ip/src/parse.ts", "../../../node_modules/@chainsafe/is-ip/src/is-ip.ts", "../../../node_modules/@multiformats/multiaddr/src/utils.ts", "../../../node_modules/@multiformats/multiaddr/src/validation.ts", "../../../node_modules/@multiformats/multiaddr/src/registry.ts", "../../../node_modules/@multiformats/multiaddr/src/components.ts", "../../../node_modules/@multiformats/multiaddr/src/multiaddr.ts", "../../../node_modules/@multiformats/multiaddr/src/index.ts", "../../../node_modules/@sindresorhus/fnv1a/index.js", "../../utils/src/filters/hashes.ts", "../../utils/src/filters/fingerprint.ts", "../../utils/src/filters/utils.ts", "../../utils/src/filters/bucket.ts", "../../utils/src/filters/cuckoo-filter.ts", "../../utils/src/filters/scalable-cuckoo-filter.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../utils/node_modules/p-timeout/index.js", "../../utils/node_modules/p-event/index.js", "../../utils/src/debounce.ts", "../../utils/src/errors.ts", "../../../node_modules/race-signal/src/index.ts", "../../utils/src/queue/recipient.ts", "../../utils/src/queue/job.ts", "../../utils/src/queue/index.ts", "../../utils/src/abstract-message-stream.ts", "../../utils/src/abstract-multiaddr-connection.ts", "../../../node_modules/any-signal/src/index.ts", "../../../node_modules/it-queueless-pushable/node_modules/race-signal/src/index.ts", "../../../node_modules/it-queueless-pushable/src/index.ts", "../../../node_modules/it-merge/src/index.ts", "../../../node_modules/it-pipe/src/index.ts", "../../utils/src/stream-utils.ts", "../../utils/src/peer-queue.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/utils.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/index.ts", "../src/constants.ts", "../src/pb/index.ts", "../src/errors.ts", "../src/utils.ts", "../../peer-collections/src/util.ts", "../../peer-collections/src/map.ts", "../../peer-collections/src/filter.ts", "../../peer-collections/src/tracked-map.ts", "../../../node_modules/retimeable-signal/src/index.ts", "../src/server/reservation-store.ts", "../src/server/reservation-voucher.ts", "../src/server/index.ts", "../../../node_modules/progress-events/src/index.ts", "../src/transport/discovery.ts", "../src/transport/listener.ts", "../../../node_modules/nanoid/url-alphabet/index.js", "../../../node_modules/nanoid/index.browser.js", "../src/transport/reservation-store.ts", "../src/transport/stream-to-conn.ts", "../src/transport/index.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The `circuitRelayTransport` allows libp2p to dial and listen on [Circuit Relay](https://docs.libp2p.io/concepts/nat/circuit-relay/)\n * addresses.\n *\n * @example Use as a transport\n *\n * Configuring a transport will let you dial other circuit relay addresses.\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'\n *\n * const node = await createLibp2p({\n * transports: [\n * circuitRelayTransport()\n * ]\n * })\n * ```\n *\n * The `circuitRelayServer` function allows libp2p to function as a [Circuit Relay](https://docs.libp2p.io/concepts/nat/circuit-relay/)\n * server. This will not work in browsers.\n *\n * @example Use as a server\n *\n * Configuring a server will let you function as a network relay for other\n * nodes.\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { circuitRelayServer } from '@libp2p/circuit-relay-v2'\n *\n * const node = await createLibp2p({\n * services: {\n * circuitRelay: circuitRelayServer()\n * }\n * })\n * ```\n */\n\nimport { TypedEventEmitter } from 'main-event'\nimport { CircuitRelayServer } from './server/index.js'\nimport { CircuitRelayTransport } from './transport/index.ts'\nimport type { Limit } from './pb/index.js'\nimport type { ComponentLogger, ConnectionGater, Libp2pEvents, Metrics, PeerId, PeerStore, PrivateKey, TopologyFilter, Transport, TypedEventTarget, Upgrader } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, RandomWalk, Registrar, TransportManager } from '@libp2p/interface-internal'\nimport type { PeerMap } from '@libp2p/peer-collections'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { RetimeableAbortSignal } from 'retimeable-signal'\n\nexport type { Limit }\n\nexport interface RelayReservation {\n /**\n * When this reservation expires\n */\n expiry: Date\n\n /**\n * The address of the relay client\n */\n addr: Multiaddr\n\n /**\n * How much data can be transferred over each relayed connection and for how\n * long before the underlying stream is reset\n */\n limit?: Limit\n\n /**\n * This signal will fire it's \"abort\" event when the reservation expires\n */\n signal: RetimeableAbortSignal\n}\n\nexport interface CircuitRelayServiceEvents {\n 'relay:reservation': CustomEvent<RelayReservation>\n 'relay:advert:success': CustomEvent<unknown>\n 'relay:advert:error': CustomEvent<Error>\n}\n\nexport interface CircuitRelayService extends TypedEventEmitter<CircuitRelayServiceEvents> {\n reservations: PeerMap<RelayReservation>\n}\n\nexport {\n RELAY_V2_HOP_CODEC,\n RELAY_V2_STOP_CODEC\n} from './constants.js'\n\nexport interface ServerReservationStoreInit {\n /**\n * maximum number of reservations allowed\n *\n * @default 15\n */\n maxReservations?: number\n\n /**\n * interval after which stale reservations are cleared\n *\n * @default 300000\n */\n reservationClearInterval?: number\n\n /**\n * apply default relay limits to a new reservation\n *\n * @default true\n */\n applyDefaultLimit?: boolean\n\n /**\n * reservation ttl\n *\n * @default 7200000\n */\n reservationTtl?: number\n\n /**\n * The maximum time a relayed connection can be open for\n */\n defaultDurationLimit?: number\n\n /**\n * The maximum amount of data allowed to be transferred over a relayed connection\n */\n defaultDataLimit?: bigint\n}\n\nexport interface CircuitRelayServerComponents {\n registrar: Registrar\n peerStore: PeerStore\n addressManager: AddressManager\n peerId: PeerId\n privateKey: PrivateKey\n connectionManager: ConnectionManager\n connectionGater: ConnectionGater\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport interface CircuitRelayServerInit {\n /**\n * Incoming hop requests must complete within this time in ms otherwise\n * the stream will be reset\n *\n * @default 30000\n */\n hopTimeout?: number\n\n /**\n * Configuration of reservations\n */\n reservations?: ServerReservationStoreInit\n\n /**\n * The maximum number of simultaneous HOP inbound streams that can be open at once\n */\n maxInboundHopStreams?: number\n\n /**\n * The maximum number of simultaneous HOP outbound streams that can be open at once\n */\n maxOutboundHopStreams?: number\n\n /**\n * The maximum number of simultaneous STOP outbound streams that can be open at\n * once.\n *\n * @default 300\n */\n maxOutboundStopStreams?: number\n}\n\nexport function circuitRelayServer (init: CircuitRelayServerInit = {}): (components: CircuitRelayServerComponents) => CircuitRelayService {\n return (components) => {\n return new CircuitRelayServer(components, init)\n }\n}\n\nexport interface RelayDiscoveryEvents {\n 'relay:discover': CustomEvent<PeerId>\n}\n\nexport interface TransportReservationStoreComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n peerStore: PeerStore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport interface TransportReservationStoreInit {\n /**\n * Multiple relays may be discovered simultaneously - to prevent listening\n * on too many relays, this value controls how many to attempt to reserve a\n * slot on at once. If set to more than one, we may end up listening on\n * more relays than the `maxReservations` value, but on networks with poor\n * connectivity the user may wish to attempt to reserve on multiple relays\n * simultaneously.\n *\n * @default 1\n */\n reservationConcurrency?: number\n\n /**\n * Limit the number of potential relays we will dial\n *\n * @default 100\n */\n maxReservationQueueLength?: number\n\n /**\n * When creating a reservation it must complete within this number of ms\n *\n * @default 5000\n */\n reservationCompletionTimeout?: number\n}\n\nexport interface RelayDiscoveryComponents {\n peerStore: PeerStore\n connectionManager: ConnectionManager\n transportManager: TransportManager\n registrar: Registrar\n logger: ComponentLogger\n randomWalk: RandomWalk\n events: TypedEventTarget<Libp2pEvents>\n}\n\nexport interface RelayDiscoveryInit {\n filter?: TopologyFilter\n}\n\nexport interface CircuitRelayTransportComponents extends RelayDiscoveryComponents {\n peerId: PeerId\n upgrader: Upgrader\n addressManager: AddressManager\n connectionGater: ConnectionGater\n}\n\n/**\n * RelayConfig configures the circuit v2 relay transport.\n */\nexport interface CircuitRelayTransportInit extends TransportReservationStoreInit {\n /**\n * An optional filter used to prevent duplicate attempts to reserve relay\n * slots on the same peer\n */\n discoveryFilter?: TopologyFilter\n\n /**\n * The maximum number of simultaneous STOP inbound streams that can be open at\n * once - each inbound relayed connection uses a STOP stream\n *\n * @default 300\n */\n maxInboundStopStreams?: number\n\n /**\n * The maximum number of simultaneous STOP outbound streams that can be open\n * at once. If this transport is used along with the relay server these\n * settings should be set to the same value\n *\n * @default 300\n */\n maxOutboundStopStreams?: number\n\n /**\n * When creating a reservation it must complete within this number of ms\n *\n * @default 10_000\n */\n reservationCompletionTimeout?: number\n}\n\nexport function circuitRelayTransport (init: CircuitRelayTransportInit = {}): (components: CircuitRelayTransportComponents) => Transport {\n return (components) => {\n return new CircuitRelayTransport(components, init)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.js'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n *\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "import type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * A custom implementation of MessageEvent as the Undici version does too much\n * validation in it's constructor so is very slow.\n */\nexport class StreamMessageEvent extends Event {\n public data: Uint8Array | Uint8ArrayList\n\n constructor (data: Uint8Array | Uint8ArrayList, eventInitDict?: EventInit) {\n super('message', eventInitDict)\n\n this.data = data\n }\n}\n\n/**\n * An event dispatched when the stream is closed. The `error` property can be\n * inspected to discover if the closing was graceful or not, and the `remote`\n * property shows which end of the stream initiated the closure\n */\nexport class StreamCloseEvent extends Event {\n public error?: Error\n public local?: boolean\n\n constructor (local?: boolean, error?: Error, eventInitDict?: EventInit) {\n super('close', eventInitDict)\n\n this.error = error\n this.local = local\n }\n}\n\nexport class StreamAbortEvent extends StreamCloseEvent {\n constructor (error: Error, eventInitDict?: EventInit) {\n super(true, error, eventInitDict)\n }\n}\n\nexport class StreamResetEvent extends StreamCloseEvent {\n constructor (error: Error, eventInitDict?: EventInit) {\n super(false, error, eventInitDict)\n }\n}\n", "import type { Ed25519PublicKey, KeyType, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = KeyType | string\n\n/**\n * A PeerId generated from an RSA public key - it is a base58btc encoded sha-256\n * hash of the public key.\n *\n * RSA public keys are too large to pass around freely, instead Ed25519 or\n * secp256k1 should be preferred as they can embed their public key in the\n * PeerId itself.\n *\n * @deprecated Ed25519 or secp256k1 keys are preferred to RSA\n */\nexport interface RSAPeerId {\n readonly type: 'RSA'\n\n /**\n * RSA public keys are too large to embed in the multihash commonly used to\n * refer to peers, so this will only be defined if the public key has\n * previously been found through a routing query or during normal protocol\n * operations\n */\n readonly publicKey?: RSAPublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the SHA2-256 hash of the public\n * key\n */\n toMultihash(): MultihashDigest<0x12>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x12, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface Ed25519PeerId {\n readonly type: 'Ed25519'\n\n /**\n * This will always be defined as the public key is embedded in the multihash\n * of this PeerId\n */\n readonly publicKey: Ed25519PublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the protobuf-encoded public key\n * encoded as an identity hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface Secp256k1PeerId {\n readonly type: 'secp256k1'\n\n /**\n * This will always be defined as the public key is embedded in the multihash\n * of this PeerId\n */\n readonly publicKey: Secp256k1PublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the protobuf-encoded public key\n * encoded as an identity hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface URLPeerId {\n readonly type: 'url'\n\n /**\n * This will always be undefined as URL Peers do not have public keys\n */\n readonly publicKey: undefined\n\n /**\n * Returns CID from `toCID()` encoded as a base36 string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the URL encoded as an identity\n * hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the Transport IPFS Gateway HTTP code and the same\n * multihash as `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x0920, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\n/**\n * This is a union of all known PeerId types - use the `.type` field to\n * disambiguate them\n */\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId | URLPeerId\n\n/**\n * All PeerId implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const peerIdSymbol = Symbol.for('@libp2p/peer-id')\n\n/**\n * Returns true if the passed argument is a PeerId implementation\n */\nexport function isPeerId (other?: any): other is PeerId {\n return Boolean(other?.[peerIdSymbol])\n}\n", "import type { AbortOptions } from './index.ts'\nimport type { PublicKey } from './keys.js'\nimport type { PeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * When a peer that is tagged with this prefix disconnects, we will attempt to\n * redial it, up to a limit.\n *\n * To allow multiple components to add/remove their own keep-alive tags without\n * accidentally overwriting those of other components, attach a unique suffix to\n * the tag, e.g. `keep-alive-circuit-relay` or `keep-alive-kad-dht`, etc.\n */\nexport const KEEP_ALIVE = 'keep-alive'\n\n/**\n * A multiaddr with an optional flag that indicates if its trustworthy\n */\nexport interface Address {\n /**\n * Peer multiaddr\n */\n multiaddr: Multiaddr\n\n /**\n * Obtained from a signed peer record\n */\n isCertified: boolean\n}\n\n/**\n * Data stored in the peer store about peers\n */\nexport interface Peer {\n /**\n * Peer's peer-id instance\n */\n id: PeerId\n\n /**\n * Peer's addresses containing a list of multiaddrs and a isCertified field\n * indicating if the address was loaded from a signed peer record or not\n */\n addresses: Address[]\n\n /**\n * Peer's supported protocols\n */\n protocols: string[]\n\n /**\n * Peer's metadata map\n */\n metadata: Map<string, Uint8Array>\n\n /**\n * Tags a peer has\n */\n tags: Map<string, Tag>\n\n /**\n * The last peer record envelope received\n */\n peerRecordEnvelope?: Uint8Array\n}\n\n/**\n * Peer data used to update the peer store\n */\nexport interface PeerData {\n /**\n * Peer's addresses containing its multiaddrs and metadata - multiaddrs\n * passed here can be treated as certified if the `isCertifed` value is\n * set to true.\n *\n * If both addresses and multiaddrs are specified they will be merged\n * together with entries in addresses taking precedence.\n */\n addresses?: Address[]\n\n /**\n * Peer's multiaddrs - any multiaddrs passed here will be treated as\n * uncertified.\n *\n * If both addresses and multiaddrs are specified they will be merged\n * together with entries in addresses taking precedence.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Peer's supported protocols\n */\n protocols?: string[]\n\n /**\n * Peer's metadata map. When merging pass undefined as values to remove metadata.\n */\n metadata?: Map<string, Uint8Array | undefined> | Record<string, Uint8Array | undefined>\n\n /**\n * Peer tags. When merging pass undefined as values to remove tags.\n */\n tags?: Map<string, TagOptions | undefined> | Record<string, TagOptions | undefined>\n\n /**\n * If this Peer has an RSA key, it's public key can be set with this property.\n *\n * The byte array should be the protobuf encoded form of the public key.\n */\n publicKey?: PublicKey\n\n /**\n * The last peer record envelope received\n */\n peerRecordEnvelope?: Uint8Array\n}\n\nexport interface TagOptions {\n /**\n * An optional tag value (1-100)\n */\n value?: number\n\n /**\n * An optional duration in ms after which the tag will expire\n */\n ttl?: number\n}\n\nexport interface Tag {\n /**\n * The tag value\n */\n value: number\n}\n\n/**\n * A predicate by which to filter lists of peers\n */\nexport interface PeerQueryFilter { (peer: Peer): boolean }\n\n/**\n * A predicate by which to sort lists of peers\n */\nexport interface PeerQueryOrder { (a: Peer, b: Peer): -1 | 0 | 1 }\n\n/**\n * A query for getting lists of peers\n */\nexport interface PeerQuery extends AbortOptions {\n filters?: PeerQueryFilter[]\n orders?: PeerQueryOrder[]\n limit?: number\n offset?: number\n}\n\nexport interface ConsumePeerRecordOptions extends AbortOptions {\n expectedPeer?: PeerId\n}\n\nexport interface PeerStore {\n /**\n * Loop over every peer - the looping is async because we read from a\n * datastore but the peer operation is sync, this is to prevent\n * long-lived peer operations causing deadlocks over the datastore\n * which can happen if they try to access the peer store during the\n * loop\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.forEach(peer => {\n * // ...\n * })\n * ```\n */\n forEach(fn: (peer: Peer) => void, query?: PeerQuery): Promise<void>\n\n /**\n * Returns all peers in the peer store.\n *\n * @example\n *\n * ```TypeScript\n * for (const peer of await peerStore.all()) {\n * // ...\n * }\n * ```\n */\n all(query?: PeerQuery): Promise<Peer[]>\n\n /**\n * Delete all data stored for the passed peer\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.addressBook.set(peerId, multiaddrs)\n * await peerStore.addressBook.get(peerId)\n * // multiaddrs[]\n *\n * await peerStore.delete(peerId)\n *\n * await peerStore.addressBook.get(peerId)\n * // []\n * ```\n */\n delete(peerId: PeerId, options?: AbortOptions): Promise<void>\n\n /**\n * Returns true if the passed PeerId is in the peer store\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.has(peerId)\n * // false\n * await peerStore.addressBook.add(peerId, multiaddrs)\n * await peerStore.has(peerId)\n * // true\n * ```\n */\n has(peerId: PeerId, options?: AbortOptions): Promise<boolean>\n\n /**\n * Returns all data stored for the passed PeerId\n *\n * @example\n *\n * ```TypeScript\n * const peer = await peerStore.get(peerId)\n * // { .. }\n * ```\n */\n get(peerId: PeerId, options?: AbortOptions): Promise<Peer>\n\n /**\n * Returns a PeerInfo object for the passed peer id. This is similar to `get`\n * except the returned value contains fewer fields and is often used to\n * exchange peer information with other systems.\n *\n * The returned object can be passed to `JSON.stringify` without any\n * additional processing.\n *\n * @see https://docs.libp2p.io/concepts/fundamentals/peers/#peer-info\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await peerStore.getInfo(peerId)\n *\n * console.info(JSON.stringify(peerInfo))\n * // {\n * // id: 'peerId'\n * // multiaddrs: [\n * // '...'\n * // ]\n * // }\n * ```\n */\n getInfo (peerId: PeerId, options?: AbortOptions): Promise<PeerInfo>\n\n /**\n * Adds a peer to the peer store, overwriting any existing data\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.save(peerId, {\n * multiaddrs\n * })\n * ```\n */\n save(id: PeerId, data: PeerData, options?: AbortOptions): Promise<Peer>\n\n /**\n * Adds a peer to the peer store, overwriting only the passed fields\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.patch(peerId, {\n * multiaddrs\n * })\n * ```\n */\n patch(id: PeerId, data: PeerData, options?: AbortOptions): Promise<Peer>\n\n /**\n * Adds a peer to the peer store, deeply merging any existing data.\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.merge(peerId, {\n * multiaddrs\n * })\n * ```\n */\n merge(id: PeerId, data: PeerData, options?: AbortOptions): Promise<Peer>\n\n /**\n * Unmarshal and verify a signed peer record, extract the multiaddrs and\n * overwrite the stored addresses for the peer.\n *\n * Optionally pass an expected PeerId to verify that the peer record was\n * signed by that peer.\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.consumePeerRecord(buf, expectedPeer)\n * ```\n */\n consumePeerRecord(buf: Uint8Array, options?: ConsumePeerRecordOptions): Promise<boolean>\n}\n", "/**\n * Implemented by components that have a life cycle\n */\nexport interface Startable {\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?(): void | Promise<void>\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?(): void | Promise<void>\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?(): void | Promise<void>\n}\n\n/**\n * Returns `true` if the object has type overlap with `Startable`\n */\nexport function isStartable (obj?: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\n/**\n * A function that can be used to start and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { start } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await start(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function start (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\n/**\n * A function that can be used to stop and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { stop } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await stop(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function stop (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n", "import type { AbortOptions, ClearableSignal, ConnectionEncrypter, MultiaddrConnection, Connection, ConnectionLimits, StreamMuxerFactory, PeerId } from './index.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\nexport interface ListenerEvents {\n /**\n * This event signals to the transport manager that the listening addresses\n * have changed and may be emitted at any point and/or multiple times\n */\n listening: CustomEvent\n\n /**\n * Emitted if listening on an address failed\n */\n error: CustomEvent<Error>\n\n /**\n * Emitted when the listener has been shut down, has no open connections and\n * will no longer accept new connections\n */\n close: CustomEvent\n}\n\nexport interface Listener extends TypedEventTarget<ListenerEvents> {\n /**\n * Start a listener\n */\n listen(multiaddr: Multiaddr): Promise<void>\n\n /**\n * Get listen addresses\n */\n getAddrs(): Multiaddr[]\n\n /**\n * Close listener\n *\n * @returns {Promise<void>}\n */\n close(): Promise<void>\n\n /**\n * Allows transports to amend announce addresses - to add certificate hashes\n * or other metadata that cannot be known before runtime\n */\n updateAnnounceAddrs(addrs: Multiaddr[]): void\n}\n\nexport const transportSymbol = Symbol.for('@libp2p/transport')\n\n/**\n * A filter that acts on a list of multiaddrs\n */\nexport interface MultiaddrFilter {\n (multiaddrs: Multiaddr[]): Multiaddr[]\n}\n\nexport interface CreateListenerOptions {\n /**\n * The upgrader turns a MultiaddrConnection into a Connection and notifies\n * other libp2p components about a new incoming connection.\n */\n upgrader: Upgrader\n}\n\nexport interface DialTransportOptions<DialEvents extends ProgressEvent = ProgressEvent> extends Required<AbortOptions>, ProgressOptions<DialEvents> {\n /**\n * The upgrader turns a MultiaddrConnection into a Connection which should be\n * returned by the transport's dial method\n */\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport offers dial and listen methods to establish connections.\n */\nexport interface Transport<DialEvents extends ProgressEvent = ProgressEvent> {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [transportSymbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial(ma: Multiaddr, options: DialTransportOptions<DialEvents>): Promise<Connection>\n\n /**\n * Create transport listeners.\n */\n createListener(options: CreateListenerOptions): Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only addresses that are valid for\n * the transport to listen on\n */\n listenFilter: MultiaddrFilter\n\n /**\n * Takes a list of `Multiaddr`s and returns only addresses that are valid for\n * the transport to dial\n */\n dialFilter: MultiaddrFilter\n}\n\n/**\n * Used to disambiguate transport implementations\n */\nexport function isTransport (other?: any): other is Transport {\n return other != null && Boolean(other[transportSymbol])\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n\n/**\n * Options accepted by the upgrader during connection establishment\n */\nexport interface UpgraderOptions<ConnectionUpgradeEvents extends ProgressEvent = ProgressEvent> extends ProgressOptions<ConnectionUpgradeEvents>, Required<AbortOptions> {\n /**\n * If true no connection protection will be performed on the connection.\n */\n skipProtection?: boolean\n\n /**\n * By default a stream muxer protocol will be negotiated via multi-stream\n * select after an encryption protocol has been agreed on.\n *\n * If a transport provides it's own stream muxing facility pass a muxer\n * factory instance here to skip muxer negotiation.\n */\n muxerFactory?: StreamMuxerFactory\n\n /**\n * If the connection is to have limits applied to it, pass them here\n */\n limits?: ConnectionLimits\n\n /**\n * Multi-stream select is a initiator/responder protocol. By default a\n * connection returned from `upgrader.upgradeOutbound` will be the initiator\n * and one returned from `upgrader.upgradeInbound` will be the responder.\n *\n * Pass a value here to override the default.\n */\n initiator?: boolean\n}\n\n/**\n * Options accepted by the upgrader during connection establishment\n */\nexport interface UpgraderWithoutEncryptionOptions extends UpgraderOptions {\n /**\n * If true the invoking transport is expected to implement it's own encryption\n * and an encryption protocol will not attempted to be negotiated via\n * multi-stream select\n */\n skipEncryption: true\n\n /**\n * If `skipEncryption` is true, a remote PeerId must be supplied\n */\n remotePeer: PeerId\n}\n\nexport type InboundConnectionUpgradeEvents =\nProgressEvent<'upgrader:encrypt-inbound-connection'> |\nProgressEvent<'upgrader:multiplex-inbound-connection'>\n\nexport type OutboundConnectionUpgradeEvents =\nProgressEvent<'upgrader:encrypt-outbound-connection'> |\nProgressEvent<'upgrader:multiplex-outbound-connection'>\n\nexport interface Upgrader {\n /**\n * Upgrades an outbound connection created by the `dial` method of a transport\n */\n upgradeOutbound(maConn: MultiaddrConnection, opts: UpgraderOptions<OutboundConnectionUpgradeEvents>): Promise<Connection>\n upgradeOutbound(maConn: MultiaddrConnection, opts: UpgraderWithoutEncryptionOptions): Promise<Connection>\n\n /**\n * Upgrades an inbound connection received by a transport listener and\n * notifies other libp2p components about the new connection\n */\n upgradeInbound(maConn: MultiaddrConnection, opts: UpgraderOptions<InboundConnectionUpgradeEvents>): Promise<void>\n upgradeInbound(maConn: MultiaddrConnection, opts: UpgraderWithoutEncryptionOptions): Promise<void>\n\n /**\n * Used by transports that perform part of the upgrade process themselves and\n * do some async work. This allows configuring inbound upgrade timeouts from a\n * single location.\n *\n * Regular transports should just pass the signal from their shutdown\n * controller to `upgradeInbound`.\n */\n createInboundAbortSignal (signal: AbortSignal): ClearableSignal\n\n /**\n * Returns configured stream muxers\n */\n getStreamMuxers (): Map<string, StreamMuxerFactory>\n\n /**\n * Returns configured connection encrypters\n */\n getConnectionEncrypters (): Map<string, ConnectionEncrypter>\n}\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.js'\nimport type { Stream } from './stream.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './connection-protector.js'\nexport * from './content-routing.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './keys.js'\nexport * from './message-stream.js'\nexport * from './metrics.js'\nexport * from './multiaddr-connection.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './record.js'\nexport * from './startable.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './stream.js'\nexport * from './topology.js'\nexport * from './transport.js'\n\nexport * from 'main-event'\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { return new Uint8Array(o) }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n", "import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\nimport type { DigestOptions } from './hasher.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`)\n }\n\n input = input.subarray(0, options.truncate)\n }\n\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce<string[]>((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce<number[]>((p, c, i) => {\n const codePoint = c.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`)\n }\n p[codePoint] = i\n return p\n}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const codePoint = char.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`)\n }\n const byt = alphabetCharsToBytes[codePoint]\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise<Uint8Array> {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nconst DEFAULT_MIN_DIGEST_LENGTH = 20\n\nexport interface HasherInit <Name extends string, Code extends number> {\n name: Name\n code: Code\n encode(input: Uint8Array): Await<Uint8Array>\n\n /**\n * The minimum length a hash is allowed to be truncated to in bytes\n *\n * @default 20\n */\n minDigestLength?: number\n\n /**\n * The maximum length a hash is allowed to be truncated to in bytes. If not\n * specified it will be inferred from the length of the digest.\n */\n maxDigestLength?: number\n}\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode, minDigestLength, maxDigestLength }: HasherInit<Name, Code>): Hasher<Name, Code> {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength)\n}\n\nexport interface DigestOptions {\n /**\n * Truncate the returned digest to this number of bytes.\n *\n * This may cause the digest method to throw/reject if the passed value is\n * greater than the digest length or below a threshold under which the risk of\n * hash collisions is significant.\n *\n * The actual value of this threshold can depend on the hashing algorithm in\n * use.\n */\n truncate?: number\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n readonly minDigestLength: number\n readonly maxDigestLength?: number\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>, minDigestLength?: number, maxDigestLength?: number) {\n this.name = name\n this.code = code\n this.encode = encode\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH\n this.maxDigestLength = maxDigestLength\n }\n\n digest (input: Uint8Array, options?: DigestOptions): Await<Digest.Digest<Code, number>> {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`)\n }\n\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)\n }\n }\n\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate)\n }\n\n return result.then(digest => createDigest(digest, this.code, options?.truncate))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest <Code extends number> (digest: Uint8Array, code: Code, truncate?: number): Digest.Digest<Code, number> {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`)\n }\n\n digest = digest.subarray(0, truncate)\n }\n\n return Digest.create(code, digest)\n}\n", "import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec<any> {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record<SupportedEncodings, MultibaseCodec<any>> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\n\ninterface Context {\n offset: number\n}\n\nconst TAG_MASK = parseInt('11111', 2)\nconst LONG_LENGTH_MASK = parseInt('10000000', 2)\nconst LONG_LENGTH_BYTES_MASK = parseInt('01111111', 2)\n\ninterface Decoder {\n (buf: Uint8Array, context: Context): any\n}\n\nconst decoders: Record<number, Decoder> = {\n 0x0: readSequence,\n 0x1: readSequence,\n 0x2: readInteger,\n 0x3: readBitString,\n 0x4: readOctetString,\n 0x5: readNull,\n 0x6: readObjectIdentifier,\n 0x10: readSequence,\n 0x16: readSequence,\n 0x30: readSequence\n}\n\nexport function decodeDer (buf: Uint8Array, context: Context = { offset: 0 }): any {\n const tag = buf[context.offset] & TAG_MASK\n context.offset++\n\n if (decoders[tag] != null) {\n return decoders[tag](buf, context)\n }\n\n throw new Error('No decoder for tag ' + tag)\n}\n\nfunction readLength (buf: Uint8Array, context: Context): number {\n let length = 0\n\n if ((buf[context.offset] & LONG_LENGTH_MASK) === LONG_LENGTH_MASK) {\n // long length\n const count = buf[context.offset] & LONG_LENGTH_BYTES_MASK\n let str = '0x'\n context.offset++\n\n for (let i = 0; i < count; i++, context.offset++) {\n str += buf[context.offset].toString(16).padStart(2, '0')\n }\n\n length = parseInt(str, 16)\n } else {\n length = buf[context.offset]\n context.offset++\n }\n\n return length\n}\n\nfunction readSequence (buf: Uint8Array, context: Context): any[] {\n readLength(buf, context)\n const entries: any[] = []\n\n while (true) {\n if (context.offset >= buf.byteLength) {\n break\n }\n\n const result = decodeDer(buf, context)\n\n if (result === null) {\n break\n }\n\n entries.push(result)\n }\n\n return entries\n}\n\nfunction readInteger (buf: Uint8Array, context: Context): Uint8Array {\n const length = readLength(buf, context)\n const start = context.offset\n const end = context.offset + length\n\n const vals: number[] = []\n\n for (let i = start; i < end; i++) {\n if (i === start && buf[i] === 0) {\n continue\n }\n\n vals.push(buf[i])\n }\n\n context.offset += length\n\n return Uint8Array.from(vals)\n}\n\nfunction readObjectIdentifier (buf: Uint8Array, context: Context): string {\n const count = readLength(buf, context)\n const finalOffset = context.offset + count\n\n const byte = buf[context.offset]\n context.offset++\n\n let val1 = 0\n let val2 = 0\n\n if (byte < 40) {\n val1 = 0\n val2 = byte\n } else if (byte < 80) {\n val1 = 1\n val2 = byte - 40\n } else {\n val1 = 2\n val2 = byte - 80\n }\n\n let oid = `${val1}.${val2}`\n let num: number[] = []\n\n while (context.offset < finalOffset) {\n const byte = buf[context.offset]\n context.offset++\n\n // remove msb\n num.push(byte & 0b01111111)\n\n if (byte < 128) {\n num.reverse()\n\n // reached the end of the encoding\n let val = 0\n\n for (let i = 0; i < num.length; i++) {\n val += num[i] << (i * 7)\n }\n\n oid += `.${val}`\n num = []\n }\n }\n\n return oid\n}\n\nfunction readNull (buf: Uint8Array, context: Context): null {\n context.offset++\n\n return null\n}\n\nfunction readBitString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const unusedBits = buf[context.offset]\n context.offset++\n const bytes = buf.subarray(context.offset, context.offset + length - 1)\n context.offset += length\n\n if (unusedBits !== 0) {\n // need to shift all bytes along by this many bits\n throw new Error('Unused bits in bit string is unimplemented')\n }\n\n return bytes\n}\n\nfunction readOctetString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const bytes = buf.subarray(context.offset, context.offset + length)\n context.offset += length\n\n return bytes\n}\n\nfunction encodeNumber (value: number): Uint8ArrayList {\n let number = value.toString(16)\n\n if (number.length % 2 === 1) {\n number = '0' + number\n }\n\n const array = new Uint8ArrayList()\n\n for (let i = 0; i < number.length; i += 2) {\n array.append(Uint8Array.from([parseInt(`${number[i]}${number[i + 1]}`, 16)]))\n }\n\n return array\n}\n\nfunction encodeLength (bytes: { byteLength: number }): Uint8Array | Uint8ArrayList {\n if (bytes.byteLength < 128) {\n return Uint8Array.from([bytes.byteLength])\n }\n\n // long length\n const length = encodeNumber(bytes.byteLength)\n\n return new Uint8ArrayList(\n Uint8Array.from([\n length.byteLength | LONG_LENGTH_MASK\n ]),\n length\n )\n}\n\nexport function encodeInteger (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const contents = new Uint8ArrayList()\n\n const mask = 0b10000000\n const positive = (value.subarray()[0] & mask) === mask\n\n if (positive) {\n contents.append(Uint8Array.from([0]))\n }\n\n contents.append(value)\n\n return new Uint8ArrayList(\n Uint8Array.from([0x02]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeBitString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n // unused bits is always 0 with full-byte-only values\n const unusedBits = Uint8Array.from([0])\n\n const contents = new Uint8ArrayList(\n unusedBits,\n value\n )\n\n return new Uint8ArrayList(\n Uint8Array.from([0x03]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeOctetString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n return new Uint8ArrayList(\n Uint8Array.from([0x04]),\n encodeLength(value),\n value\n )\n}\n\nexport function encodeSequence (values: Array<Uint8Array | Uint8ArrayList>, tag = 0x30): Uint8ArrayList {\n const output = new Uint8ArrayList()\n\n for (const buf of values) {\n output.append(\n buf\n )\n }\n\n return new Uint8ArrayList(\n Uint8Array.from([tag]),\n encodeLength(output),\n output\n )\n}\n", "import type { JWKKeyPair } from '../interface.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport type Curve = 'P-256' | 'P-384' | 'P-521'\n\nexport const ECDSA_P_256_OID = '1.2.840.10045.3.1.7'\nexport const ECDSA_P_384_OID = '1.3.132.0.34'\nexport const ECDSA_P_521_OID = '1.3.132.0.35'\n\nexport async function generateECDSAKey (curve: Curve = 'P-256'): Promise<JWKKeyPair> {\n const keyPair = await crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: curve\n }, true, ['sign', 'verify'])\n\n return {\n publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey),\n privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n }\n}\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<Uint8Array> {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign'])\n options?.signal?.throwIfAborted()\n\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, msg.subarray())\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(signature, 0, signature.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<boolean> {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify'])\n options?.signal?.throwIfAborted()\n\n const result = await crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, sig, msg.subarray())\n options?.signal?.throwIfAborted()\n\n return result\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { decodeDer, encodeBitString, encodeInteger, encodeOctetString, encodeSequence } from '../rsa/der.js'\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass, ECDSAPublicKey as ECDSAPublicKeyClass } from './ecdsa.js'\nimport { generateECDSAKey } from './index.js'\nimport type { Curve } from '../ecdh/index.js'\nimport type { ECDSAPublicKey, ECDSAPrivateKey } from '@libp2p/interface'\n\n// 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)\nconst OID_256 = Uint8Array.from([0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07])\n// 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)\nconst OID_384 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22])\n// 1.3.132.0.35 secp521r1 (SECG (Certicom) named elliptic curve)\nconst OID_521 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23])\n\nconst P_256_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-256'\n}\n\nconst P_384_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-384'\n}\n\nconst P_521_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-521'\n}\n\nconst P_256_KEY_LENGTH = 32\nconst P_384_KEY_LENGTH = 48\nconst P_521_KEY_LENGTH = 66\n\nexport function unmarshalECDSAPrivateKey (bytes: Uint8Array): ECDSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkiMessageToECDSAPrivateKey(message)\n}\n\nexport function pkiMessageToECDSAPrivateKey (message: any): ECDSAPrivateKey {\n const privateKey = message[1]\n const d = uint8ArrayToString(privateKey, 'base64url')\n const coordinates: Uint8Array = message[2][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (privateKey.byteLength === P_256_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n if (privateKey.byteLength === P_384_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n if (privateKey.byteLength === P_521_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n throw new InvalidParametersError(`Private key length was wrong length, got ${privateKey.byteLength}, expected 32, 48 or 66`)\n}\n\nexport function unmarshalECDSAPublicKey (bytes: Uint8Array): ECDSAPublicKey {\n const message = decodeDer(bytes)\n\n return pkiMessageToECDSAPublicKey(message)\n}\n\nexport function pkiMessageToECDSAPublicKey (message: any): ECDSAPublicKey {\n const coordinates = message[1][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (coordinates.byteLength === ((P_256_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n if (coordinates.byteLength === ((P_384_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n if (coordinates.byteLength === ((P_521_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n throw new InvalidParametersError(`coordinates were wrong length, got ${coordinates.byteLength}, expected 65, 97 or 133`)\n}\n\nexport function privateKeyToPKIMessage (privateKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeOctetString(uint8ArrayFromString(privateKey.d ?? '', 'base64url')), // body\n encodeSequence([ // PKIProtection\n getOID(privateKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n uint8ArrayFromString(privateKey.x ?? '', 'base64url'),\n uint8ArrayFromString(privateKey.y ?? '', 'base64url')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nexport function publicKeyToPKIMessage (publicKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeSequence([ // PKIProtection\n getOID(publicKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n uint8ArrayFromString(publicKey.x ?? '', 'base64url'),\n uint8ArrayFromString(publicKey.y ?? '', 'base64url')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction getOID (curve?: string): Uint8Array {\n if (curve === 'P-256') {\n return OID_256\n }\n\n if (curve === 'P-384') {\n return OID_384\n }\n\n if (curve === 'P-521') {\n return OID_521\n }\n\n throw new InvalidParametersError(`Invalid curve ${curve}`)\n}\n\nexport async function generateECDSAKeyPair (curve: Curve = 'P-256'): Promise<ECDSAPrivateKey> {\n const key = await generateECDSAKey(curve)\n\n return new ECDSAPrivateKeyClass(key.privateKey)\n}\n\nexport function ensureECDSAKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`)\n }\n return key\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { privateKeyToPKIMessage, publicKeyToPKIMessage } from './utils.js'\nimport { hashAndVerify, hashAndSign } from './index.js'\nimport type { ECDSAPublicKey as ECDSAPublicKeyInterface, ECDSAPrivateKey as ECDSAPrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class ECDSAPublicKey implements ECDSAPublicKeyInterface {\n public readonly type = 'ECDSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = publicKeyToPKIMessage(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n async verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array, options?: AbortOptions): Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data, options)\n }\n}\n\nexport class ECDSAPrivateKey implements ECDSAPrivateKeyInterface {\n public readonly type = 'ECDSA'\n public readonly jwk: JsonWebKey\n public readonly publicKey: ECDSAPublicKey\n private _raw?: Uint8Array\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n this.publicKey = new ECDSAPublicKey({\n crv: jwk.crv,\n ext: jwk.ext,\n key_ops: ['verify'],\n kty: 'EC',\n x: jwk.x,\n y: jwk.y\n })\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = privateKeyToPKIMessage(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n async sign (message: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<Uint8Array> {\n return hashAndSign(this.jwk, message, options)\n }\n}\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/** Merges default options and passed options. */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash<T> {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash constructor */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: HashInfo = {}\n): CHash<T, Opts> {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required<HashInfo> => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Uint8Array): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n isLE: boolean;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType<typeof FpSqrt> | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly<FpField> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.Point.Fn.ORDER)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n hexToBytes,\n isBytes,\n memoized,\n notImplemented,\n validateObject,\n randomBytes as wcRandomBytes,\n type FHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { type IField } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: string, zip215?: boolean): EdwardsPoint;\n}\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating \u221A(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n sign: (\n message: Uint8Array,\n secretKey: Uint8Array,\n options?: { context?: Uint8Array }\n ) => Uint8Array;\n verify: (\n sig: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n options?: { context?: Uint8Array; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const someonesPub = ed25519.utils.toMontgomery(someonesPub);\n * const aPriv = x25519.utils.randomSecretKey();\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv_ed = ed25519.utils.randomSecretKey();\n * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomerySecret: (secretKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Uint8Array) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aedpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('EdwardsPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) \u220B (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n\n static fromHex(hex: string, zip215 = false): Point {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: string): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || wcRandomBytes;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Uint8Array) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(cHash(key), 2 * len, 'hashedSecretKey');\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Uint8Array) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Uint8Array): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Uint8Array = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(\n msg: Uint8Array,\n secretKey: Uint8Array,\n options: { context?: Uint8Array } = {}\n ): Uint8Array {\n msg = abytes(msg, undefined, 'message');\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Uint8Array; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(\n sig: Uint8Array,\n msg: Uint8Array,\n publicKey: Uint8Array,\n options = verifyOpts\n ): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n };\n\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n }) satisfies Signer;\n}\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport { type AffinePoint } from './abstract/curve.ts';\nimport {\n eddsa,\n edwards,\n PrimeEdwardsPoint,\n type EdDSA,\n type EdDSAOpts,\n type EdwardsOpts,\n type EdwardsPoint,\n type EdwardsPointCons,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CDSTOpts,\n type H2CHasher,\n type H2CHasherBase,\n} from './abstract/hash-to-curve.ts';\nimport {\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts';\nimport { createORPF, type OPRF } from './abstract/oprf.ts';\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n asciiToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nfunction ed(opts: EdDSAOpts) {\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));\n}\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, pub); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, pub, { zip215: false });\n * ```\n */\nexport const ed25519: EdDSA = /* @__PURE__ */ ed({});\n/** Context version of ed25519 (ctx for domain separation). See {@link ed25519} */\nexport const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/** Prehashed version of ed25519. See {@link ed25519} */\nexport const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519: MontgomeryECDH = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u: bigint): {\n xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint\n} {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<EdwardsPointCons> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519_Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): EdwardsPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: EdwardsPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: string): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<typeof _RistrettoPoint> = {\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, we are using version from OPRF here, using bytes255ToNumblerLE will create different result if we use bytes255ToNumberLE as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg: Uint8Array, options?: H2CDSTOpts): _RistrettoPoint {\n // == 'hash_to_ristretto255'\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function 'ristretto255_map', in RFC 9496 map was function inside (per point)\n // That also lead to confustion that ristretto255_map is mapToCurve (it is not! it is old hashToCurve)\n return ristretto255_hasher.deriveToCurve!(xmd);\n },\n hashToScalar(msg: Uint8Array, options: H2CDSTOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction, preceding the finalization of RFC 9380.\n * It was later reused as a component in the newer `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes: Uint8Array): _RistrettoPoint {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n};\n\n/** ristretto255 OPRF, defined in RFC 9497. */\nexport const ristretto255_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n }))();\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * \u27E8T\u27E9 = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n", "/**\n * Signing a message failed\n */\nexport class SigningError extends Error {\n constructor (message = 'An error occurred while signing a message') {\n super(message)\n this.name = 'SigningError'\n }\n}\n\n/**\n * Verifying a message signature failed\n */\nexport class VerificationError extends Error {\n constructor (message = 'An error occurred while verifying a message') {\n super(message)\n this.name = 'VerificationError'\n }\n}\n\n/**\n * WebCrypto was not available in the current context\n */\nexport class WebCryptoMissingError extends Error {\n constructor (message = 'Missing Web Crypto API') {\n super(message)\n this.name = 'WebCryptoMissingError'\n }\n}\n", "/* eslint-env browser */\n\nimport { WebCryptoMissingError } from '../errors.js'\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto?.subtle == null) {\n throw new WebCryptoMissingError(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n )\n }\n\n return nativeCrypto\n }\n}\n", "import webcrypto from './webcrypto.js'\n\nexport default webcrypto\n", "import { ed25519 as ed } from '@noble/curves/ed25519.js'\nimport { toString as uint8arrayToString } from 'uint8arrays/to-string'\nimport crypto from '../../webcrypto/index.js'\nimport type { Uint8ArrayKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\n// memoize support result to skip additional awaits every time we use an ed key\nlet ed25519Supported: boolean | undefined\nconst webCryptoEd25519SupportedPromise = (async () => {\n try {\n await crypto.get().subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])\n return true\n } catch {\n return false\n }\n})()\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomSecretKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nasync function hashAndSignWebCrypto (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n let privateKeyRaw: Uint8Array\n if (privateKey.length === PRIVATE_KEY_BYTE_LENGTH) {\n privateKeyRaw = privateKey.subarray(0, 32)\n } else {\n privateKeyRaw = privateKey\n }\n\n const jwk: JsonWebKey = {\n crv: 'Ed25519',\n kty: 'OKP',\n x: uint8arrayToString(privateKey.subarray(32), 'base64url'),\n d: uint8arrayToString(privateKeyRaw, 'base64url'),\n ext: true,\n key_ops: ['sign']\n }\n\n const key = await crypto.get().subtle.importKey('jwk', jwk, { name: 'Ed25519' }, true, ['sign'])\n const sig = await crypto.get().subtle.sign({ name: 'Ed25519' }, key, msg instanceof Uint8Array ? msg : msg.subarray())\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport function hashAndSignNoble (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise\n }\n\n if (ed25519Supported) {\n return hashAndSignWebCrypto(privateKey, msg)\n }\n\n return hashAndSignNoble(privateKey, msg)\n}\n\nasync function hashAndVerifyWebCrypto (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n if (publicKey.buffer instanceof ArrayBuffer) {\n const key = await crypto.get().subtle.importKey('raw', publicKey.buffer, { name: 'Ed25519' }, false, ['verify'])\n const isValid = await crypto.get().subtle.verify({ name: 'Ed25519' }, key, sig, msg instanceof Uint8Array ? msg : msg.subarray())\n return isValid\n }\n\n throw new TypeError('WebCrypto does not support SharedArrayBuffer for Ed25519 keys')\n}\n\nexport function hashAndVerifyNoble (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise\n }\n\n if (ed25519Supported) {\n return hashAndVerifyWebCrypto(publicKey, sig, msg)\n }\n\n return hashAndVerifyNoble(publicKey, sig, msg)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) {\n throw new Error('byte array longer than desired length')\n }\n\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise <T = unknown> (thing: any): thing is Promise<T> {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../../util.ts'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { ensureEd25519Key } from './utils.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey as Ed25519PublicKeyInterface, Ed25519PrivateKey as Ed25519PrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey implements Ed25519PublicKeyInterface {\n public readonly type = 'Ed25519'\n public readonly raw: Uint8Array\n\n constructor (key: Uint8Array) {\n this.raw = ensureEd25519Key(key, crypto.publicKeyLength)\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n const result = crypto.hashAndVerify(this.raw, sig, data)\n\n if (isPromise<boolean>(result)) {\n return result.then(res => {\n options?.signal?.throwIfAborted()\n return res\n })\n }\n\n return result\n }\n}\n\nexport class Ed25519PrivateKey implements Ed25519PrivateKeyInterface {\n public readonly type = 'Ed25519'\n public readonly raw: Uint8Array\n public readonly publicKey: Ed25519PublicKey\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this.raw = ensureEd25519Key(key, crypto.privateKeyLength)\n this.publicKey = new Ed25519PublicKey(publicKey)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n options?.signal?.throwIfAborted()\n const sig = crypto.hashAndSign(this.raw, message)\n\n if (isPromise<Uint8Array>(sig)) {\n return sig.then(res => {\n options?.signal?.throwIfAborted()\n return res\n })\n }\n\n options?.signal?.throwIfAborted()\n return sig\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { Ed25519PublicKey as Ed25519PublicKeyClass, Ed25519PrivateKey as Ed25519PrivateKeyClass } from './ed25519.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey, Ed25519PrivateKey } from '@libp2p/interface'\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureEd25519Key(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKeyClass(bytes)\n}\n\nexport async function generateEd25519KeyPair (): Promise<Ed25519PrivateKey> {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKeyClass(privateKey, publicKey)\n}\n\nexport async function generateEd25519KeyPairFromSeed (seed: Uint8Array): Promise<Ed25519PrivateKey> {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKeyClass(privateKey, publicKey)\n}\n\nexport function ensureEd25519Key (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`)\n }\n return key\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\n\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 1: {\n buf[offset++] = (value & 0xFF)\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 1: {\n buf.set(offset++, (value & 0xFF))\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode <T extends Uint8Array | Uint8ArrayList = Uint8Array> (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n", "// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'decode'>, opts?: DecodeOptions<T>): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation<T> {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op<T> {\n /**\n * Function to call\n */\n public fn: WriterOperation<T>\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op<any>\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation<T>, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {}\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op<any>\n\n /**\n * Current tail\n */\n public tail: Op<any>\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction<T> {\n (value: Partial<T>, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map<any, any>\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits <T> = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits<T[K]>\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits <T> = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array<infer ElementType> ?\n (ElementType extends PrimitiveTypes ? never : Limits<ElementType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits <T> = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map<any, infer MapValueType> ?\n (MapValueType extends PrimitiveTypes ? never : Limits<MapValueType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// union of collection and array elements\ntype Limits<T> = Partial<CollectionLimits<T> & ArrayElementLimits<T> & MapValueLimits<T>>\n\nexport interface DecodeOptions<T> {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits<T>\n}\n\nexport interface DecodeFunction<T> {\n (reader: Reader, length?: number, opts?: DecodeOptions<T>): T\n}\n\nexport interface Codec<T> {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: CODEC_TYPES, encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<number | string> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { EncodeFunction, DecodeFunction, Codec } from '../codec.js'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec<any>\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\n/**\n * This will be removed in a future release\n *\n * @deprecated\n */\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string) {\n super(message)\n\n this.code = code\n }\n}\n\n/**\n * Thrown when a repeated field has too many elements\n */\nexport class MaxLengthError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_MAX_LENGTH'\n public name = 'MaxLengthError'\n}\n\n/**\n * Thrown when a map has too many elements\n */\nexport class MaxSizeError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_MAX_SIZE'\n public name = 'MaxSizeError'\n}\n\nexport class ParseError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_PARSE_ERROR'\n public name = 'ParseError'\n}\n\nexport class NoMessagesFoundError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_NO_MESSAGES_FOUND'\n public name = 'NoMessagesFoundError'\n}\n", "import { decodeMessage, encodeMessage, enumeration, message } from 'protons-runtime'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n secp256k1 = 'secp256k1',\n ECDSA = 'ECDSA'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n secp256k1 = 2,\n ECDSA = 3\n}\n\nexport namespace KeyType {\n export const codec = (): Codec<KeyType> => {\n return enumeration<KeyType>(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec<PublicKey>\n\n export const codec = (): Codec<PublicKey> => {\n if (_codec == null) {\n _codec = message<PublicKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PublicKey>): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): PublicKey => {\n return decodeMessage(buf, PublicKey.codec(), opts)\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec<PrivateKey>\n\n export const codec = (): Codec<PrivateKey> => {\n if (_codec == null) {\n _codec = message<PrivateKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PrivateKey>): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec(), opts)\n }\n}\n", "import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { create } from 'multiformats/hashes/digest'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as pb from '../keys.js'\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from './der.js'\nimport { RSAPrivateKey as RSAPrivateKeyClass, RSAPublicKey as RSAPublicKeyClass } from './rsa.js'\nimport { generateRSAKey, rsaKeySize } from './index.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { RSAPrivateKey, RSAPublicKey } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport const MAX_RSA_KEY_SIZE = 8192\nconst SHA2_256_CODE = 0x12\nconst MAX_RSA_JWK_SIZE = 1062\n\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n])\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToJwk(message)\n}\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1MessageToJwk (message: any): JsonWebKey {\n return {\n n: uint8ArrayToString(message[1], 'base64url'),\n e: uint8ArrayToString(message[2], 'base64url'),\n d: uint8ArrayToString(message[3], 'base64url'),\n p: uint8ArrayToString(message[4], 'base64url'),\n q: uint8ArrayToString(message[5], 'base64url'),\n dp: uint8ArrayToString(message[6], 'base64url'),\n dq: uint8ArrayToString(message[7], 'base64url'),\n qi: uint8ArrayToString(message[8], 'base64url'),\n kty: 'RSA'\n }\n}\n\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.d, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.p, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.q, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dp, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dq, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.qi, 'base64url'))\n ]).subarray()\n}\n\n/**\n * Convert a PKIX in ASN1 DER format to a JWK public key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToJwk(message)\n}\n\nexport function pkixMessageToJwk (message: any): JsonWebKey {\n const keys = decodeDer(message[1], {\n offset: 0\n })\n\n // this looks fragile but DER is a canonical format so we are safe to have\n // deeply property chains like this\n return {\n kty: 'RSA',\n n: uint8ArrayToString(\n keys[0],\n 'base64url'\n ),\n e: uint8ArrayToString(\n keys[1],\n 'base64url'\n )\n }\n}\n\n/**\n * Convert a JWK public key to PKIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(\n encodeSequence([\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url'))\n ])\n )\n ])\n\n return subjectPublicKeyInfo.subarray()\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1ToRSAPrivateKey (bytes: Uint8Array): RSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToRSAPrivateKey(message)\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1MessageToRSAPrivateKey (message: any): RSAPrivateKey {\n const jwk = pkcs1MessageToJwk(message)\n\n return jwkToRSAPrivateKey(jwk)\n}\n\n/**\n * Turn a PKIX message into a PublicKey\n */\nexport function pkixToRSAPublicKey (bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n if (bytes.byteLength >= MAX_RSA_JWK_SIZE) {\n throw new InvalidPublicKeyError('Key size is too large')\n }\n\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToRSAPublicKey(message, bytes, digest)\n}\n\nexport function pkixMessageToRSAPublicKey (message: any, bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n const jwk = pkixMessageToJwk(message)\n\n if (digest == null) {\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: bytes\n }))\n digest = create(SHA2_256_CODE, hash)\n }\n\n return new RSAPublicKeyClass(jwk, digest)\n}\n\nexport function jwkToRSAPrivateKey (jwk: JsonWebKey): RSAPrivateKey {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = jwkToJWKKeyPair(jwk)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\nexport async function generateRSAKeyPair (bits: number): Promise<RSAPrivateKey> {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = await generateRSAKey(bits)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\n/**\n * Takes a jwk key and returns a JWK KeyPair\n */\nexport function jwkToJWKKeyPair (key: JsonWebKey): JWKKeyPair {\n if (key == null) {\n throw new InvalidParametersError('Missing key parameter')\n }\n\n return {\n privateKey: key,\n publicKey: {\n kty: key.kty,\n n: key.n,\n e: key.e\n }\n }\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { hashAndSign, utils, hashAndVerify } from './index.js'\nimport type { RSAPublicKey as RSAPublicKeyInterface, RSAPrivateKey as RSAPrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class RSAPublicKey implements RSAPublicKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n private readonly _multihash: Digest<18, number>\n\n constructor (jwk: JsonWebKey, digest: Digest<18, number>) {\n this.jwk = jwk\n this._multihash = digest\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkix(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<18, number> {\n return this._multihash\n }\n\n toCID (): CID<unknown, 114, 18, 1> {\n return CID.createV1(114, this._multihash)\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array, options?: AbortOptions): boolean | Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data, options)\n }\n}\n\nexport class RSAPrivateKey implements RSAPrivateKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n public readonly publicKey: RSAPublicKey\n\n constructor (jwk: JsonWebKey, publicKey: RSAPublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkcs1(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.jwk, message, options)\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../../random-bytes.js'\nimport webcrypto from '../../webcrypto/index.js'\nimport * as utils from './utils.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const RSAES_PKCS1_V1_5_OID = '1.2.840.113549.1.1.1'\nexport { utils }\n\nexport async function generateRSAKey (bits: number, options?: AbortOptions): Promise<JWKKeyPair> {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n options?.signal?.throwIfAborted()\n\n const keys = await exportKey(pair, options)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<Uint8Array> {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n options?.signal?.throwIfAborted()\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<boolean> {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n options?.signal?.throwIfAborted()\n\n const result = await webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n options?.signal?.throwIfAborted()\n\n return result\n}\n\nasync function exportKey (pair: CryptoKeyPair, options?: AbortOptions): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required')\n }\n\n const result = await Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n options?.signal?.throwIfAborted()\n\n return result\n}\n\nexport function rsaKeySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('invalid key type')\n } else if (jwk.n == null) {\n throw new InvalidParametersError('invalid key modulus')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, key: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: _HMAC<T>): _HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC<any>;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC<any>(hash, key);\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abool,\n abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n memoized,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism \u03C8**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism \u03C8 transforms a point: `P = (x, y) \u21A6 \u03C8(P) = (\u03B2\u00B7x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k \u2261 k\u2081 + k\u2082\u00B7\u03BB (mod n)`\n * 3. Then these are combined: `k\u00B7P = k\u2081\u00B7P + k\u2082\u00B7\u03C8(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: \u03B2 \u2208 F\u209A with \u03B2\u00B3 = 1, \u03B2 \u2260 1\n * * lambda: \u03BB \u2208 F\u2099 with \u03BB\u00B3 = 1, \u03BB \u2260 1\n * * splitScalar decomposes k \u21A6 k\u2081, k\u2082, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-\u03BB, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * https://paulmillr.com/posts/deterministic-signatures/\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates sigs with increased security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n opts: T,\n def: D\n): Required<ECDSASignOpts> {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required<ECDSASignOpts>;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n CURVE(): WeierstrassOpts<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\nexport type WeierstrassExtraOpts<T> = Partial<{\n Fp: IField<T>;\n Fn: IField<bigint>;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n fromBytes: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: (key: Uint8Array, message: Uint8Array) => Uint8Array;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed?: boolean\n ) => Uint8Array;\n Point: WeierstrassPointCons<bigint>;\n utils: {\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Uint8Array, secretKey: Uint8Array, opts?: ECDSASignOpts) => Uint8Array;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes: Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass<T>(\n params: WeierstrassOpts<T>,\n extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts<T>;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x\u00B2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) \u220B (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint<T> => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint<T> {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts<T> {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than na\u00EFve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint<T> {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n hasHighS(): boolean;\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint<bigint>;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n}\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASignatureFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: IField<T>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths<T>(Fp: IField<T>, Fn: IField<bigint>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons<bigint>,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: Uint8Array) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey: Uint8Array, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: Uint8Array): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item)) return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey) return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed = true\n ): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons<bigint>,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required<ECDSASignOpts> = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor(): void {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: Uint8Array,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint<bigint> {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASignatureFormat = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: Uint8Array): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts = {}): Uint8Array {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg<Signature>(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1\u22C5G + u2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1\u22C5G + u2\u22C5P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n }) satisfies Signer;\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts<bigint> = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toBytes(true).slice(1);\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: Uint8Array) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Uint8Array): Uint8Array {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Uint8Array,\n secretKey: Uint8Array,\n auxRand: Uint8Array = randomBytes(32)\n): Uint8Array {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!Fn.isValidNot0(s)) return false;\n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons<bigint>;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\n", "import { secp256k1 as secp } from '@noble/curves/secp256k1.js'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { SigningError, VerificationError } from '../../errors.js'\nimport { isPromise } from '../../util.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 33\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted()\n return secp.sign(digest, key, {\n prehash: false,\n format: 'der'\n })\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err\n }\n\n throw new SigningError(String(err))\n })\n }\n\n try {\n return secp.sign(p.digest, key, {\n prehash: false,\n format: 'der'\n })\n } catch (err) {\n throw new SigningError(String(err))\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): boolean | Promise<boolean> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted()\n return secp.verify(sig, digest, key, {\n prehash: false,\n format: 'der'\n })\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err\n }\n\n throw new VerificationError(String(err))\n })\n }\n\n try {\n options?.signal?.throwIfAborted()\n return secp.verify(sig, p.digest, key, {\n prehash: false,\n format: 'der'\n })\n } catch (err) {\n throw new VerificationError(String(err))\n }\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { validateSecp256k1PublicKey, compressSecp256k1PublicKey, computeSecp256k1PublicKey, validateSecp256k1PrivateKey } from './utils.js'\nimport { hashAndVerify, hashAndSign } from './index.js'\nimport type { Secp256k1PublicKey as Secp256k1PublicKeyInterface, Secp256k1PrivateKey as Secp256k1PrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey implements Secp256k1PublicKeyInterface {\n public readonly type = 'secp256k1'\n public readonly raw: Uint8Array\n public readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = validateSecp256k1PublicKey(key)\n this.raw = compressSecp256k1PublicKey(this._key)\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array, options?: AbortOptions): boolean {\n return hashAndVerify(this._key, sig, data, options)\n }\n}\n\nexport class Secp256k1PrivateKey implements Secp256k1PrivateKeyInterface {\n public readonly type = 'secp256k1'\n public readonly raw: Uint8Array\n public readonly publicKey: Secp256k1PublicKey\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this.raw = validateSecp256k1PrivateKey(key)\n this.publicKey = new Secp256k1PublicKey(publicKey ?? computeSecp256k1PublicKey(key))\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.raw, message, options)\n }\n}\n", "import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js'\nimport { Secp256k1PublicKey as Secp256k1PublicKeyClass, Secp256k1PrivateKey as Secp256k1PrivateKeyClass } from './secp256k1.js'\nimport type { Secp256k1PublicKey, Secp256k1PrivateKey } from '@libp2p/interface'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKeyClass(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKeyClass(bytes)\n}\n\nexport async function generateSecp256k1KeyPair (): Promise<Secp256k1PrivateKey> {\n const privateKeyBytes = generateSecp256k1PrivateKey()\n return new Secp256k1PrivateKeyClass(privateKeyBytes)\n}\n\nexport function compressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n return secp.Point.fromBytes(key).toBytes()\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n return secp.Point.fromBytes(key).toBytes(false)\n}\n\nexport function validateSecp256k1PrivateKey (key: Uint8Array): Uint8Array {\n try {\n secp.getPublicKey(key, true)\n\n return key\n } catch (err) {\n throw new InvalidPrivateKeyError(String(err))\n }\n}\n\nexport function validateSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n try {\n secp.Point.fromBytes(key)\n\n return key\n } catch (err) {\n throw new InvalidPublicKeyError(String(err))\n }\n}\n\nexport function computeSecp256k1PublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new InvalidPrivateKeyError(String(err))\n }\n}\n\nexport function generateSecp256k1PrivateKey (): Uint8Array {\n return secp.utils.randomSecretKey()\n}\n", "/**\n * @packageDocumentation\n *\n * ## Supported Key Types\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass } from './ecdsa/ecdsa.js'\nimport { ECDSA_P_256_OID, ECDSA_P_384_OID, ECDSA_P_521_OID } from './ecdsa/index.js'\nimport { generateECDSAKeyPair, pkiMessageToECDSAPrivateKey, pkiMessageToECDSAPublicKey, unmarshalECDSAPrivateKey, unmarshalECDSAPublicKey } from './ecdsa/utils.js'\nimport { privateKeyLength as ed25519PrivateKeyLength, publicKeyLength as ed25519PublicKeyLength } from './ed25519/index.js'\nimport { generateEd25519KeyPair, generateEd25519KeyPairFromSeed, unmarshalEd25519PrivateKey, unmarshalEd25519PublicKey } from './ed25519/utils.js'\nimport * as pb from './keys.js'\nimport { decodeDer } from './rsa/der.js'\nimport { RSAES_PKCS1_V1_5_OID } from './rsa/index.js'\nimport { pkcs1ToRSAPrivateKey, pkixToRSAPublicKey, generateRSAKeyPair, pkcs1MessageToRSAPrivateKey, pkixMessageToRSAPublicKey, jwkToRSAPrivateKey } from './rsa/utils.js'\nimport { privateKeyLength as secp256k1PrivateKeyLength, publicKeyLength as secp256k1PublicKeyLength } from './secp256k1/index.js'\nimport { generateSecp256k1KeyPair, unmarshalSecp256k1PrivateKey, unmarshalSecp256k1PublicKey } from './secp256k1/utils.js'\nimport type { Curve } from './ecdsa/index.js'\nimport type { PrivateKey, PublicKey, KeyType, RSAPrivateKey, Secp256k1PrivateKey, Ed25519PrivateKey, Secp256k1PublicKey, Ed25519PublicKey, ECDSAPrivateKey, ECDSAPublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport { generateEphemeralKeyPair } from './ecdh/index.js'\nexport type { Curve } from './ecdh/index.js'\nexport type { ECDHKey, EnhancedKey, EnhancedKeyPair, ECDHKeyPair } from './interface.js'\nexport { keyStretcher } from './key-stretcher.js'\n\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair (type: 'Ed25519'): Promise<Ed25519PrivateKey>\nexport async function generateKeyPair (type: 'secp256k1'): Promise<Secp256k1PrivateKey>\nexport async function generateKeyPair (type: 'ECDSA', curve?: Curve): Promise<ECDSAPrivateKey>\nexport async function generateKeyPair (type: 'RSA', bits?: number): Promise<RSAPrivateKey>\nexport async function generateKeyPair (type: KeyType, bits?: number): Promise<PrivateKey>\nexport async function generateKeyPair (type: KeyType, bits?: number | string): Promise<unknown> {\n if (type === 'Ed25519') {\n return generateEd25519KeyPair()\n }\n\n if (type === 'secp256k1') {\n return generateSecp256k1KeyPair()\n }\n\n if (type === 'RSA') {\n return generateRSAKeyPair(toBits(bits))\n }\n\n if (type === 'ECDSA') {\n return generateECDSAKeyPair(toCurve(bits))\n }\n\n throw new UnsupportedKeyTypeError()\n}\n\n/**\n * Generates a keypair of the given type from the passed seed. Currently only\n * supports Ed25519 keys.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: 'Ed25519', seed: Uint8Array): Promise<Ed25519PrivateKey>\nexport async function generateKeyPairFromSeed <T extends KeyType> (type: T, seed: Uint8Array, bits?: number): Promise<never>\nexport async function generateKeyPairFromSeed (type: string, seed: Uint8Array): Promise<unknown> {\n if (type !== 'Ed25519') {\n throw new UnsupportedKeyTypeError('Seed key derivation only supported for Ed25519 keys')\n }\n\n return generateEd25519KeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object.\n *\n * For RSA public keys optionally pass the multihash digest of the public key if\n * it is known. If the digest is omitted it will be calculated which can be\n * expensive.\n *\n * For other key types the digest option is ignored.\n */\nexport function publicKeyFromProtobuf (buf: Uint8Array, digest?: Digest<18, number>): PublicKey {\n const { Type, Data } = pb.PublicKey.decode(buf)\n const data = Data ?? new Uint8Array()\n\n switch (Type) {\n case pb.KeyType.RSA:\n return pkixToRSAPublicKey(data, digest)\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Creates a public key from the raw key bytes\n */\nexport function publicKeyFromRaw (buf: Uint8Array): PublicKey {\n if (buf.byteLength === ed25519PublicKeyLength) {\n return unmarshalEd25519PublicKey(buf)\n } else if (buf.byteLength === secp256k1PublicKeyLength) {\n return unmarshalSecp256k1PublicKey(buf)\n }\n\n const message = decodeDer(buf)\n const ecdsaOid = message[1]?.[0]\n\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPublicKey(message)\n }\n\n if (message[0]?.[0] === RSAES_PKCS1_V1_5_OID) {\n return pkixMessageToRSAPublicKey(message, buf)\n }\n\n throw new InvalidParametersError('Could not extract public key from raw bytes')\n}\n\n/**\n * Creates a public key from an identity multihash which contains a protobuf\n * encoded Ed25519 or secp256k1 public key.\n *\n * RSA keys are not supported as in practice we they are not stored in identity\n * multihash since the hash would be very large.\n */\nexport function publicKeyFromMultihash (digest: MultihashDigest<0x0>): Ed25519PublicKey | Secp256k1PublicKey | ECDSAPublicKey {\n const { Type, Data } = pb.PublicKey.decode(digest.digest)\n const data = Data ?? new Uint8Array()\n\n switch (Type) {\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function publicKeyToProtobuf (key: PublicKey): Uint8Array {\n return pb.PublicKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n })\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport function privateKeyFromProtobuf (buf: Uint8Array): Ed25519PrivateKey | Secp256k1PrivateKey | RSAPrivateKey | ECDSAPrivateKey {\n const decoded = pb.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case pb.KeyType.RSA:\n return pkcs1ToRSAPrivateKey(data)\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PrivateKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PrivateKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPrivateKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Creates a private key from the raw key bytes. For Ed25519 keys this requires\n * the public key to be appended to the private key otherwise we can't\n * differentiate between Ed25519 and secp256k1 keys as they are the same length.\n */\nexport function privateKeyFromRaw (buf: Uint8Array): PrivateKey {\n if (buf.byteLength === ed25519PrivateKeyLength) {\n return unmarshalEd25519PrivateKey(buf)\n } else if (buf.byteLength === secp256k1PrivateKeyLength) {\n return unmarshalSecp256k1PrivateKey(buf)\n }\n\n const message = decodeDer(buf)\n const ecdsaOid = message[2]?.[0]\n\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPrivateKey(message)\n }\n\n if (message.length > 8) {\n return pkcs1MessageToRSAPrivateKey(message)\n }\n\n throw new InvalidParametersError('Could not extract private key from raw bytes')\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function privateKeyToProtobuf (key: PrivateKey): Uint8Array {\n return pb.PrivateKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n })\n}\n\nfunction toBits (bits: any): number {\n if (bits == null) {\n return 2048\n }\n\n return parseInt(bits, 10)\n}\n\nfunction toCurve (curve: any): Curve {\n if (curve === 'P-256' || curve == null) {\n return 'P-256'\n }\n\n if (curve === 'P-384') {\n return 'P-384'\n }\n\n if (curve === 'P-521') {\n return 'P-521'\n }\n\n throw new InvalidParametersError('Unsupported curve, should be P-256, P-384 or P-521')\n}\n\n/**\n * Convert a libp2p RSA or ECDSA private key to a WebCrypto CryptoKeyPair\n */\nexport async function privateKeyToCryptoKeyPair (privateKey: PrivateKey): Promise<CryptoKeyPair> {\n if (privateKey.type === 'RSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify'])\n }\n }\n\n if (privateKey.type === 'ECDSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.jwk.crv ?? 'P-256'\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.publicKey.jwk.crv ?? 'P-256'\n }, true, ['verify'])\n }\n }\n\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported')\n}\n\n/**\n * Convert a RSA or ECDSA WebCrypto CryptoKeyPair to a libp2p private key\n */\nexport async function privateKeyFromCryptoKeyPair (keyPair: CryptoKeyPair): Promise<PrivateKey> {\n if (keyPair.privateKey.algorithm.name === 'RSASSA-PKCS1-v1_5') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n\n return jwkToRSAPrivateKey(jwk)\n }\n\n if (keyPair.privateKey.algorithm.name === 'ECDSA') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n\n return new ECDSAPrivateKeyClass(jwk)\n }\n\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported')\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { peerIdSymbol } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Ed25519PeerId as Ed25519PeerIdInterface, PeerIdType, RSAPeerId as RSAPeerIdInterface, URLPeerId as URLPeerIdInterface, Secp256k1PeerId as Secp256k1PeerIdInterface, PeerId, PublicKey, Ed25519PublicKey, Secp256k1PublicKey, RSAPublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\ninterface PeerIdInit <DigestCode extends number> {\n type: PeerIdType\n multihash: MultihashDigest<DigestCode>\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest<0x12>\n publicKey?: RSAPublicKey\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest<0x0>\n publicKey: Ed25519PublicKey\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest<0x0>\n publicKey: Secp256k1PublicKey\n}\n\nclass PeerIdImpl <DigestCode extends number> {\n public type: PeerIdType\n private readonly multihash: MultihashDigest<DigestCode>\n public readonly publicKey?: PublicKey\n private string?: string\n\n constructor (init: PeerIdInit<DigestCode>) {\n this.type = init.type\n this.multihash = init.multihash\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n toMultihash (): MultihashDigest<DigestCode> {\n return this.multihash\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID<Uint8Array, 0x72, DigestCode, 1> {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return this.toString() === id\n } else if (id?.toMultihash()?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.toMultihash().bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nexport class RSAPeerId extends PeerIdImpl<0x12> implements RSAPeerIdInterface {\n public readonly type = 'RSA'\n public readonly publicKey?: RSAPublicKey\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nexport class Ed25519PeerId extends PeerIdImpl<0x0> implements Ed25519PeerIdInterface {\n public readonly type = 'Ed25519'\n public readonly publicKey: Ed25519PublicKey\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.publicKey\n }\n}\n\nexport class Secp256k1PeerId extends PeerIdImpl<0x0> implements Secp256k1PeerIdInterface {\n public readonly type = 'secp256k1'\n public readonly publicKey: Secp256k1PublicKey\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.publicKey\n }\n}\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920\n\nexport class URLPeerId implements URLPeerIdInterface {\n readonly type = 'url'\n readonly multihash: MultihashDigest<0x0>\n readonly publicKey: undefined\n readonly url: string\n\n constructor (url: URL) {\n this.url = url.toString()\n this.multihash = identity.digest(uint8ArrayFromString(this.url))\n }\n\n [inspect] (): string {\n return `PeerId(${this.url})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n return this.toCID().toString()\n }\n\n toMultihash (): MultihashDigest<0x0> {\n return this.multihash\n }\n\n toCID (): CID<Uint8Array, 0x0920, 0x0, 1> {\n return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.toMultihash())\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n equals (other?: PeerId | Uint8Array | string): boolean {\n if (other == null) {\n return false\n }\n\n if (other instanceof Uint8Array) {\n other = uint8ArrayToString(other)\n }\n\n return other.toString() === this.toString()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { publicKeyFromMultihash } from '@libp2p/crypto/keys'\nimport { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RSAPeerId as RSAPeerIdClass, Ed25519PeerId as Ed25519PeerIdClass, Secp256k1PeerId as Secp256k1PeerIdClass, URLPeerId as URLPeerIdClass } from './peer-id.js'\nimport type { Ed25519PeerId, RSAPeerId, URLPeerId, Secp256k1PeerId, PeerId, PublicKey, Ed25519PublicKey, Secp256k1PublicKey, RSAPublicKey, Ed25519PrivateKey, Secp256k1PrivateKey, RSAPrivateKey, PrivateKey } from '@libp2p/interface'\nimport type { MultibaseDecoder } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {\n let multihash: MultihashDigest\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n multihash = Digest.decode(base58btc.decode(`z${str}`))\n } else if (str.startsWith('k51qzi5uqu5') || str.startsWith('kzwfwjn5ji4') || str.startsWith('k2k4r8') || str.startsWith('bafz')) {\n // base36 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa) or base32 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa)\n return peerIdFromCID(CID.parse(str))\n } else {\n if (decoder == null) {\n throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with \"1\" or \"Q\"')\n }\n\n multihash = Digest.decode(decoder.decode(str))\n }\n\n return peerIdFromMultihash(multihash)\n}\n\nexport function peerIdFromPublicKey (publicKey: Ed25519PublicKey): Ed25519PeerId\nexport function peerIdFromPublicKey (publicKey: Secp256k1PublicKey): Secp256k1PeerId\nexport function peerIdFromPublicKey (publicKey: RSAPublicKey): RSAPeerId\nexport function peerIdFromPublicKey (publicKey: PublicKey): PeerId\nexport function peerIdFromPublicKey (publicKey: PublicKey): PeerId {\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n } else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n } else if (publicKey.type === 'RSA') {\n return new RSAPeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n }\n\n throw new UnsupportedKeyTypeError()\n}\n\nexport function peerIdFromPrivateKey (privateKey: Ed25519PrivateKey): Ed25519PeerId\nexport function peerIdFromPrivateKey (privateKey: Secp256k1PrivateKey): Secp256k1PeerId\nexport function peerIdFromPrivateKey (privateKey: RSAPrivateKey): RSAPeerId\nexport function peerIdFromPrivateKey (privateKey: PrivateKey): PeerId\nexport function peerIdFromPrivateKey (privateKey: PrivateKey): PeerId {\n return peerIdFromPublicKey(privateKey.publicKey)\n}\n\nexport function peerIdFromMultihash (multihash: MultihashDigest): PeerId {\n if (isSha256Multihash(multihash)) {\n return new RSAPeerIdClass({ multihash })\n } else if (isIdentityMultihash(multihash)) {\n try {\n const publicKey = publicKeyFromMultihash(multihash)\n\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({ multihash, publicKey })\n } else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({ multihash, publicKey })\n }\n } catch (err) {\n // was not Ed or secp key, try URL\n const url = uint8ArrayToString(multihash.digest)\n\n return new URLPeerIdClass(new URL(url))\n }\n }\n\n throw new InvalidMultihashError('Supplied PeerID Multihash is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new InvalidCIDError('Supplied PeerID CID is invalid')\n }\n\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = uint8ArrayToString(cid.multihash.digest)\n\n return new URLPeerIdClass(new URL(url))\n }\n\n return peerIdFromMultihash(cid.multihash)\n}\n\nfunction isIdentityMultihash (multihash: MultihashDigest): multihash is MultihashDigest<0x0> {\n return multihash.code === identity.code\n}\n\nfunction isSha256Multihash (multihash: MultihashDigest): multihash is MultihashDigest<0x12> {\n return multihash.code === sha256.code\n}\n", "import { decodeMessage, encodeMessage, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec<Envelope>\n\n export const codec = (): Codec<Envelope> => {\n if (_codec == null) {\n _codec = message<Envelope>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n publicKey: uint8ArrayAlloc(0),\n payloadType: uint8ArrayAlloc(0),\n payload: uint8ArrayAlloc(0),\n signature: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.publicKey = reader.bytes()\n break\n }\n case 2: {\n obj.payloadType = reader.bytes()\n break\n }\n case 3: {\n obj.payload = reader.bytes()\n break\n }\n case 5: {\n obj.signature = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Envelope>): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Envelope>): Envelope => {\n return decodeMessage(buf, Envelope.codec(), opts)\n }\n}\n", "/**\n * The key in the record is not valid for the domain\n */\nexport class InvalidSignatureError extends Error {\n constructor (message = 'Invalid signature') {\n super(message)\n this.name = 'InvalidSignatureError'\n }\n}\n", "import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { InvalidSignatureError } from './errors.js'\nimport type { Record, Envelope, PrivateKey, PublicKey, AbortOptions } from '@libp2p/interface'\n\nexport interface RecordEnvelopeInit {\n publicKey: PublicKey\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = (data: Uint8Array | Uint8ArrayList): RecordEnvelope => {\n const envelopeData = Protobuf.decode(data)\n const publicKey = publicKeyFromProtobuf(envelopeData.publicKey)\n\n return new RecordEnvelope({\n publicKey,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, privateKey: PrivateKey, options?: AbortOptions): Promise<RecordEnvelope> => {\n if (privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n const signData = formatSignaturePayload(domain, payloadType, payload)\n const signature = await privateKey.sign(signData.subarray(), options)\n\n return new RecordEnvelope({\n publicKey: privateKey.publicKey,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshaled envelope.\n * Data is unmarshaled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array | Uint8ArrayList, domain: string, options?: AbortOptions): Promise<RecordEnvelope> => {\n const envelope = RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain, options)\n\n if (!valid) {\n throw new InvalidSignatureError('Envelope signature is not valid for the given domain')\n }\n\n return envelope\n }\n\n public publicKey: PublicKey\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { publicKey, payloadType, payload, signature } = init\n\n this.publicKey = publicKey\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: publicKeyToProtobuf(this.publicKey),\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other?: Envelope): boolean {\n if (other == null) {\n return false\n }\n\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string, options?: AbortOptions): Promise<boolean> {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n return this.publicKey.verify(signData.subarray(), this.signature, options)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = varint.encode(domainUint8Array.byteLength)\n const payloadTypeLength = varint.encode(payloadType.length)\n const payloadLength = varint.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n", "/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n name = 'InvalidMultiaddrError'\n}\n\nexport class ValidationError extends Error {\n static name = 'ValidationError'\n name = 'ValidationError'\n}\n\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n\nexport class UnknownProtocolError extends Error {\n static name = 'UnknownProtocolError'\n name = 'UnknownProtocolError'\n}\n", "/* eslint-disable @typescript-eslint/no-unsafe-return */\n\n// Heavily inspired by https://doc.rust-lang.org/src/std/net/parser.rs.html\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn = (...foo: any) => any;\n\nexport class Parser {\n private index = 0;\n private input = \"\";\n\n new(input: string): this {\n this.index = 0;\n this.input = input;\n return this;\n }\n\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically<T extends Fn>(fn: T): ReturnType<T> {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith<T extends Fn>(fn: T): ReturnType<T> | undefined {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n\n /** Peek the next character from the input */\n peekChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n\n /** Read the next character from the input */\n readChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target: string): string | undefined {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator<T extends Fn>(sep: string, index: number, inner: T): ReturnType<T> {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(\n radix: number,\n maxDigits: number | undefined,\n allowZeroPrefix: boolean,\n maxBytes: number\n ): number | undefined {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n\n if (digitCount === 0) {\n return undefined;\n } else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n } else {\n return result;\n }\n });\n }\n\n /** Read an IPv4 address. */\n readIPv4Addr(): Uint8Array | undefined {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n\n return out;\n });\n }\n\n /** Read an IPv6 Address. */\n readIPv6Addr(): Uint8Array | undefined {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups: Uint8Array): [number, boolean] => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n\n return [ix + 4, true];\n }\n }\n\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n\n if (headSize === 16) {\n return head;\n }\n\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n\n return head;\n });\n }\n\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr(): Uint8Array | undefined {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n", "import { Parser } from \"./parser.js\";\n\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\n\nconst parser = new Parser();\n\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n\n/** Parse IPv4 `input` into IPv6 with IPv4-mapped bytes, eg ::ffff:1.2.3.4 */\nexport function parseIPv4Mapped(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n\n const ipv4 = parser.new(input).parseWith(() => parser.readIPv4Addr());\n if (ipv4 === undefined) {\n return undefined;\n }\n\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, ipv4[0], ipv4[1], ipv4[2], ipv4[3]]);\n}\n\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input: string): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input: string, mapIPv4ToIPv6 = false): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n\n const addr = parser.new(input).parseWith(() => parser.readIPAddr());\n if (!addr) {\n return undefined;\n }\n\n if (mapIPv4ToIPv6 && addr.length === 4) {\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);\n }\n\n return addr;\n}\n", "import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n\n/** Check if `input` is IPv4. */\nexport function isIPv4(input: string): boolean {\n return Boolean(parseIPv4(input));\n}\n\n/** Check if `input` is IPv6. */\nexport function isIPv6(input: string): boolean {\n return Boolean(parseIPv6(input));\n}\n\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input: string): boolean {\n return Boolean(parseIP(input));\n}\n\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input: string): 4 | 6 | undefined {\n if (isIPv4(input)) {\n return 4;\n } else if (isIPv6(input)) {\n return 6;\n } else {\n return undefined;\n }\n}\n", "import { isIPv4 } from '@chainsafe/is-ip'\nimport { base32 } from 'multiformats/bases/base32'\nimport { bases } from 'multiformats/basics'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidMultiaddrError } from './errors.ts'\nimport type { MultibaseCodec } from 'multiformats'\nimport type { SupportedEncodings } from 'uint8arrays/to-string'\n\nexport function bytesToString (base: SupportedEncodings): (buf: Uint8Array) => string {\n return (buf) => {\n return uint8ArrayToString(buf, base)\n }\n}\n\nexport function stringToBytes (base: SupportedEncodings): (value: string) => Uint8Array {\n return (buf) => {\n return uint8ArrayFromString(buf, base)\n }\n}\n\nexport function bytes2port (buf: Uint8Array): string {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset).toString()\n}\n\nexport function port2bytes (port: string | number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, typeof port === 'string' ? parseInt(port) : port)\n\n return new Uint8Array(buf)\n}\n\nexport function onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = uint8ArrayFromString(addr[0], 'base32')\n\n // onion port number\n const port = parseInt(addr[1], 10)\n\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n\n const portBuf = port2bytes(port)\n\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nexport function onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n\n const portBuf = port2bytes(port)\n\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nexport function bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.subarray(0, buf.length - 2)\n const portBytes = buf.subarray(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const ip4ToBytes = function (ip: string): Uint8Array {\n ip = ip.toString().trim()\n\n const bytes = new Uint8Array(4)\n\n ip.split(/\\./g).forEach((byte, index) => {\n const value = parseInt(byte, 10)\n\n if (isNaN(value) || value < 0 || value > 0xff) {\n throw new InvalidMultiaddrError('Invalid byte value in IP address')\n }\n\n bytes[index] = value\n })\n\n return bytes\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const ip6ToBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isIPv4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = ip4ToBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.subarray(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.subarray(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) { sections.unshift('0') }\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) { sections.push('0') }\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++) { }\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n if (sections[i] === '') {\n sections[i] = '0'\n }\n\n const word = parseInt(sections[i], 16)\n\n if (isNaN(word) || word < 0 || word > 0xffff) {\n throw new InvalidMultiaddrError('Invalid byte value in IP address')\n }\n\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const ip4ToString = function (buf: Uint8Array): string {\n if (buf.byteLength !== 4) {\n throw new InvalidMultiaddrError('IPv4 address was incorrect length')\n }\n\n const result = []\n\n for (let i = 0; i < buf.byteLength; i++) {\n result.push(buf[i])\n }\n\n return result.join('.')\n}\n\nexport const ip6ToString = function (buf: Uint8Array): string {\n if (buf.byteLength !== 16) {\n throw new InvalidMultiaddrError('IPv6 address was incorrect length')\n }\n\n const result: string[] = []\n\n for (let i = 0; i < buf.byteLength; i += 2) {\n const byte1 = buf[i]\n const byte2 = buf[i + 1]\n\n const tuple = `${byte1.toString(16).padStart(2, '0')}${byte2.toString(16).padStart(2, '0')}`\n\n result.push(tuple)\n }\n\n const ip = result.join(':')\n\n try {\n const url = new URL(`http://[${ip}]`)\n\n return url.hostname.substring(1, url.hostname.length - 1)\n } catch {\n throw new InvalidMultiaddrError(`Invalid IPv6 address \"${ip}\"`)\n }\n}\n\nexport function ip6StringToValue (str: string): string {\n try {\n const url = new URL(`http://[${str}]`)\n\n return url.hostname.substring(1, url.hostname.length - 1)\n } catch {\n throw new InvalidMultiaddrError(`Invalid IPv6 address \"${str}\"`)\n }\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nexport function mb2bytes (mbstr: string): Uint8Array {\n return anybaseDecoder.decode(mbstr)\n}\n\nexport function bytes2mb (base: MultibaseCodec<any>): (buf: Uint8Array) => string {\n return (buf) => {\n return base.encoder.encode(buf)\n }\n}\n", "import { ValidationError } from './errors.ts'\n\nexport function integer (value: string): void {\n const int = parseInt(value)\n\n if (int.toString() !== value) {\n throw new ValidationError('Value must be an integer')\n }\n}\n\nexport function positive (value: any): void {\n if (value < 0) {\n throw new ValidationError('Value must be a positive integer, or zero')\n }\n}\n\nexport function maxValue (max: number): (value: any) => void {\n return (value) => {\n if (value > max) {\n throw new ValidationError(`Value must be smaller than or equal to ${max}`)\n }\n }\n}\n\nexport function validate (...funcs: Array<(value: string) => void>): (value: string) => void {\n return (value) => {\n for (const fn of funcs) {\n fn(value)\n }\n }\n}\n\nexport const validatePort = validate(\n integer,\n positive,\n maxValue(65_535)\n)\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { CID } from 'multiformats'\nimport { base64url } from 'multiformats/bases/base64'\nimport { CODE_CERTHASH, CODE_DCCP, CODE_DNS, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_GARLIC32, CODE_GARLIC64, CODE_HTTP, CODE_HTTP_PATH, CODE_HTTPS, CODE_IP4, CODE_IP6, CODE_IP6ZONE, CODE_IPCIDR, CODE_MEMORY, CODE_NOISE, CODE_ONION, CODE_ONION3, CODE_P2P, CODE_P2P_CIRCUIT, CODE_P2P_STARDUST, CODE_P2P_WEBRTC_DIRECT, CODE_P2P_WEBRTC_STAR, CODE_P2P_WEBSOCKET_STAR, CODE_QUIC, CODE_QUIC_V1, CODE_SCTP, CODE_SNI, CODE_TCP, CODE_TLS, CODE_UDP, CODE_UDT, CODE_UNIX, CODE_UTP, CODE_WEBRTC, CODE_WEBRTC_DIRECT, CODE_WEBTRANSPORT, CODE_WS, CODE_WSS } from './constants.ts'\nimport { UnknownProtocolError, ValidationError } from './errors.ts'\nimport { bytes2mb, bytes2onion, bytes2port, bytesToString, ip4ToBytes, ip4ToString, ip6StringToValue, ip6ToBytes, ip6ToString, mb2bytes, onion2bytes, onion32bytes, port2bytes, stringToBytes } from './utils.ts'\nimport { validatePort } from './validation.ts'\nimport type { Registry as RegistryInterface } from './index.ts'\n\nexport const V = -1\n\nexport interface ProtocolCodec {\n /**\n * A numeric code that will be used in the binary representation of the tuple.\n */\n code: number\n\n /**\n * A string name that will be used in the string representation of the addr.\n */\n name: string\n\n /**\n * Size defines the expected length of the address part of the tuple - valid\n * values are `-1` (or the `V` constant) for variable length (this will be\n * varint encoded in the binary representation), `0` for no address part or a\n * number that represents a fixed-length address.\n */\n size?: number\n\n /**\n * If specified this protocol codec will also be used to decode tuples with\n * these names from string multiaddrs.\n */\n aliases?: string[]\n\n /**\n * Where the multiaddr has been encoded as a string, decode the value if\n * necessary, unescaping any escaped values\n */\n stringToValue?(value: string): string\n\n /**\n * To encode the multiaddr as a string, escape any necessary values\n */\n valueToString?(value: string): string\n\n /**\n * To encode the multiaddr as bytes, convert the value to bytes\n */\n valueToBytes?(value: string): Uint8Array\n\n /**\n * To decode bytes to a multiaddr, convert the value bytes to a string\n */\n bytesToValue?(bytes: Uint8Array): string\n\n /**\n * Perform any necessary validation on the string value\n */\n validate?(value: string): void\n}\n\nclass Registry implements RegistryInterface {\n private protocolsByCode = new Map<number, ProtocolCodec>()\n private protocolsByName = new Map<string, ProtocolCodec>()\n\n getProtocol (key: string | number): ProtocolCodec {\n let codec: ProtocolCodec | undefined\n\n if (typeof key === 'string') {\n codec = this.protocolsByName.get(key)\n } else {\n codec = this.protocolsByCode.get(key)\n }\n\n if (codec == null) {\n throw new UnknownProtocolError(`Protocol ${key} was unknown`)\n }\n\n return codec\n }\n\n addProtocol (codec: ProtocolCodec): void {\n this.protocolsByCode.set(codec.code, codec)\n this.protocolsByName.set(codec.name, codec)\n\n codec.aliases?.forEach(alias => {\n this.protocolsByName.set(alias, codec)\n })\n }\n\n removeProtocol (code: number): void {\n const codec = this.protocolsByCode.get(code)\n\n if (codec == null) {\n return\n }\n\n this.protocolsByCode.delete(codec.code)\n this.protocolsByName.delete(codec.name)\n\n codec.aliases?.forEach(alias => {\n this.protocolsByName.delete(alias)\n })\n }\n}\n\nexport const registry = new Registry()\n\nconst codecs: ProtocolCodec[] = [{\n code: CODE_IP4,\n name: 'ip4',\n size: 32,\n valueToBytes: ip4ToBytes,\n bytesToValue: ip4ToString,\n validate: (value) => {\n if (!isIPv4(value)) {\n throw new ValidationError(`Invalid IPv4 address \"${value}\"`)\n }\n }\n}, {\n code: CODE_TCP,\n name: 'tcp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_UDP,\n name: 'udp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_DCCP,\n name: 'dccp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_IP6,\n name: 'ip6',\n size: 128,\n valueToBytes: ip6ToBytes,\n bytesToValue: ip6ToString,\n stringToValue: ip6StringToValue,\n validate: (value) => {\n if (!isIPv6(value)) {\n throw new ValidationError(`Invalid IPv6 address \"${value}\"`)\n }\n }\n}, {\n code: CODE_IP6ZONE,\n name: 'ip6zone',\n size: V\n}, {\n code: CODE_IPCIDR,\n name: 'ipcidr',\n size: 8,\n bytesToValue: bytesToString('base10'),\n valueToBytes: stringToBytes('base10')\n}, {\n code: CODE_DNS,\n name: 'dns',\n size: V\n}, {\n code: CODE_DNS4,\n name: 'dns4',\n size: V\n}, {\n code: CODE_DNS6,\n name: 'dns6',\n size: V\n}, {\n code: CODE_DNSADDR,\n name: 'dnsaddr',\n size: V\n}, {\n code: CODE_SCTP,\n name: 'sctp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_UDT,\n name: 'udt'\n}, {\n code: CODE_UTP,\n name: 'utp'\n}, {\n code: CODE_UNIX,\n name: 'unix',\n size: V,\n stringToValue: (str) => decodeURIComponent(str),\n valueToString: (val) => encodeURIComponent(val)\n}, {\n code: CODE_P2P,\n name: 'p2p',\n aliases: ['ipfs'],\n size: V,\n bytesToValue: bytesToString('base58btc'),\n valueToBytes: (val) => {\n if (val.startsWith('Q') || val.startsWith('1')) {\n return stringToBytes('base58btc')(val)\n }\n\n return CID.parse(val).multihash.bytes\n }\n}, {\n code: CODE_ONION,\n name: 'onion',\n size: 96,\n bytesToValue: bytes2onion,\n valueToBytes: onion2bytes\n}, {\n code: CODE_ONION3,\n name: 'onion3',\n size: 296,\n bytesToValue: bytes2onion,\n valueToBytes: onion32bytes\n}, {\n code: CODE_GARLIC64,\n name: 'garlic64',\n size: V\n}, {\n code: CODE_GARLIC32,\n name: 'garlic32',\n size: V\n}, {\n code: CODE_TLS,\n name: 'tls'\n}, {\n code: CODE_SNI,\n name: 'sni',\n size: V\n}, {\n code: CODE_NOISE,\n name: 'noise'\n}, {\n code: CODE_QUIC,\n name: 'quic'\n}, {\n code: CODE_QUIC_V1,\n name: 'quic-v1'\n}, {\n code: CODE_WEBTRANSPORT,\n name: 'webtransport'\n}, {\n code: CODE_CERTHASH,\n name: 'certhash',\n size: V,\n bytesToValue: bytes2mb(base64url),\n valueToBytes: mb2bytes\n}, {\n code: CODE_HTTP,\n name: 'http'\n}, {\n code: CODE_HTTP_PATH,\n name: 'http-path',\n size: V,\n stringToValue: (str) => `/${decodeURIComponent(str)}`,\n valueToString: (val) => encodeURIComponent(val.substring(1))\n}, {\n code: CODE_HTTPS,\n name: 'https'\n}, {\n code: CODE_WS,\n name: 'ws'\n}, {\n code: CODE_WSS,\n name: 'wss'\n}, {\n code: CODE_P2P_WEBSOCKET_STAR,\n name: 'p2p-websocket-star'\n}, {\n code: CODE_P2P_STARDUST,\n name: 'p2p-stardust'\n}, {\n code: CODE_P2P_WEBRTC_STAR,\n name: 'p2p-webrtc-star'\n}, {\n code: CODE_P2P_WEBRTC_DIRECT,\n name: 'p2p-webrtc-direct'\n}, {\n code: CODE_WEBRTC_DIRECT,\n name: 'webrtc-direct'\n}, {\n code: CODE_WEBRTC,\n name: 'webrtc'\n}, {\n code: CODE_P2P_CIRCUIT,\n name: 'p2p-circuit'\n}, {\n code: CODE_MEMORY,\n name: 'memory',\n size: V\n}]\n\ncodecs.forEach(codec => {\n registry.addProtocol(codec)\n})\n", "import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidMultiaddrError } from './errors.ts'\nimport { registry, V } from './registry.ts'\nimport type { Component } from './index.js'\nimport type { ProtocolCodec } from './registry.ts'\n\nexport function bytesToComponents (bytes: Uint8Array): Component[] {\n const components: Component[] = []\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const codec = registry.getProtocol(code)\n const codeLength = varint.encodingLength(code)\n const size = sizeForAddr(codec, bytes, i + codeLength)\n let sizeLength = 0\n\n if (size > 0 && codec.size === V) {\n sizeLength = varint.encodingLength(size)\n }\n\n const componentLength = codeLength + sizeLength + size\n\n const component: Component = {\n code,\n name: codec.name,\n bytes: bytes.subarray(i, i + componentLength)\n }\n\n if (size > 0) {\n const valueOffset = i + codeLength + sizeLength\n const valueBytes = bytes.subarray(valueOffset, valueOffset + size)\n\n component.value = codec.bytesToValue?.(valueBytes) ?? uint8ArrayToString(valueBytes)\n }\n\n components.push(component)\n\n i += componentLength\n }\n\n return components\n}\n\nexport function componentsToBytes (components: Component[]): Uint8Array {\n let length = 0\n const bytes: Uint8Array[] = []\n\n for (const component of components) {\n if (component.bytes == null) {\n const codec = registry.getProtocol(component.code)\n const codecLength = varint.encodingLength(component.code)\n let valueBytes: Uint8Array | undefined\n let valueLength = 0\n let valueLengthLength = 0\n\n if (component.value != null) {\n valueBytes = codec.valueToBytes?.(component.value) ?? uint8ArrayFromString(component.value)\n valueLength = valueBytes.byteLength\n\n if (codec.size === V) {\n valueLengthLength = varint.encodingLength(valueLength)\n }\n }\n\n const bytes = new Uint8Array(codecLength + valueLengthLength + valueLength)\n\n // encode the protocol code\n let offset = 0\n varint.encodeUint8Array(component.code, bytes, offset)\n offset += codecLength\n\n // if there is a value\n if (valueBytes != null) {\n // if the value has variable length, encode the length\n if (codec.size === V) {\n varint.encodeUint8Array(valueLength, bytes, offset)\n offset += valueLengthLength\n }\n\n // finally encode the value\n bytes.set(valueBytes, offset)\n }\n\n component.bytes = bytes\n }\n\n bytes.push(component.bytes)\n length += component.bytes.byteLength\n }\n\n return uint8ArrayConcat(bytes, length)\n}\n\nexport function stringToComponents (string: string): Component[] {\n if (string.charAt(0) !== '/') {\n throw new InvalidMultiaddrError('String multiaddr must start with \"/\"')\n }\n\n const components: Component[] = []\n let collecting: 'protocol' | 'value' = 'protocol'\n let value = ''\n let protocol = ''\n\n for (let i = 1; i < string.length; i++) {\n const char = string.charAt(i)\n\n if (char !== '/') {\n if (collecting === 'protocol') {\n protocol += string.charAt(i)\n } else {\n value += string.charAt(i)\n }\n }\n\n const ended = i === string.length - 1\n\n if (char === '/' || ended) {\n const codec = registry.getProtocol(protocol)\n\n if (collecting === 'protocol') {\n if (codec.size == null || codec.size === 0) {\n // a protocol without an address, eg. `/tls`\n components.push({\n code: codec.code,\n name: codec.name\n })\n\n value = ''\n protocol = ''\n collecting = 'protocol'\n\n continue\n } else if (ended) {\n throw new InvalidMultiaddrError(`Component ${protocol} was missing value`)\n }\n\n // continue collecting value\n collecting = 'value'\n } else if (collecting === 'value') {\n const component: Component = {\n code: codec.code,\n name: codec.name\n }\n\n if (codec.size != null && codec.size !== 0) {\n if (value === '') {\n throw new InvalidMultiaddrError(`Component ${protocol} was missing value`)\n }\n\n component.value = codec.stringToValue?.(value) ?? value\n }\n\n components.push(component)\n\n value = ''\n protocol = ''\n collecting = 'protocol'\n }\n }\n }\n\n if (protocol !== '' && value !== '') {\n throw new InvalidMultiaddrError('Incomplete multiaddr')\n }\n\n return components\n}\n\nexport function componentsToString (components: Component[]): string {\n return `/${components.flatMap(component => {\n if (component.value == null) {\n return component.name\n }\n\n const codec = registry.getProtocol(component.code)\n\n if (codec == null) {\n throw new InvalidMultiaddrError(`Unknown protocol code ${component.code}`)\n }\n\n return [\n component.name,\n codec.valueToString?.(component.value) ?? component.value\n ]\n }).join('/')}`\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (codec: ProtocolCodec, bytes: Uint8Array, offset: number): number {\n if (codec.size == null || codec.size === 0) {\n return 0\n }\n\n if (codec.size > 0) {\n return codec.size / 8\n }\n\n return varint.decode(bytes, offset)\n}\n", "import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { bytesToComponents, componentsToBytes, componentsToString, stringToComponents } from './components.js'\nimport { InvalidMultiaddrError, InvalidParametersError } from './errors.ts'\nimport { registry } from './registry.ts'\nimport { isMultiaddr } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, Component } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/multiaddr')\n\nfunction toComponents (addr: MultiaddrInput): Component[] {\n if (addr == null) {\n addr = '/'\n }\n\n if (isMultiaddr(addr)) {\n return addr.getComponents()\n }\n\n if (addr instanceof Uint8Array) {\n return bytesToComponents(addr)\n }\n\n if (typeof addr === 'string') {\n addr = addr\n .replace(/\\/(\\/)+/, '/')\n .replace(/(\\/)+$/, '')\n\n if (addr === '') {\n addr = '/'\n }\n\n return stringToComponents(addr)\n }\n\n if (Array.isArray(addr)) {\n return addr\n }\n\n throw new InvalidMultiaddrError('Must be a string, Uint8Array, Component[], or another Multiaddr')\n}\n\ninterface MultiaddrOptions {\n validate?: boolean\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n [symbol]: boolean = true\n readonly #components: Component[]\n\n // cache string representation\n #string: string | undefined\n // cache byte representation\n #bytes: Uint8Array | undefined\n\n constructor (addr: MultiaddrInput | Component[] = '/', options: MultiaddrOptions = {}) {\n this.#components = toComponents(addr)\n\n if (options.validate !== false) {\n validate(this)\n }\n }\n\n get bytes (): Uint8Array {\n if (this.#bytes == null) {\n this.#bytes = componentsToBytes(this.#components)\n }\n\n return this.#bytes\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = componentsToString(this.#components)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n getComponents (): Component[] {\n return [\n ...this.#components.map(c => ({ ...c }))\n ]\n }\n\n encapsulate (addr: MultiaddrInput): MultiaddrInterface {\n const ma = new Multiaddr(addr)\n\n return new Multiaddr([\n ...this.#components,\n ...ma.getComponents()\n ], {\n validate: false\n })\n }\n\n decapsulate (addr: Multiaddr | string): MultiaddrInterface {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n\n if (i < 0) {\n throw new InvalidParametersError(`Address ${this.toString()} does not contain subaddress: ${addrString}`)\n }\n\n return new Multiaddr(s.slice(0, i), {\n validate: false\n })\n }\n\n decapsulateCode (code: number): Multiaddr {\n let index\n\n for (let i = this.#components.length - 1; i > -1; i--) {\n if (this.#components[i].code === code) {\n index = i\n break\n }\n }\n\n return new Multiaddr(this.#components.slice(0, index), {\n validate: false\n })\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.toString()})`\n }\n}\n\n/**\n * Ensures all multiaddr tuples are correct. Throws if any invalid protocols or\n * values are encountered.\n */\nexport function validate (addr: Multiaddr): void {\n addr.getComponents()\n .forEach(component => {\n const codec = registry.getProtocol(component.code)\n\n if (component.value == null) {\n return\n }\n\n codec.validate?.(component.value)\n })\n}\n", "/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // <Uint8Array 04 7f 00 00 01 11 04 d2>\n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.getComponents()\n * // [\n * // { code: 4, name: 'ip4', value: '127.0.0.1' },\n * // { code: 273, name: 'udp', value: '1234' }\n * // ]\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * @example Adding custom protocols\n *\n * To add application-specific or experimental protocols, add a protocol codec\n * to the protocol registry:\n *\n * ```ts\n * import { registry, V, multiaddr } from '@multiformats/multiaddr'\n * import type { ProtocolCodec } from '@multiformats/multiaddr'\n *\n * const maWithCustomTuple = '/custom-protocol/hello'\n *\n * // throws UnknownProtocolError\n * multiaddr(maWithCustomTuple)\n *\n * const protocol: ProtocolCodec = {\n * code: 2059,\n * name: 'custom-protocol',\n * size: V\n * // V means variable length, can also be 0, a positive integer (e.g. a fixed\n * // length or omitted\n * }\n *\n * registry.addProtocol(protocol)\n *\n * // does not throw UnknownProtocolError\n * multiaddr(maWithCustomTuple)\n *\n * // protocols can also be removed\n * registry.removeProtocol(protocol.code)\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { registry, V } from './registry.ts'\nimport type { ProtocolCodec } from './registry.ts'\n\n/**\n * The protocol registry stores protocol codecs that allow transformation of\n * multiaddr tuples from bytes to string and back again, and also validation of\n * the address values.\n */\nexport interface Registry {\n /**\n * Retrieve a protocol definition by it's code or name\n */\n getProtocol (key: string | number): ProtocolCodec\n\n /**\n * Add a new protocol definition\n */\n addProtocol (codec: ProtocolCodec): void\n\n /**\n * Remove a protocol definition by it's code\n */\n removeProtocol (code: number): void\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null | Component[]\n\n/**\n * A Component is a section of a multiaddr with a name/code, possibly with a\n * value.\n *\n * Component names/codes are defined in the protocol table.\n *\n * @see https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n */\nexport interface Component {\n /**\n * The code of the component as defined in the protocol table\n */\n code: number\n\n /**\n * The name of the component as defined in the protocol table\n */\n name: string\n\n /**\n * The component value, if one is present\n */\n value?: string\n\n /**\n * The bytes that make up the component. This will be set if the multiaddr\n * was parsed from a `Uint8Array`, or if `.bytes` has been accessed on it.\n */\n bytes?: Uint8Array\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns the components that make up this Multiaddr\n *\n * @example\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').getComponents()\n * // [{ name: 'ip4', code: 4, value: '127.0.0.1' }, { name: 'tcp', code: 6, value: '4001' }]\n * ```\n */\n getComponents(): Component[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a specific\n * code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\n/**\n * Export all table.csv codes. These are all named exports so can be tree-shaken\n * out by bundlers.\n */\nexport * from './constants.ts'\nexport { registry, V }\nexport type { ProtocolCodec }\n", "// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n", "import fnv1aHash from '@sindresorhus/fnv1a'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport interface Hash {\n hash(input: Uint8Array, seed: number): number\n hashV(input: Uint8Array, seed: number): Uint8Array\n}\n\nexport const fnv1a: Hash = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }))\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed))\n }\n}\n\nexport function numberToBuffer (num: bigint | number): Uint8Array {\n let hex = num.toString(16)\n\n if (hex.length % 2 === 1) {\n hex = `0${hex}`\n }\n\n return uint8ArrayFromString(hex, 'base16')\n}\n", "import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { Hash } from './hashes.js'\n\nexport const MAX_FINGERPRINT_SIZE = 64\n\nexport class Fingerprint {\n private readonly fp: Uint8Array\n private readonly h: Hash\n private readonly seed: number\n\n constructor (buf: Uint8Array, hash: Hash, seed: number, fingerprintSize: number = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size')\n }\n\n const fnv = hash.hashV(buf, seed)\n const fp = uint8ArrayAlloc(fingerprintSize)\n\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i]\n }\n\n if (fp.length === 0) {\n fp[0] = 7\n }\n\n this.fp = fp\n this.h = hash\n this.seed = seed\n }\n\n hash (): number {\n return this.h.hash(this.fp, this.seed)\n }\n\n equals (other?: any): boolean {\n if (!(other?.fp instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.fp, other.fp)\n }\n}\n", "export function getRandomInt (min: number, max: number): number {\n return Math.floor(Math.random() * (max - min)) + min\n}\n", "import { Fingerprint } from './fingerprint.js'\nimport { getRandomInt } from './utils.js'\n\nexport class Bucket {\n private readonly contents: Array<Fingerprint | null>\n\n constructor (size: number) {\n this.contents = new Array(size).fill(null)\n }\n\n has (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n return this.contents.some((fp) => {\n return fingerprint.equals(fp)\n })\n }\n\n add (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint\n return true\n }\n }\n\n return true\n }\n\n swap (fingerprint: Fingerprint): Fingerprint | null {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const i = getRandomInt(0, this.contents.length - 1)\n const current = this.contents[i]\n this.contents[i] = fingerprint\n\n return current\n }\n\n remove (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp)\n })\n\n if (found > -1) {\n this.contents[found] = null\n return true\n } else {\n return false\n }\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Bucket } from './bucket.js'\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.js'\nimport { fnv1a } from './hashes.js'\nimport { getRandomInt } from './utils.js'\nimport type { Hash } from './hashes.js'\nimport type { Filter } from './index.js'\n\nconst maxCuckooCount = 500\n\nexport interface CuckooFilterInit {\n /**\n * How many items the filter is expected to contain\n */\n filterSize: number\n\n /**\n * How many items to put in each bucket\n */\n bucketSize?: number\n\n /**\n * How many bytes the fingerprint is expected to be\n */\n fingerprintSize?: number\n\n /**\n * A non-cryptographic hash implementation\n */\n hash?: Hash\n\n /**\n * A number used to seed the hash\n */\n seed?: number\n}\n\nexport class CuckooFilter implements Filter {\n private readonly bucketSize: number\n private readonly filterSize: number\n private readonly fingerprintSize: number\n private readonly buckets: Bucket[]\n public count: number\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: CuckooFilterInit) {\n this.filterSize = init.filterSize\n this.bucketSize = init.bucketSize ?? 4\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.count = 0\n this.buckets = []\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++\n return true\n }\n\n const rand = [j, k]\n let i = rand[getRandomInt(0, rand.length - 1)]\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint)\n\n if (swapped == null) {\n continue\n }\n\n i = (i ^ swapped.hash()) % this.filterSize\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[i].add(swapped)) {\n this.count++\n\n return true\n } else {\n continue\n }\n }\n\n return false\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.has(fingerprint) ?? false\n\n if (inJ) {\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n return this.buckets[k]?.has(fingerprint) ?? false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false\n\n if (inJ) {\n this.count--\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n const inK = this.buckets[k]?.remove(fingerprint) ?? false\n\n if (inK) {\n this.count--\n }\n\n return inK\n }\n\n get reliable (): boolean {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90\n }\n}\n\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n}\n\nfunction calculateBucketSize (errorRate: number = 0.001): 2 | 4 | 8 {\n if (errorRate > 0.002) {\n return 2\n }\n\n if (errorRate > 0.00001) {\n return 4\n }\n\n return 8\n}\n\nexport function optimize (maxItems: number, errorRate: number = 0.001): CuckooFilterInit {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate)\n const load = MAX_LOAD[bucketSize]\n\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load)\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), MAX_FINGERPRINT_SIZE)\n\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n }\n}\n\nexport function createCuckooFilter (maxItems: number, errorRate: number = 0.005): Filter {\n const opts = optimize(maxItems, errorRate)\n return new CuckooFilter(opts)\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { CuckooFilter, optimize } from './cuckoo-filter.js'\nimport { fnv1a } from './hashes.js'\nimport { getRandomInt } from './utils.js'\nimport type { CuckooFilterInit } from './cuckoo-filter.js'\nimport type { Hash } from './hashes.js'\nimport type { Filter } from './index.js'\n\nexport interface ScalableCuckooFilterInit extends CuckooFilterInit {\n /**\n * A number to multiply maxItems by when adding new sub-filters\n */\n scale?: number\n}\n\nexport class ScalableCuckooFilter implements Filter {\n private readonly filterSize: number\n private readonly bucketSize: number\n private readonly fingerprintSize: number\n private readonly scale: number\n private readonly filterSeries: CuckooFilter[]\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: ScalableCuckooFilterInit) {\n this.bucketSize = init.bucketSize ?? 4\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.scale = init.scale ?? 2\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ]\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n if (this.has(item)) {\n return true\n }\n\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable\n })\n\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length)\n\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n\n this.filterSeries.push(current)\n }\n\n return current.add(item)\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true\n }\n }\n\n return false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true\n }\n }\n\n return false\n }\n\n get count (): number {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count\n }, 0)\n }\n}\n\nexport function createScalableCuckooFilter (maxItems: number, errorRate: number = 0.001, options?: Pick<ScalableCuckooFilterInit, 'hash' | 'seed' | 'scale'>): Filter {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n })\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next<T> {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO<T> {\n public buffer: Array<Next<T> | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO<T> | null\n\n constructor (hwm: number) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two')\n }\n\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n push (data: Next<T>): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next<T> | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO<T> {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO<T>\n private tail: FixedFIFO<T>\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO<T>(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next<T>): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\n\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift (): Next<T> | undefined {\n let val = this.tail.shift()\n\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n val = this.tail.shift()\n }\n\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { FIFO, type Next } from './fifo.js'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable<T> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise<void>\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable<T, R = void, N = unknown> extends AsyncGenerator<T, R, N>, BasePushable<T> {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV<T, R = void, N = unknown> extends AsyncGenerator<T[], R, N>, BasePushable<T> {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult<T> { done: false, value: T }\nexport type NextResult<T> = ValueResult<T> | DoneResult\n\ninterface getNext<T, V = T> { (buffer: FIFO<T>): NextResult<V> }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): Pushable<T>\nexport function pushable<T> (options: ObjectPushableOptions): Pushable<T>\nexport function pushable<T> (options: Options = {}): Pushable<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T> => {\n const next: Next<T> | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n }\n }\n\n return _pushable<T, T, Pushable<T>>(getNext, options)\n}\n\nexport function pushableV<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): PushableV<T>\nexport function pushableV<T> (options: ObjectPushableOptions): PushableV<T>\nexport function pushableV<T> (options: Options = {}): PushableV<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T[]> => {\n let next: Next<T> | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable<T, T[], PushableV<T>>(getNext, options)\n}\n\nfunction _pushable<PushType, ValueType, ReturnType> (getNext: getNext<PushType, ValueType>, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO<PushType>()\n let pushable: any\n let onNext: ((next: Next<PushType>) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise<NextResult<ValueType>> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise<NextResult<ValueType>>((resolve, reject) => {\n onNext = (next: Next<PushType>) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n } finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve()\n drain = deferred()\n })\n }\n }\n }\n\n const bufferNext = (next: Next<PushType>): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\n\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value')\n }\n\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise<void> | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n", "import pTimeout from 'p-timeout';\n\nconst normalizeEmitter = emitter => {\n\tconst addListener = emitter.addEventListener || emitter.on || emitter.addListener;\n\tconst removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;\n\n\tif (!addListener || !removeListener) {\n\t\tthrow new TypeError('Emitter is not compatible');\n\t}\n\n\treturn {\n\t\taddListener: addListener.bind(emitter),\n\t\tremoveListener: removeListener.bind(emitter),\n\t};\n};\n\nexport function pEventMultiple(emitter, event, options) {\n\tlet cancel;\n\tconst returnValue = new Promise((resolve, reject) => {\n\t\toptions = {\n\t\t\trejectionEvents: ['error'],\n\t\t\tmultiArgs: false,\n\t\t\trejectionMultiArgs: false,\n\t\t\tresolveImmediately: false,\n\t\t\t...options,\n\t\t};\n\n\t\tif (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {\n\t\t\tthrow new TypeError('The `count` option should be at least 0 or more');\n\t\t}\n\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Allow multiple events\n\t\tconst events = [event].flat();\n\n\t\tconst items = [];\n\t\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\t\tconst onItem = async (...arguments_) => {\n\t\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\t\tif (options.filter) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\titems.push(value);\n\n\t\t\tif (options.count === items.length) {\n\t\t\t\tcancel();\n\t\t\t\tresolve(items);\n\t\t\t}\n\t\t};\n\n\t\tconst rejectHandler = (...arguments_) => {\n\t\t\tcancel();\n\t\t\treject(options.rejectionMultiArgs ? arguments_ : arguments_[0]);\n\t\t};\n\n\t\tcancel = () => {\n\t\t\tfor (const event of events) {\n\t\t\t\tremoveListener(event, onItem);\n\t\t\t}\n\n\t\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t\t// Only remove rejection handler if we actually registered it\n\t\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const event of events) {\n\t\t\taddListener(event, onItem);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\t// Skip registering rejection handler if we're already listening to this event\n\t\t\t// as the main event takes priority (as documented)\n\t\t\tif (!events.includes(rejectionEvent)) {\n\t\t\t\taddListener(rejectionEvent, rejectHandler);\n\t\t\t}\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener('abort', () => {\n\t\t\t\trejectHandler(options.signal.reason);\n\t\t\t}, {once: true});\n\t\t}\n\n\t\tif (options.resolveImmediately) {\n\t\t\tresolve(items);\n\t\t}\n\t});\n\n\treturnValue.cancel = cancel;\n\n\tif (typeof options.timeout === 'number') {\n\t\tconst timeout = pTimeout(returnValue, {milliseconds: options.timeout});\n\t\t// When cancelling, also clear the timeout timer\n\t\ttimeout.cancel = () => {\n\t\t\tcancel();\n\t\t\ttimeout.clear();\n\t\t};\n\n\t\treturn timeout;\n\t}\n\n\treturn returnValue;\n}\n\nexport function pEvent(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\toptions = {\n\t\t...options,\n\t\tcount: 1,\n\t\tresolveImmediately: false,\n\t};\n\n\tconst arrayPromise = pEventMultiple(emitter, event, options);\n\tconst promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then\n\tpromise.cancel = arrayPromise.cancel;\n\n\treturn promise;\n}\n\nexport function pEventIterator(emitter, event, options) {\n\tif (typeof options === 'function') {\n\t\toptions = {filter: options};\n\t}\n\n\t// Allow multiple events\n\tconst events = [event].flat();\n\n\toptions = {\n\t\trejectionEvents: ['error'],\n\t\tresolutionEvents: [],\n\t\tlimit: Number.POSITIVE_INFINITY,\n\t\tmultiArgs: false,\n\t\trejectionMultiArgs: false,\n\t\t...options,\n\t};\n\n\tconst {limit} = options;\n\tconst isValidLimit = limit >= 0 && (limit === Number.POSITIVE_INFINITY || Number.isInteger(limit));\n\tif (!isValidLimit) {\n\t\tthrow new TypeError('The `limit` option should be a non-negative integer or Infinity');\n\t}\n\n\toptions.signal?.throwIfAborted();\n\n\tif (limit === 0) {\n\t\t// Return an empty async iterator to avoid any further cost\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tasync next() {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tconst {addListener, removeListener} = normalizeEmitter(emitter);\n\n\tlet isDone = false;\n\tlet error;\n\tlet hasPendingError = false;\n\tconst nextQueue = [];\n\tconst valueQueue = [];\n\tlet eventCount = 0;\n\tlet isLimitReached = false;\n\n\tconst valueHandler = (...arguments_) => {\n\t\teventCount++;\n\t\tisLimitReached = eventCount === limit;\n\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\n\t\t\tresolve({done: false, value});\n\n\t\t\tif (isLimitReached) {\n\t\t\t\tcancel();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalueQueue.push(value);\n\n\t\tif (isLimitReached) {\n\t\t\tcancel();\n\t\t}\n\t};\n\n\tconst cancel = () => {\n\t\tisDone = true;\n\n\t\tfor (const event of events) {\n\t\t\tremoveListener(event, valueHandler);\n\t\t}\n\n\t\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\t\tremoveListener(rejectionEvent, rejectHandler);\n\t\t}\n\n\t\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\t\tremoveListener(resolutionEvent, resolveHandler);\n\t\t}\n\n\t\twhile (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value: undefined});\n\t\t}\n\t};\n\n\tconst rejectHandler = (...arguments_) => {\n\t\terror = options.rejectionMultiArgs ? arguments_ : arguments_[0];\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {reject} = nextQueue.shift();\n\t\t\treject(error);\n\t\t} else {\n\t\t\thasPendingError = true;\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tconst resolveHandler = async (...arguments_) => {\n\t\tconst value = options.multiArgs ? arguments_ : arguments_[0];\n\n\t\tif (options.filter) {\n\t\t\ttry {\n\t\t\t\tif (!(await options.filter(value))) {\n\t\t\t\t\tcancel();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (filterError) {\n\t\t\t\tcancel();\n\t\t\t\tif (nextQueue.length > 0) {\n\t\t\t\t\tconst {reject} = nextQueue.shift();\n\t\t\t\t\treject(filterError);\n\t\t\t\t} else {\n\t\t\t\t\t// Store error for next iterator call\n\t\t\t\t\thasPendingError = true;\n\t\t\t\t\terror = filterError;\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (nextQueue.length > 0) {\n\t\t\tconst {resolve} = nextQueue.shift();\n\t\t\tresolve({done: true, value});\n\t\t} else {\n\t\t\tvalueQueue.push(value);\n\t\t}\n\n\t\tcancel();\n\t};\n\n\tfor (const event of events) {\n\t\taddListener(event, valueHandler);\n\t}\n\n\tfor (const rejectionEvent of options.rejectionEvents) {\n\t\taddListener(rejectionEvent, rejectHandler);\n\t}\n\n\tfor (const resolutionEvent of options.resolutionEvents) {\n\t\taddListener(resolutionEvent, resolveHandler);\n\t}\n\n\tif (options.signal) {\n\t\toptions.signal.addEventListener('abort', () => {\n\t\t\trejectHandler(options.signal.reason);\n\t\t}, {once: true});\n\t}\n\n\treturn {\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t\tasync next() {\n\t\t\tif (valueQueue.length > 0) {\n\t\t\t\tconst value = valueQueue.shift();\n\t\t\t\treturn {\n\t\t\t\t\tdone: isDone && valueQueue.length === 0 && !isLimitReached,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (hasPendingError) {\n\t\t\t\thasPendingError = false;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (isDone) {\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tnextQueue.push({resolve, reject});\n\t\t\t});\n\t\t},\n\t\tasync return(value) {\n\t\t\tcancel();\n\t\t\treturn {\n\t\t\t\tdone: isDone,\n\t\t\t\tvalue,\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport {TimeoutError} from 'p-timeout';\n", "import type { Startable } from '@libp2p/interface'\n\nexport interface DebouncedFunction extends Startable {\n (): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = (): void => {}\n output.stop = (): void => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "import type { RateLimiterResult } from './rate-limiter.js'\n\n/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n\n constructor (message = 'Rate limit exceeded', props: RateLimiterResult) {\n super(message)\n this.name = 'RateLimitError'\n this.remainingPoints = props.remainingPoints\n this.msBeforeNext = props.msBeforeNext\n this.consumedPoints = props.consumedPoints\n this.isFirstInDuration = props.isFirstInDuration\n }\n}\n\nexport class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n\nexport class UnexpectedEOFError extends Error {\n static name = 'UnexpectedEOFError'\n name = 'UnexpectedEOFError'\n}\n\nexport class MaxEarlyStreamsError extends Error {\n static name = 'MaxEarlyStreamsError'\n name = 'MaxEarlyStreamsError'\n}\n\nexport class StreamClosedError extends Error {\n static name = 'StreamClosedError'\n name = 'StreamClosedError'\n}\n", "/**\n * @packageDocumentation\n *\n * Pass a promise and an abort signal and await the result.\n *\n * @example Basic usage\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws an AbortError\n * const resolve = await raceSignal(promise, controller.signal)\n * ```\n *\n * @example Overriding errors\n *\n * By default the thrown error is the `.reason` property of the signal but it's\n * possible to override this behaviour with the `translateError` option:\n *\n * ```ts\n * import { raceSignal } from 'race-signal'\n *\n * const controller = new AbortController()\n *\n * const promise = new Promise((resolve, reject) => {\n * setTimeout(() => {\n * resolve('a value')\n * }, 1000)\n * })\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws `Error('Oh no!')`\n * const resolve = await raceSignal(promise, controller.signal, {\n * translateError: (signal) => {\n * // use `signal`, or don't\n * return new Error('Oh no!')\n * }\n * })\n * ```\n */\n\nexport interface RaceSignalOptions {\n /**\n * By default the rejection reason will be taken from the `.reason` field of\n * the aborted signal.\n *\n * Passing a function here allows overriding the default error.\n */\n translateError?(signal: AbortSignal): Error\n}\n\nfunction defaultTranslate (signal: AbortSignal): Error {\n return signal.reason\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n const translateError = opts?.translateError ?? defaultTranslate\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(translateError(signal))\n }\n\n let listener\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(translateError(signal))\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport pDefer from 'p-defer'\nimport type { DeferredPromise } from 'p-defer'\n\nexport class JobRecipient<JobReturnType> {\n public deferred: DeferredPromise<JobReturnType>\n public signal?: AbortSignal\n\n constructor (signal?: AbortSignal) {\n this.signal = signal\n this.deferred = pDefer()\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(this.signal?.reason ?? new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport { setMaxListeners } from 'main-event'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.js'\nimport type { JobStatus } from './index.js'\nimport type { AbortOptions } from '@libp2p/interface'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job <JobOptions extends AbortOptions = AbortOptions, JobReturnType = unknown> {\n public id: string\n public fn: (options: JobOptions) => Promise<JobReturnType>\n public options: JobOptions\n public recipients: Array<JobRecipient<JobReturnType>>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n\n constructor (fn: (options: JobOptions) => Promise<JobReturnType>, options: any) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n this.cleanup()\n }\n }\n\n async join (options: AbortOptions = {}): Promise<JobReturnType> {\n const recipient = new JobRecipient<JobReturnType>(options.signal)\n this.recipients.push(recipient)\n\n options.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise<void> {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.cleanup()\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n", "import { AbortError } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { TypedEventEmitter } from 'main-event'\nimport { pEvent } from 'p-event'\nimport { debounce } from '../debounce.js'\nimport { QueueFullError } from '../errors.js'\nimport { Job } from './job.js'\nimport type { AbortOptions, Metrics } from '@libp2p/interface'\n\nexport type { Job, JobTimeline } from './job.js'\nexport type { JobRecipient } from './recipient.js'\n\nexport interface Comparator<T> {\n (a: T, b: T): -1 | 0 | 1\n}\n\nexport interface QueueInit<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * If the queue size grows to larger than this number the promise returned\n * from the add function will reject\n *\n * @default Infinity\n */\n maxSize?: number\n\n /**\n * The name of the metric for the queue length\n */\n metricName?: string\n\n /**\n * An implementation of the libp2p Metrics interface\n */\n metrics?: Metrics\n\n /**\n * An optional function that will sort the queue after a job has been added\n */\n sort?: Comparator<Job<JobOptions, JobReturnType>>\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction<Options extends AbortOptions = AbortOptions, ReturnType = void> {\n (options: Options): Promise<ReturnType>\n}\n\nexport interface JobMatcher<JobOptions extends AbortOptions = AbortOptions> {\n (options?: Partial<JobOptions>): boolean\n}\n\nexport interface QueueJobSuccess<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n result: JobReturnType\n}\n\nexport interface QueueJobFailure<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n error: Error\n}\n\nexport interface QueueEvents<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * A job is about to start running\n */\n active: CustomEvent\n\n /**\n * All jobs have finished and the queue is empty\n */\n idle: CustomEvent\n\n /**\n * The queue is empty, jobs may be running\n */\n empty: CustomEvent\n\n /**\n * A job was added to the queue\n */\n add: CustomEvent\n\n /**\n * A job has finished or failed\n */\n next: CustomEvent\n\n /**\n * A job has finished successfully\n */\n completed: CustomEvent<JobReturnType>\n\n /**\n * Emitted just after `\"completed\", a job has finished successfully - this\n * event gives access to the job and it's result\n */\n success: CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>\n\n /**\n * Emitted just after `\"error\", a job has failed - this event gives access to\n * the job and the thrown error\n */\n failure: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue<JobReturnType = unknown, JobOptions extends AbortOptions = AbortOptions> extends TypedEventEmitter<QueueEvents<JobReturnType, JobOptions>> {\n public concurrency: number\n public maxSize: number\n public queue: Array<Job<JobOptions, JobReturnType>>\n private pending: number\n private readonly sort?: Comparator<Job<JobOptions, JobReturnType>>\n private paused: boolean\n\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY\n this.pending = 0\n this.paused = false\n\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n }\n }\n })\n }\n\n this.sort = init.sort\n this.queue = []\n\n this.emitEmpty = debounce(this.emitEmpty.bind(this), 1)\n this.emitIdle = debounce(this.emitIdle.bind(this), 1)\n }\n\n emitEmpty (): void {\n if (this.size !== 0) {\n return\n }\n\n this.safeDispatchEvent('empty')\n }\n\n emitIdle (): void {\n if (this.running !== 0) {\n return\n }\n\n this.safeDispatchEvent('idle')\n }\n\n pause (): void {\n this.paused = true\n }\n\n resume (): void {\n if (!this.paused) {\n return\n }\n\n this.paused = false\n this.tryToStartAnother()\n }\n\n private tryToStartAnother (): boolean {\n if (this.paused) {\n return false\n }\n\n if (this.size === 0) {\n this.emitEmpty()\n\n if (this.running === 0) {\n this.emitIdle()\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job<JobOptions, JobReturnType> | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.tryToStartAnother()\n this.safeDispatchEvent('next')\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job<JobOptions, JobReturnType>): void {\n this.queue.push(job)\n\n if (this.sort != null) {\n this.queue.sort(this.sort)\n }\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction<JobOptions, JobReturnType>, options?: JobOptions): Promise<JobReturnType> {\n options?.signal?.throwIfAborted()\n\n if (this.size === this.maxSize) {\n throw new QueueFullError()\n }\n\n const job = new Job<JobOptions, JobReturnType>(fn, options)\n this.enqueue(job)\n this.safeDispatchEvent('add')\n this.tryToStartAnother()\n\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result })\n this.safeDispatchEvent('success', { detail: { job, result } })\n\n return result\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n }\n\n this.safeDispatchEvent('failure', { detail: { job, error: err } })\n\n throw err\n })\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\n\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty (options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await pEvent(this, 'empty', options)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await pEvent(this, 'next', {\n ...options,\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise<void> {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await pEvent(this, 'idle', options)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator<JobReturnType, void, unknown> {\n options?.signal?.throwIfAborted()\n\n const stream = pushable<JobReturnType>({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent<JobReturnType>): void => {\n if (evt.detail != null) {\n stream.push(evt.detail)\n }\n }\n\n const onQueueFailure = (evt: CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>): void => {\n cleanup(evt.detail.error)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new AbortError('Queue aborted'))\n }\n\n // add listeners\n this.addEventListener('completed', onQueueJobComplete)\n this.addEventListener('failure', onQueueFailure)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete)\n this.removeEventListener('failure', onQueueFailure)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n", "import { StreamResetError, TypedEventEmitter, StreamMessageEvent, StreamBufferError, StreamResetEvent, StreamAbortEvent, StreamCloseEvent, StreamStateError } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { StreamClosedError } from './errors.ts'\nimport type { MessageStreamEvents, MessageStreamStatus, MessageStream, AbortOptions, MessageStreamTimeline, MessageStreamDirection, EventHandler, StreamOptions, MessageStreamReadStatus, MessageStreamWriteStatus } from '@libp2p/interface'\nimport type { Logger } from '@libp2p/logger'\n\nconst DEFAULT_MAX_READ_BUFFER_LENGTH = Math.pow(2, 20) * 4 // 4MB\n\nexport interface MessageStreamInit extends StreamOptions {\n /**\n * A Logger implementation used to log stream-specific information\n */\n log: Logger\n\n /**\n * The stream direction\n */\n direction?: MessageStreamDirection\n\n /**\n * By default all available bytes are passed to the `sendData` method of\n * extending classes, if smaller chunks are required, pass a value here.\n */\n maxMessageSize?: number\n}\n\nexport interface SendResult {\n /**\n * The number of bytes from the passed buffer that were sent\n */\n sentBytes: number\n\n /**\n * If the underlying resource can accept more data immediately. If `true`,\n * `sent` must equal the `.byteLength` of the buffer passed to `sendData`.\n */\n canSendMore: boolean\n}\n\nexport abstract class AbstractMessageStream<Timeline extends MessageStreamTimeline = MessageStreamTimeline> extends TypedEventEmitter<MessageStreamEvents> implements MessageStream {\n public status: MessageStreamStatus\n public readonly timeline: Timeline\n public inactivityTimeout: number\n public maxReadBufferLength: number\n public maxWriteBufferLength?: number\n public readonly log: Logger\n public direction: MessageStreamDirection\n public maxMessageSize?: number\n\n public readStatus: MessageStreamReadStatus\n public writeStatus: MessageStreamWriteStatus\n public remoteReadStatus: MessageStreamReadStatus\n public remoteWriteStatus: MessageStreamWriteStatus\n\n public writableNeedsDrain: boolean\n\n /**\n * Any data stored here is emitted before any new incoming data.\n *\n * This is used when the stream is paused or if data is pushed onto the stream\n */\n protected readonly readBuffer: Uint8ArrayList\n protected readonly writeBuffer: Uint8ArrayList\n protected sendingData: boolean\n\n private onDrainPromise?: PromiseWithResolvers<void>\n\n constructor (init: MessageStreamInit) {\n super()\n\n this.status = 'open'\n this.log = init.log\n this.direction = init.direction ?? 'outbound'\n this.inactivityTimeout = init.inactivityTimeout ?? 120_000\n this.maxReadBufferLength = init.maxReadBufferLength ?? DEFAULT_MAX_READ_BUFFER_LENGTH\n this.maxWriteBufferLength = init.maxWriteBufferLength\n this.maxMessageSize = init.maxMessageSize\n this.readBuffer = new Uint8ArrayList()\n this.writeBuffer = new Uint8ArrayList()\n\n this.readStatus = 'readable'\n this.remoteReadStatus = 'readable'\n this.writeStatus = 'writable'\n this.remoteWriteStatus = 'writable'\n this.sendingData = false\n this.writableNeedsDrain = false\n\n // @ts-expect-error type could have required fields other than 'open'\n this.timeline = {\n open: Date.now()\n }\n\n this.processSendQueue = this.processSendQueue.bind(this)\n\n const continueSendingOnDrain = (): void => {\n if (this.writableNeedsDrain) {\n this.log.trace('drain event received, continue sending data')\n this.writableNeedsDrain = false\n this.processSendQueue()\n }\n\n this.onDrainPromise?.resolve()\n }\n this.addEventListener('drain', continueSendingOnDrain)\n\n const rejectOnDrainOnClose = (evt: StreamCloseEvent): void => {\n this.onDrainPromise?.reject(evt.error ?? new StreamClosedError())\n }\n this.addEventListener('close', rejectOnDrainOnClose)\n }\n\n get readBufferLength (): number {\n return this.readBuffer.byteLength\n }\n\n get writeBufferLength (): number {\n return this.writeBuffer.byteLength\n }\n\n async onDrain (options?: AbortOptions): Promise<void> {\n if (this.writableNeedsDrain !== true) {\n return Promise.resolve()\n }\n\n if (this.onDrainPromise == null) {\n this.onDrainPromise = Promise.withResolvers()\n }\n\n return raceSignal(this.onDrainPromise.promise, options?.signal)\n }\n\n async * [Symbol.asyncIterator] (): AsyncGenerator<Uint8Array | Uint8ArrayList> {\n if (this.readStatus !== 'readable' && this.readStatus !== 'paused') {\n return\n }\n\n const output = pushable<Uint8Array | Uint8ArrayList>()\n\n const streamAsyncIterableOnMessageListener = (evt: StreamMessageEvent): void => {\n output.push(evt.data)\n }\n this.addEventListener('message', streamAsyncIterableOnMessageListener)\n\n const streamAsyncIterableOnCloseListener = (evt: StreamCloseEvent): void => {\n output.end(evt.error)\n }\n this.addEventListener('close', streamAsyncIterableOnCloseListener)\n\n const streamAsyncIterableOnRemoteCloseWriteListener = (): void => {\n output.end()\n }\n this.addEventListener('remoteCloseWrite', streamAsyncIterableOnRemoteCloseWriteListener)\n\n try {\n yield * output\n } finally {\n this.removeEventListener('message', streamAsyncIterableOnMessageListener)\n this.removeEventListener('close', streamAsyncIterableOnCloseListener)\n this.removeEventListener('remoteCloseWrite', streamAsyncIterableOnRemoteCloseWriteListener)\n }\n }\n\n isReadable (): boolean {\n return this.status === 'open'\n }\n\n send (data: Uint8Array | Uint8ArrayList): boolean {\n if (this.writeStatus === 'closed' || this.writeStatus === 'closing') {\n throw new StreamStateError(`Cannot write to a stream that is ${this.writeStatus}`)\n }\n\n this.log.trace('append %d bytes to write buffer', data.byteLength)\n this.writeBuffer.append(data)\n\n return this.processSendQueue()\n }\n\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort (err: Error): void {\n if (this.status === 'aborted' || this.status === 'reset' || this.status === 'closed') {\n return\n }\n\n this.log.error('abort with error - %e', err)\n\n this.status = 'aborted'\n\n // throw away unread data\n if (this.readBuffer.byteLength > 0) {\n this.readBuffer.consume(this.readBuffer.byteLength)\n }\n\n // throw away unsent data\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength)\n this.safeDispatchEvent('idle')\n }\n\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n\n this.readStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.timeline.close = Date.now()\n\n try {\n this.sendReset(err)\n } catch (err: any) {\n this.log('failed to send reset to remote - %e', err)\n }\n\n this.dispatchEvent(new StreamAbortEvent(err))\n }\n\n pause (): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot pause a stream that is closing/closed')\n }\n\n if (this.readStatus === 'paused') {\n return\n }\n\n this.readStatus = 'paused'\n this.sendPause()\n }\n\n resume (): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError('Cannot resume a stream that is closing/closed')\n }\n\n if (this.readStatus === 'readable') {\n return\n }\n\n this.readStatus = 'readable'\n // emit any data that accumulated while we were paused\n this.dispatchReadBuffer()\n this.sendResume()\n }\n\n push (data: Uint8Array | Uint8ArrayList): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`)\n }\n\n if (data.byteLength === 0) {\n return\n }\n\n this.readBuffer.append(data)\n\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength()\n\n return\n }\n\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer()\n }, 0)\n }\n\n unshift (data: Uint8Array | Uint8ArrayList): void {\n if (this.readStatus === 'closed' || this.readStatus === 'closing') {\n throw new StreamStateError(`Cannot push data onto a stream that is ${this.readStatus}`)\n }\n\n if (data.byteLength === 0) {\n return\n }\n\n this.readBuffer.prepend(data)\n\n if (this.readStatus === 'paused' || this.listenerCount('message') === 0) {\n // abort if the read buffer is too large\n this.checkReadBufferLength()\n\n return\n }\n\n // TODO: use a microtask instead?\n setTimeout(() => {\n this.dispatchReadBuffer()\n }, 0)\n }\n\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n onData (data: Uint8Array | Uint8ArrayList): void {\n if (data.byteLength === 0) {\n // this.log('ignoring empty data')\n return\n }\n\n // discard the data if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('ignoring data - read status %s', this.readStatus)\n return\n }\n\n this.readBuffer.append(data)\n this.dispatchReadBuffer()\n }\n\n addEventListener<K extends keyof MessageStreamEvents>(type: K, listener: EventHandler<MessageStreamEvents[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void\n addEventListener (...args: any[]): void {\n // @ts-expect-error cannot ensure args has enough members\n super.addEventListener.apply(this, args)\n\n // if a 'message' listener is being added and we have queued data, dispatch\n // the data\n if (args[0] === 'message' && this.readBuffer.byteLength > 0) {\n // event listeners can be added in constructors and often use object\n // properties - if this the case we can access a class member before it\n // has been initialized so dispatch the message in the microtask queue\n queueMicrotask(() => {\n this.dispatchReadBuffer()\n })\n }\n }\n\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n onRemoteReset (): void {\n this.log('remote reset')\n\n this.status = 'reset'\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.timeline.close = Date.now()\n\n if (this.readBuffer.byteLength === 0) {\n this.readStatus = 'closed'\n }\n\n const err = new StreamResetError()\n this.dispatchEvent(new StreamResetEvent(err))\n }\n\n /**\n * The underlying resource or transport this stream uses has closed - it is\n * not possible to send any more messages though any data still in the read\n * buffer may still be read\n */\n onTransportClosed (err?: Error): void {\n this.log('transport closed')\n\n if (this.readStatus === 'readable' && this.readBuffer.byteLength === 0) {\n this.log('close readable end after transport closed and read buffer is empty')\n this.readStatus = 'closed'\n }\n\n if (this.remoteReadStatus !== 'closed') {\n this.remoteReadStatus = 'closed'\n }\n\n if (this.remoteWriteStatus !== 'closed') {\n this.remoteWriteStatus = 'closed'\n }\n\n if (this.writeStatus !== 'closed') {\n this.writeStatus = 'closed'\n }\n\n if (err != null) {\n this.abort(err)\n } else {\n if (this.status === 'open' || this.status === 'closing') {\n this.timeline.close = Date.now()\n this.status = 'closed'\n this.writeStatus = 'closed'\n this.remoteWriteStatus = 'closed'\n this.remoteReadStatus = 'closed'\n this.dispatchEvent(new StreamCloseEvent())\n }\n }\n }\n\n /**\n * Called by extending classes when the remote closes its writable end\n */\n onRemoteCloseWrite (): void {\n if (this.remoteWriteStatus === 'closed') {\n return\n }\n\n this.log.trace('on remote close write')\n\n this.remoteWriteStatus = 'closed'\n\n this.safeDispatchEvent('remoteCloseWrite')\n\n if (this.writeStatus === 'closed') {\n this.onTransportClosed()\n }\n }\n\n /**\n * Called by extending classes when the remote closes its readable end\n */\n onRemoteCloseRead (): void {\n this.log.trace('on remote close read')\n\n this.remoteReadStatus = 'closed'\n\n // throw away any unsent bytes if the remote closes it's readable end\n if (this.writeBuffer.byteLength > 0) {\n this.writeBuffer.consume(this.writeBuffer.byteLength)\n this.safeDispatchEvent('idle')\n }\n }\n\n protected processSendQueue (): boolean {\n // bail if the underlying transport is full\n if (this.writableNeedsDrain) {\n this.log.trace('not processing send queue as drain is required')\n this.checkWriteBufferLength()\n\n return false\n }\n\n // bail if there is no data to send\n if (this.writeBuffer.byteLength === 0) {\n this.log.trace('not processing send queue as no bytes to send')\n return true\n }\n\n // bail if we are already sending data\n if (this.sendingData) {\n this.log.trace('not processing send queue as already sending data')\n return true\n }\n\n this.sendingData = true\n\n this.log.trace('processing send queue with %d queued bytes', this.writeBuffer.byteLength)\n\n try {\n let canSendMore = true\n const totalBytes = this.writeBuffer.byteLength\n let sentBytes = 0\n\n // send as much data as possible while we have data to send and the\n // underlying muxer can still accept data\n while (this.writeBuffer.byteLength > 0) {\n const end = Math.min(this.maxMessageSize ?? this.writeBuffer.byteLength, this.writeBuffer.byteLength)\n\n // this can happen if a subclass changes the max message size dynamically\n if (end === 0) {\n canSendMore = false\n break\n }\n\n // chunk to send to the remote end\n const toSend = this.writeBuffer.sublist(0, end)\n\n // copy toSend in case the extending class modifies the list\n const willSend = new Uint8ArrayList(toSend)\n\n this.writeBuffer.consume(toSend.byteLength)\n\n // sending data can cause buffers to fill up, events to be emitted and\n // this method to be invoked again\n const sendResult = this.sendData(toSend)\n canSendMore = sendResult.canSendMore\n sentBytes += sendResult.sentBytes\n\n if (sendResult.sentBytes !== willSend.byteLength) {\n willSend.consume(sendResult.sentBytes)\n this.writeBuffer.prepend(willSend)\n }\n\n if (!canSendMore) {\n break\n }\n }\n\n if (!canSendMore) {\n this.log.trace('sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer', sentBytes, totalBytes, this.writeBuffer.byteLength)\n this.writableNeedsDrain = true\n this.checkWriteBufferLength()\n }\n\n // we processed all bytes in the queue, resolve the write queue idle promise\n if (this.writeBuffer.byteLength === 0) {\n this.safeDispatchEvent('idle')\n }\n\n return canSendMore\n } finally {\n this.sendingData = false\n }\n }\n\n protected dispatchReadBuffer (): void {\n try {\n if (this.listenerCount('message') === 0) {\n this.log.trace('not dispatching pause buffer as there are no listeners for the message event')\n return\n }\n\n if (this.readBuffer.byteLength === 0) {\n this.log.trace('not dispatching pause buffer as there is no data to dispatch')\n return\n }\n\n if (this.readStatus === 'paused') {\n this.log.trace('not dispatching pause buffer we are paused')\n return\n }\n\n // discard the pause buffer if our readable end is closed\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('dropping %d bytes because the readable end is %s', this.readBuffer.byteLength, this.readStatus)\n this.readBuffer.consume(this.readBuffer.byteLength)\n return\n }\n\n const buf = this.readBuffer.sublist()\n this.readBuffer.consume(buf.byteLength)\n\n this.dispatchEvent(new StreamMessageEvent(buf))\n } finally {\n if (this.readBuffer.byteLength === 0 && this.remoteWriteStatus === 'closed') {\n this.log('close readable end after dispatching read buffer and remote writable end is closed')\n this.readStatus = 'closed'\n }\n\n // abort if we failed to consume the read buffer and it is too large\n this.checkReadBufferLength()\n }\n }\n\n private checkReadBufferLength (): void {\n if (this.readBuffer.byteLength > this.maxReadBufferLength) {\n this.abort(new StreamBufferError(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))\n }\n }\n\n private checkWriteBufferLength (): void {\n if (this.maxWriteBufferLength == null) {\n return\n }\n\n if (this.writeBuffer.byteLength > this.maxWriteBufferLength) {\n this.abort(new StreamBufferError(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))\n }\n }\n\n public onMuxerNeedsDrain (): void {\n this.writableNeedsDrain = true\n }\n\n public onMuxerDrain (): void {\n this.safeDispatchEvent('drain')\n }\n\n /**\n * Send a data message to the remote end of the stream. Implementations of\n * this method should return the number of bytes from the passed buffer that\n * were sent successfully and if the underlying resource can accept more data.\n *\n * The implementation should always attempt to send the maximum amount of data\n * possible.\n *\n * Returning a result that means the data was only partially sent but that the\n * underlying resource can accept more data is invalid.\n */\n abstract sendData (data: Uint8ArrayList): SendResult\n\n /**\n * Send a reset message to the remote end of the stream\n */\n abstract sendReset (err: Error): void\n\n /**\n * If supported, instruct the remote end of the stream to temporarily stop\n * sending data messages\n */\n abstract sendPause (): void\n\n /**\n * If supported, inform the remote end of the stream they may resume sending\n * data messages\n */\n abstract sendResume (): void\n\n /**\n * Stop accepting new data to send and return a promise that resolves when any\n * unsent data has been written into the underlying resource.\n */\n abstract close (options?: AbortOptions): Promise<void>\n}\n", "import { pEvent } from 'p-event'\nimport { AbstractMessageStream } from './abstract-message-stream.ts'\nimport type { MessageStreamInit } from './abstract-message-stream.ts'\nimport type { CounterGroup, Logger, MultiaddrConnection, MessageStreamDirection, AbortOptions } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface AbstractMultiaddrConnectionInit extends Omit<MessageStreamInit, 'log'> {\n remoteAddr: Multiaddr\n direction: MessageStreamDirection\n log: Logger\n inactivityTimeout?: number\n localAddr?: Multiaddr\n metricPrefix?: string\n metrics?: CounterGroup\n}\n\nexport abstract class AbstractMultiaddrConnection extends AbstractMessageStream implements MultiaddrConnection {\n public remoteAddr: Multiaddr\n\n private metricPrefix: string\n private metrics?: CounterGroup\n\n constructor (init: AbstractMultiaddrConnectionInit) {\n super(init)\n\n this.metricPrefix = init.metricPrefix ?? ''\n this.metrics = init.metrics\n this.remoteAddr = init.remoteAddr\n\n this.addEventListener('close', (evt) => {\n this.metrics?.increment({ [`${this.metricPrefix}end`]: true })\n\n if (evt.error != null) {\n if (evt.local) {\n this.metrics?.increment({ [`${this.metricPrefix}abort`]: true })\n } else {\n this.metrics?.increment({ [`${this.metricPrefix}reset`]: true })\n }\n } else {\n if (evt.local) {\n this.metrics?.increment({ [`${this.metricPrefix}_local_close`]: true })\n } else {\n this.metrics?.increment({ [`${this.metricPrefix}_remote_close`]: true })\n }\n }\n })\n }\n\n async close (options?: AbortOptions): Promise<void> {\n if (this.status !== 'open') {\n return\n }\n\n this.status = 'closing'\n this.writeStatus = 'closing'\n this.remoteWriteStatus = 'closing'\n this.remoteReadStatus = 'closing'\n\n // if we are currently sending data, wait for all the data to be written\n // into the underlying transport\n if (this.sendingData || this.writeBuffer.byteLength > 0) {\n this.log('waiting for write queue to become idle before closing writable end of stream, %d unsent bytes', this.writeBuffer.byteLength)\n await pEvent(this, 'idle', {\n ...options,\n rejectionEvents: [\n 'close'\n ]\n })\n }\n\n // now that the underlying transport has all the data, if the buffer is full\n // wait for it to be emptied\n if (this.writableNeedsDrain) {\n this.log('waiting for write queue to drain before closing writable end of stream, %d unsent bytes', this.writeBuffer.byteLength)\n await pEvent(this, 'drain', {\n ...options,\n rejectionEvents: [\n 'close'\n ]\n })\n }\n\n await this.sendClose(options)\n\n this.onTransportClosed()\n }\n\n /**\n * Wait for any unsent data to be written to the underlying resource, then\n * close the resource and resolve the returned promise\n */\n abstract sendClose (options?: AbortOptions): Promise<void>\n}\n", "\nexport interface ClearableSignal extends AbortSignal {\n clear: () => void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n controller.abort()\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n public type: string\n public code: string | string\n\n constructor (message?: string, code?: string, name?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = name ?? 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RaceSignalOptions {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * The name for the error thrown if the signal aborts\n */\n errorName?: string\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName))\n }\n\n let listener\n\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName)\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(error)\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable<string>()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { AbortOptions } from 'abort-error'\nimport type { RaceSignalOptions } from 'race-signal'\n\nexport interface Pushable<T> extends AsyncGenerator<T, void, unknown> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void>\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T, options?: AbortOptions & RaceSignalOptions): Promise<void>\n}\n\nclass QueuelessPushable <T> implements Pushable<T> {\n private readNext: PromiseWithResolvers<void>\n private haveNext: PromiseWithResolvers<void>\n private ended: boolean\n private nextResult: IteratorResult<T> | undefined\n private error?: Error\n\n constructor () {\n this.ended = false\n\n this.readNext = deferred()\n this.haveNext = deferred()\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<T, void, unknown> {\n return this\n }\n\n async next (): Promise<IteratorResult<T, void>> {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise\n }\n\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined')\n }\n\n const nextResult = this.nextResult\n this.nextResult = undefined\n\n // signal to the supplier that we read the value\n this.readNext.resolve()\n this.readNext = deferred()\n\n return nextResult\n }\n\n async throw (err?: Error): Promise<IteratorReturnResult<undefined>> {\n this.ended = true\n this.error = err\n\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => {})\n this.haveNext.reject(err)\n }\n\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n async return (): Promise<IteratorResult<T>> {\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n this.ended = true\n this.nextResult = result\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n\n return result\n }\n\n async push (value: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n await this._push(value, options)\n }\n\n async end (err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (err != null) {\n await this.throw(err)\n } else {\n // abortable return\n await this._push(undefined, options)\n }\n }\n\n private async _push (value?: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (value != null && this.ended) {\n throw this.error ?? new Error('Cannot push value onto an ended pushable')\n }\n\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise\n }\n\n if (value != null) {\n this.nextResult = { done: false, value }\n } else {\n this.ended = true\n this.nextResult = { done: true, value: undefined }\n }\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n this.haveNext = deferred()\n\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(\n this.readNext.promise,\n options?.signal,\n options\n )\n }\n}\n\nexport function queuelessPushable <T> (): Pushable<T> {\n return new QueuelessPushable<T>()\n}\n", "/**\n * @packageDocumentation\n *\n * Merge several (async)iterables into one, yield values as they arrive.\n *\n * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.\n *\n * @example\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values1 = [0, 1, 2, 3, 4]\n * const values2 = [5, 6, 7, 8, 9]\n *\n * const arr = all(merge(values1, values2))\n *\n * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const values1 = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n * const values2 = async function * () {\n * yield * [5, 6, 7, 8, 9]\n * }\n *\n * const arr = await all(merge(values1(), values2()))\n *\n * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed\n * ```\n */\n\nimport { queuelessPushable } from 'it-queueless-pushable'\nimport type { Pushable } from 'it-queueless-pushable'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\nasync function addAllToPushable <T> (sources: Array<AsyncIterable<T> | Iterable<T>>, output: Pushable<T>, signal: AbortSignal): Promise<void> {\n try {\n await Promise.all(\n sources.map(async (source) => {\n for await (const item of source) {\n await output.push(item, {\n signal\n })\n signal.throwIfAborted()\n }\n })\n )\n\n await output.end(undefined, {\n signal\n })\n } catch (err: any) {\n await output.end(err, {\n signal\n })\n .catch(() => {})\n }\n}\n\nasync function * mergeSources <T> (sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> {\n const controller = new AbortController()\n const output = queuelessPushable<T>()\n\n addAllToPushable(sources, output, controller.signal)\n .catch(() => {})\n\n try {\n yield * output\n } finally {\n controller.abort()\n }\n}\n\nfunction * mergeSyncSources <T> (syncSources: Array<Iterable<T>>): Generator<T, void, undefined> {\n for (const source of syncSources) {\n yield * source\n }\n}\n\n/**\n * Treat one or more iterables as a single iterable.\n *\n * Nb. sources are iterated over in parallel so the\n * order of emitted items is not guaranteed.\n */\nfunction merge <T> (...sources: Array<Iterable<T>>): Generator<T, void, undefined>\nfunction merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined>\nfunction merge <T> (...sources: Array<AsyncIterable<T> | Iterable<T>>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n const syncSources: Array<Iterable<T>> = []\n\n for (const source of sources) {\n if (!isAsyncIterable(source)) {\n syncSources.push(source)\n }\n }\n\n if (syncSources.length === sources.length) {\n // all sources are synchronous\n return mergeSyncSources(syncSources)\n }\n\n return mergeSources(sources)\n}\n\nexport default merge\n", "import { pushable } from 'it-pushable'\nimport merge from 'it-merge'\nimport type { Duplex, Transform, Sink } from 'it-stream-types'\n\ninterface SourceFn<A = any> { (): A }\n\ntype PipeSource<A = any> =\n Iterable<A> |\n AsyncIterable<A> |\n SourceFn<A> |\n Duplex<A, any, any>\n\ntype PipeTransform<A = any, B = any> =\n Transform<A, B> |\n Duplex<B, A>\n\ntype PipeSink<A = any, B = any> =\n Sink<A, B> |\n Duplex<any, A, B>\n\ntype PipeOutput<A> =\n A extends Sink<any> ? ReturnType<A> :\n A extends Duplex<any, any, any> ? ReturnType<A['sink']> :\n never\n\n// single item pipe output includes pipe source types\ntype SingleItemPipeOutput<A> =\n A extends Iterable<any> ? A :\n A extends AsyncIterable<any> ? A :\n A extends SourceFn ? ReturnType<A> :\n A extends Duplex<any, any, any> ? A['source'] :\n PipeOutput<A>\n\ntype PipeFnInput<A> =\n A extends Iterable<any> ? A :\n A extends AsyncIterable<any> ? A :\n A extends SourceFn ? ReturnType<A> :\n A extends Transform<any, any> ? ReturnType<A> :\n A extends Duplex<any, any, any> ? A['source'] :\n never\n\n// one item, just a pass-through\nexport function pipe<\n A extends PipeSource\n> (\n source: A\n): SingleItemPipeOutput<A>\n\n// two items, source to sink\nexport function pipe<\n A extends PipeSource,\n B extends PipeSink<PipeFnInput<A>>\n> (\n source: A,\n sink: B\n): PipeOutput<B>\n\n// three items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeSink<PipeFnInput<B>>\n> (\n source: A,\n transform1: B,\n sink: C\n): PipeOutput<C>\n\n// many items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeSink<PipeFnInput<C>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n sink: D\n): PipeOutput<D>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeSink<PipeFnInput<D>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n sink: E\n): PipeOutput<E>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeSink<PipeFnInput<E>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n sink: F\n): PipeOutput<F>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeSink<PipeFnInput<F>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n sink: G\n): PipeOutput<G>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeSink<PipeFnInput<G>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n sink: H\n): PipeOutput<H>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeSink<PipeFnInput<H>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n sink: I\n): PipeOutput<I>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeTransform<PipeFnInput<H>>,\n J extends PipeSink<PipeFnInput<I>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n sink: J\n): PipeOutput<J>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeTransform<PipeFnInput<H>>,\n J extends PipeTransform<PipeFnInput<I>>,\n K extends PipeSink<PipeFnInput<J>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n transform9: J,\n sink: K\n): PipeOutput<K>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeTransform<PipeFnInput<H>>,\n J extends PipeTransform<PipeFnInput<I>>,\n K extends PipeTransform<PipeFnInput<J>>,\n L extends PipeSink<PipeFnInput<K>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n transform9: J,\n transform10: K,\n sink: L\n): PipeOutput<L>\n\nexport function pipe (first: any, ...rest: any[]): any {\n if (first == null) {\n throw new Error('Empty pipeline')\n }\n\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first\n first = () => duplex.source\n // Iterable at start: wrap in function\n } else if (isIterable(first) || isAsyncIterable(first)) {\n const source = first\n first = () => source\n }\n\n const fns = [first, ...rest]\n\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink\n }\n }\n\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i])\n }\n }\n }\n\n return rawPipe(...fns)\n}\n\nexport const rawPipe = (...fns: any): any => {\n let res\n while (fns.length > 0) {\n res = fns.shift()(res)\n }\n return res\n}\n\nconst isAsyncIterable = (obj: any): obj is AsyncIterable<unknown> => {\n return obj?.[Symbol.asyncIterator] != null\n}\n\nconst isIterable = (obj: any): obj is Iterable<unknown> => {\n return obj?.[Symbol.iterator] != null\n}\n\nconst isDuplex = (obj: any): obj is Duplex => {\n if (obj == null) {\n return false\n }\n\n return obj.sink != null && obj.source != null\n}\n\nconst duplexPipelineFn = (duplex: Duplex<any, any, any>) => {\n return (source: any) => {\n const p = duplex.sink(source)\n\n if (p?.then != null) {\n const stream = pushable<any>({\n objectMode: true\n })\n p.then(() => {\n stream.end()\n }, (err: Error) => {\n stream.end(err)\n })\n\n let sourceWrap: () => Iterable<any> | AsyncIterable<any>\n const source = duplex.source\n\n if (isAsyncIterable(source)) {\n sourceWrap = async function * () {\n yield * source\n stream.end()\n }\n } else if (isIterable(source)) {\n sourceWrap = function * () {\n yield * source\n stream.end()\n }\n } else {\n throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable')\n }\n\n return merge(stream, sourceWrap())\n }\n\n return duplex.source\n }\n}\n", "import { StreamMessageEvent, StreamCloseEvent, InvalidParametersError } from '@libp2p/interface'\nimport { pipe as itPipe } from 'it-pipe'\nimport { pushable } from 'it-pushable'\nimport { pEvent } from 'p-event'\nimport { raceSignal } from 'race-signal'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { UnexpectedEOFError } from './errors.js'\nimport type { MessageStream, MultiaddrConnection, Stream, AbortOptions } from '@libp2p/interface'\nimport type { Duplex, Source, Transform, Sink } from 'it-stream-types'\n\nconst DEFAULT_MAX_BUFFER_SIZE = 4_194_304\n\nexport class UnwrappedError extends Error {\n static name = 'UnwrappedError'\n name = 'UnwrappedError'\n}\n\n/**\n * The reported length of the next data message was not a positive integer\n */\nexport class InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError'\n code = 'ERR_INVALID_MSG_LENGTH'\n}\n\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nexport class InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError'\n code = 'ERR_MSG_DATA_TOO_LONG'\n}\n\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nexport class InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError'\n code = 'ERR_MSG_LENGTH_TOO_LONG'\n}\n\nexport interface ByteStreamOpts {\n /**\n * Incoming bytes are buffered until read, this setting limits how many bytes\n * will be buffered.\n *\n * @default 4_194_304\n */\n maxBufferSize?: number\n}\n\nexport interface ReadBytesOptions extends AbortOptions {\n /**\n * If specified, read this number of bytes from the stream\n */\n bytes: number\n}\n\nexport interface ByteStream<S extends MessageStream> {\n /**\n * Read bytes from the stream.\n *\n * If a required number of bytes is passed as an option, this will wait for\n * the underlying stream to supply that number of bytes, throwing an\n * `UnexpectedEOFError` if the stream closes before this happens.\n *\n * If no required number of bytes is passed, this will return `null` if the\n * underlying stream closes before supplying any bytes.\n */\n read(options: ReadBytesOptions): Promise<Uint8ArrayList>\n read(options?: AbortOptions): Promise<Uint8ArrayList | null>\n\n /**\n * Write the passed bytes to the stream\n */\n write(data: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>\n\n /**\n * After calling this method the stream can no longer be used. Any unread data\n * will be emitted as a message event during the microtask queue of the\n * current event loop tick.\n */\n unwrap(): S\n}\n\nfunction isStream (obj?: any): obj is Stream {\n return typeof obj?.closeRead === 'function'\n}\n\nfunction isMultiaddrConnection (obj?: any): obj is MultiaddrConnection {\n return typeof obj?.close === 'function'\n}\n\nfunction isEOF (obj?: any): boolean {\n if (isStream(obj)) {\n return obj.remoteWriteStatus !== 'writable' && obj.readBufferLength === 0\n }\n\n if (isMultiaddrConnection(obj)) {\n return obj.status !== 'open'\n }\n\n return false\n}\n\ntype ByteStreamReadable = Pick<Stream & MultiaddrConnection, 'addEventListener' | 'removeEventListener' | 'send' | 'push' | 'log'>\n\nfunction isValid (obj?: any): obj is ByteStreamReadable {\n return obj?.addEventListener != null && obj?.removeEventListener != null && obj?.send != null && obj?.push != null && obj?.log != null\n}\n\nexport function byteStream <T extends MessageStream> (stream: T, opts?: ByteStreamOpts): ByteStream<T> {\n const maxBufferSize = opts?.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE\n const readBuffer = new Uint8ArrayList()\n\n let hasBytes: PromiseWithResolvers<void> | undefined\n let unwrapped = false\n\n if (!isValid(stream)) {\n throw new InvalidParametersError('Argument should be a Stream or a Multiaddr')\n }\n\n const byteStreamOnMessageListener = (evt: StreamMessageEvent): void => {\n readBuffer.append(evt.data)\n\n if (readBuffer.byteLength > maxBufferSize) {\n const readBufferSize = readBuffer.byteLength\n readBuffer.consume(readBuffer.byteLength)\n hasBytes?.reject(new Error(`Read buffer overflow - ${readBufferSize} > ${maxBufferSize}`))\n }\n\n hasBytes?.resolve()\n }\n stream.addEventListener('message', byteStreamOnMessageListener)\n\n const byteStreamOnCloseListener = (evt: StreamCloseEvent): void => {\n if (evt.error != null) {\n hasBytes?.reject(evt.error)\n } else {\n hasBytes?.resolve()\n }\n }\n stream.addEventListener('close', byteStreamOnCloseListener)\n\n const byteStreamOnRemoteCloseWrite = (): void => {\n hasBytes?.resolve()\n }\n stream.addEventListener('remoteCloseWrite', byteStreamOnRemoteCloseWrite)\n\n const byteStream: ByteStream<T> = {\n readBuffer,\n\n // @ts-expect-error options type prevents type inference\n async read (options?: ReadBytesOptions) {\n if (unwrapped === true) {\n throw new UnwrappedError('Stream was unwrapped')\n }\n\n if (isEOF(stream)) {\n if (options?.bytes == null) {\n return null\n }\n\n if (readBuffer.byteLength < options.bytes) {\n stream.log.error('closed after reading %d/%d bytes', readBuffer.byteLength, options.bytes)\n throw new UnexpectedEOFError(`Unexpected EOF - stream closed after reading ${readBuffer.byteLength}/${options.bytes} bytes`)\n }\n }\n\n const bytesToRead = options?.bytes ?? 1\n hasBytes = Promise.withResolvers<void>()\n\n while (true) {\n if (readBuffer.byteLength >= bytesToRead) {\n // if we are about to exit the loop this promise will not be awaited\n // so resolve it to prevent and unhandled promise rejections that may\n // occur\n hasBytes.resolve()\n\n break\n }\n\n await raceSignal(hasBytes.promise, options?.signal)\n\n if (isEOF(stream)) {\n if (readBuffer.byteLength === 0 && options?.bytes == null) {\n return null\n }\n\n break\n }\n\n hasBytes = Promise.withResolvers<void>()\n }\n\n const toRead = options?.bytes ?? readBuffer.byteLength\n\n if (readBuffer.byteLength < toRead) {\n if (isEOF(stream)) {\n stream.log.error('closed while reading %d/%d bytes', readBuffer.byteLength, toRead)\n throw new UnexpectedEOFError(`Unexpected EOF - stream closed while reading ${readBuffer.byteLength}/${toRead} bytes`)\n }\n\n return byteStream.read(options)\n }\n\n const output = readBuffer.sublist(0, toRead)\n readBuffer.consume(toRead)\n\n return output\n },\n async write (data: Uint8Array | Uint8ArrayList, options?: AbortOptions) {\n if (unwrapped === true) {\n throw new UnwrappedError('Stream was unwrapped')\n }\n\n if (!stream.send(data)) {\n await pEvent(stream, 'drain', {\n signal: options?.signal,\n rejectionEvents: ['close']\n })\n }\n },\n unwrap () {\n // already unwrapped, just return the original stream\n if (unwrapped) {\n return stream\n }\n\n // only unwrap once\n unwrapped = true\n stream.removeEventListener('message', byteStreamOnMessageListener)\n stream.removeEventListener('close', byteStreamOnCloseListener)\n stream.removeEventListener('remoteCloseWrite', byteStreamOnRemoteCloseWrite)\n\n // emit any unread data\n if (readBuffer.byteLength > 0) {\n stream.log('stream unwrapped with %d unread bytes', readBuffer.byteLength)\n stream.push(readBuffer)\n }\n\n return stream\n }\n }\n\n return byteStream\n}\n\nexport interface LengthPrefixedStream<S extends MessageStream = MessageStream> {\n /**\n * Read the next length-prefixed number of bytes from the stream\n */\n read(options?: AbortOptions): Promise<Uint8ArrayList>\n\n /**\n * Write the passed bytes to the stream prefixed by their length\n */\n write(data: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>\n\n /**\n * Write passed list of bytes, prefix by their individual lengths to the stream as a single write\n */\n writeV(input: Array<Uint8Array | Uint8ArrayList>, options?: AbortOptions): Promise<void>\n\n /**\n * Returns the underlying stream\n */\n unwrap(): S\n}\n\nexport interface LengthPrefixedStreamOpts extends ByteStreamOpts {\n lengthEncoder (value: number): Uint8ArrayList | Uint8Array\n lengthDecoder (data: Uint8ArrayList): number\n maxLengthLength: number\n maxDataLength: number\n}\n\nexport function lpStream <T extends MessageStream> (stream: T, opts: Partial<LengthPrefixedStreamOpts> = {}): LengthPrefixedStream<T> {\n const bytes = byteStream(stream, opts)\n\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength)\n }\n\n const decodeLength = opts?.lengthDecoder ?? varint.decode\n const encodeLength = opts?.lengthEncoder ?? varint.encode\n\n const lpStream: LengthPrefixedStream<any> = {\n async read (options?: AbortOptions) {\n let dataLength: number = -1\n const lengthBuffer = new Uint8ArrayList()\n\n while (true) {\n // read one byte at a time until we can decode a varint\n const buf = await bytes.read({\n ...options,\n bytes: 1\n })\n\n // the underlying resource closed gracefully\n if (buf == null) {\n break\n }\n\n // append byte and try to decode\n lengthBuffer.append(buf)\n\n try {\n dataLength = decodeLength(lengthBuffer)\n } catch (err) {\n if (err instanceof RangeError) {\n continue\n }\n\n throw err\n }\n\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length')\n }\n\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new InvalidDataLengthLengthError(`Message length length too long - ${lengthBuffer.byteLength} > ${opts.maxLengthLength}`)\n }\n\n if (dataLength > -1) {\n break\n }\n }\n\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new InvalidDataLengthError(`Message length too long - ${dataLength} > ${opts.maxDataLength}`)\n }\n\n const buf = await bytes.read({\n ...options,\n bytes: dataLength\n })\n\n if (buf == null) {\n stream.log.error('tried to read %d bytes but the stream closed', dataLength)\n throw new UnexpectedEOFError(`Unexpected EOF - tried to read ${dataLength} bytes but the stream closed`)\n }\n\n if (buf.byteLength !== dataLength) {\n stream.log.error('read %d/%d bytes before the stream closed', buf.byteLength, dataLength)\n throw new UnexpectedEOFError(`Unexpected EOF - read ${buf.byteLength}/${dataLength} bytes before the stream closed`)\n }\n\n return buf\n },\n async write (data, options?: AbortOptions) {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options)\n },\n async writeV (data, options?: AbortOptions) {\n const list = new Uint8ArrayList(\n ...data.flatMap(buf => ([encodeLength(buf.byteLength), buf]))\n )\n\n // encode, write\n await bytes.write(list, options)\n },\n unwrap () {\n return bytes.unwrap()\n }\n }\n\n return lpStream\n}\n\n/**\n * A protobuf decoder - takes a byte array and returns an object\n */\nexport interface ProtobufDecoder<T> {\n (data: Uint8Array | Uint8ArrayList): T\n}\n\n/**\n * A protobuf encoder - takes an object and returns a byte array\n */\nexport interface ProtobufEncoder<T> {\n (data: T): Uint8Array\n}\n\n/**\n * Convenience methods for working with protobuf streams\n */\nexport interface ProtobufStream<S extends MessageStream = MessageStream> {\n /**\n * Read the next length-prefixed byte array from the stream and decode it as the passed protobuf format\n */\n read<T>(proto: { decode: ProtobufDecoder<T> }, options?: AbortOptions): Promise<T>\n\n /**\n * Encode the passed object as a protobuf message and write it's length-prefixed bytes to the stream\n */\n write<T>(data: T, proto: { encode: ProtobufEncoder<T> }, options?: AbortOptions): Promise<void>\n\n /**\n * Encode the passed objects as protobuf messages and write their length-prefixed bytes to the stream as a single write\n */\n writeV<T>(input: T[], proto: { encode: ProtobufEncoder<T> }, options?: AbortOptions): Promise<void>\n\n /**\n * Returns an object with read/write methods for operating on one specific type of protobuf message\n */\n pb<T>(proto: { encode: ProtobufEncoder<T>, decode: ProtobufDecoder<T> }): ProtobufMessageStream<T, S>\n\n /**\n * Returns the underlying stream\n */\n unwrap(): S\n}\n\n/**\n * A message reader/writer that only uses one type of message\n */\nexport interface ProtobufMessageStream <T, S extends MessageStream = MessageStream> {\n /**\n * Read a message from the stream\n */\n read(options?: AbortOptions): Promise<T>\n\n /**\n * Write a message to the stream\n */\n write(d: T, options?: AbortOptions): Promise<void>\n\n /**\n * Write several messages to the stream\n */\n writeV(d: T[], options?: AbortOptions): Promise<void>\n\n /**\n * Unwrap the underlying protobuf stream\n */\n unwrap(): ProtobufStream<S>\n}\n\nexport interface ProtobufStreamOpts extends LengthPrefixedStreamOpts {\n\n}\n\nexport function pbStream <T extends MessageStream = Stream> (stream: T, opts?: Partial<ProtobufStreamOpts>): ProtobufStream<T> {\n const lp = lpStream(stream, opts)\n\n const pbStream: ProtobufStream<T> = {\n read: async (proto, options?: AbortOptions) => {\n // readLP, decode\n const value = await lp.read(options)\n\n return proto.decode(value)\n },\n write: async (message, proto, options?: AbortOptions) => {\n // encode, writeLP\n await lp.write(proto.encode(message), options)\n },\n writeV: async (messages, proto, options?: AbortOptions) => {\n // encode, writeLP\n await lp.writeV(messages.map(message => proto.encode(message)), options)\n },\n pb: (proto) => {\n return {\n read: async (options) => pbStream.read(proto, options),\n write: async (d, options) => pbStream.write(d, proto, options),\n writeV: async (d, options) => pbStream.writeV(d, proto, options),\n unwrap: () => pbStream\n }\n },\n unwrap: () => {\n return lp.unwrap()\n }\n }\n\n return pbStream\n}\n\nexport async function echo (stream: MessageStream, options?: AbortOptions): Promise<void> {\n const log = stream.log.newScope('echo')\n const start = Date.now()\n\n let bytes = 0\n\n try {\n for await (const buf of stream) {\n bytes += buf.byteLength\n\n if (!stream.send(buf)) {\n stream.pause()\n\n await pEvent(stream, 'drain', {\n rejectionEvents: [\n 'close'\n ],\n ...options\n })\n\n stream.resume()\n }\n }\n\n log('echoed %d bytes in %dms', bytes, Date.now() - start)\n\n await stream.close(options)\n } catch (err: any) {\n stream.abort(err)\n }\n}\n\nexport type PipeInput = Iterable<Uint8Array | Uint8ArrayList> | AsyncIterable<Uint8Array | Uint8ArrayList> | Stream\n\nfunction isMessageStream (obj?: any): obj is Stream {\n return obj?.addEventListener != null\n}\n\nexport function messageStreamToDuplex (stream: Stream): Duplex<AsyncGenerator<Uint8ArrayList | Uint8Array>, Iterable<Uint8ArrayList | Uint8Array> | AsyncIterable<Uint8ArrayList | Uint8Array>, Promise<void>> {\n const source = pushable<Uint8ArrayList | Uint8Array>()\n let onError: PromiseWithResolvers<IteratorResult<Uint8ArrayList | Uint8Array>> | undefined\n\n const onMessage = (evt: StreamMessageEvent): void => {\n source.push(evt.data)\n }\n\n const onRemoteCloseWrite = (): void => {\n source.end()\n\n stream.removeEventListener('message', onMessage)\n stream.removeEventListener('close', onClose)\n stream.removeEventListener('remoteCloseWrite', onRemoteCloseWrite)\n }\n\n const onClose = (evt: StreamCloseEvent): void => {\n source.end(evt.error)\n\n if (evt.error != null) {\n onError?.reject(evt.error)\n }\n\n stream.removeEventListener('message', onMessage)\n stream.removeEventListener('close', onClose)\n stream.removeEventListener('remoteCloseWrite', onRemoteCloseWrite)\n }\n\n stream.addEventListener('message', onMessage)\n stream.addEventListener('close', onClose, {\n once: true\n })\n stream.addEventListener('remoteCloseWrite', onRemoteCloseWrite, {\n once: true\n })\n\n return {\n source,\n async sink (source: Source<Uint8Array | Uint8ArrayList>) {\n async function * toGenerator (): AsyncGenerator<Uint8Array | Uint8ArrayList> {\n yield * source\n }\n\n const gen = toGenerator()\n\n while (true) {\n onError = Promise.withResolvers<IteratorResult<Uint8ArrayList | Uint8Array>>()\n\n const { done, value } = await Promise.race([\n gen.next(),\n onError.promise\n ])\n\n if (stream.writeStatus === 'closing' || stream.writeStatus === 'closed') {\n break\n }\n\n if (value != null) {\n if (!stream.send(value)) {\n await Promise.race([\n pEvent(stream, 'drain', {\n rejectionEvents: [\n 'close'\n ]\n })\n ])\n }\n }\n\n if (done === true) {\n break\n }\n }\n\n await stream.close()\n }\n }\n}\n\ninterface SourceFn<A = any> { (): A }\n\ntype PipeSource<A = any> =\n Iterable<A> |\n AsyncIterable<A> |\n SourceFn<A> |\n Duplex<A, any, any> |\n MessageStream\n\ntype PipeTransform<A = any, B = any> =\n Transform<A, B> |\n Duplex<B, A> |\n MessageStream\n\ntype PipeSink<A = any, B = any> =\n Sink<A, B> |\n Duplex<any, A, B> |\n MessageStream\n\ntype PipeOutput<A> =\n A extends Sink<any> ? ReturnType<A> :\n A extends Duplex<any, any, any> ? ReturnType<A['sink']> :\n A extends MessageStream ? Promise<void> :\n never\n\n// single item pipe output includes pipe source types\ntype SingleItemPipeOutput<A> =\n A extends Iterable<any> ? A :\n A extends AsyncIterable<any> ? A :\n A extends SourceFn ? ReturnType<A> :\n A extends Duplex<any, any, any> ? A['source'] :\n PipeOutput<A>\n\ntype PipeFnInput<A> =\n A extends Iterable<any> ? A :\n A extends AsyncIterable<any> ? A :\n A extends SourceFn ? ReturnType<A> :\n A extends Transform<any, any> ? ReturnType<A> :\n A extends Duplex<any, any, any> ? A['source'] :\n never\n\nexport function pipe<\n A extends PipeSource\n> (\n source: A\n): SingleItemPipeOutput<A>\n// two items, source to sink\nexport function pipe<\n A extends PipeSource,\n B extends PipeSink<PipeFnInput<A>>\n> (\n source: A,\n sink: B\n): PipeOutput<B>\n\n// three items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeSink<PipeFnInput<B>>\n> (\n source: A,\n transform1: B,\n sink: C\n): PipeOutput<C>\n\n// many items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeSink<PipeFnInput<C>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n sink: D\n): PipeOutput<D>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeSink<PipeFnInput<D>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n sink: E\n): PipeOutput<E>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeSink<PipeFnInput<E>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n sink: F\n): PipeOutput<F>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeSink<PipeFnInput<F>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n sink: G\n): PipeOutput<G>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeSink<PipeFnInput<G>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n sink: H\n): PipeOutput<H>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeSink<PipeFnInput<H>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n sink: I\n): PipeOutput<I>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeTransform<PipeFnInput<H>>,\n J extends PipeSink<PipeFnInput<I>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n sink: J\n): PipeOutput<J>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeTransform<PipeFnInput<H>>,\n J extends PipeTransform<PipeFnInput<I>>,\n K extends PipeSink<PipeFnInput<J>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n transform9: J,\n sink: K\n): PipeOutput<K>\n\n// lots of items, source to sink with transform(s) in between\nexport function pipe<\n A extends PipeSource,\n B extends PipeTransform<PipeFnInput<A>>,\n C extends PipeTransform<PipeFnInput<B>>,\n D extends PipeTransform<PipeFnInput<C>>,\n E extends PipeTransform<PipeFnInput<D>>,\n F extends PipeTransform<PipeFnInput<E>>,\n G extends PipeTransform<PipeFnInput<F>>,\n H extends PipeTransform<PipeFnInput<G>>,\n I extends PipeTransform<PipeFnInput<H>>,\n J extends PipeTransform<PipeFnInput<I>>,\n K extends PipeTransform<PipeFnInput<J>>,\n L extends PipeSink<PipeFnInput<K>>\n> (\n source: A,\n transform1: B,\n transform2: C,\n transform3: D,\n transform4: E,\n transform5: F,\n transform6: G,\n transform7: H,\n transform8: I,\n transform9: J,\n transform10: K,\n sink: L\n): PipeOutput<L>\nexport function pipe (...input: any[]): any {\n const sources = input.map(source => {\n if (isMessageStream(source)) {\n return messageStreamToDuplex(source)\n }\n\n return source\n })\n\n // @ts-expect-error it-pipe types say args cannot be spread like this\n return itPipe(...sources)\n}\n", "import { Queue } from './queue/index.js'\nimport type { Job } from './queue/job.js'\nimport type { AbortOptions, PeerId } from '@libp2p/interface'\n\nexport interface PeerQueueJobOptions extends AbortOptions {\n peerId: PeerId\n}\n\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nexport class PeerQueue<JobReturnType = void, JobOptions extends PeerQueueJobOptions = PeerQueueJobOptions> extends Queue<JobReturnType, JobOptions> {\n has (peerId: PeerId): boolean {\n return this.find(peerId) != null\n }\n\n find (peerId: PeerId): Job<JobOptions, JobReturnType> | undefined {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId)\n })\n }\n}\n", "import type { Matcher, MultiaddrMatcher } from './index.js'\nimport type { Multiaddr, Component } from '@multiformats/multiaddr'\n\n/**\n * Matches a multiaddr component with the specified code but no value\n */\nexport const code = (code: number): Matcher => {\n return {\n match: (vals) => {\n const component = vals[0]\n\n if (component == null) {\n return false\n }\n\n if (component.code !== code) {\n return false\n }\n\n if (component.value != null) {\n return false\n }\n\n return vals.slice(1)\n }\n }\n}\n\n/**\n * Matches a multiaddr component with the specified code and value. If the value\n * is omitted any non-undefined value is matched.\n */\nexport const value = (code: number, value?: string): Matcher => {\n return {\n match: (vals) => {\n const component = vals[0]\n\n if (component?.code !== code) {\n return false\n }\n\n if (component.value == null) {\n return false\n }\n\n if (value != null && component.value !== value) {\n return false\n }\n\n return vals.slice(1)\n }\n }\n}\n\n/**\n * Matches a multiaddr component with the specified code and value. If the value\n * is omitted any non-undefined value is matched.\n */\nexport const not = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return false\n }\n }\n}\n\n/**\n * An optional matcher\n */\nexport const optional = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return result\n }\n }\n}\n\n/**\n * Matches any one of the passed matches\n */\nexport const or = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n let matches: Component[] | undefined\n\n for (const matcher of matchers) {\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n continue\n }\n\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result\n }\n }\n\n if (matches == null) {\n return false\n }\n\n return matches\n }\n }\n}\n\n/**\n * Matches all of the passed matchers\n */\nexport const and = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n return false\n }\n\n vals = result\n }\n\n return vals\n }\n }\n}\n\n/**\n * Create a multiaddr matcher from the passed component matchers\n */\nexport function fmt (...matchers: Matcher[]): MultiaddrMatcher {\n function match (ma?: Multiaddr): Component[] | false {\n if (ma == null) {\n return false\n }\n\n let parts = ma.getComponents()\n\n for (const matcher of matchers) {\n const result = matcher.match(parts)\n\n if (result === false) {\n return false\n }\n\n parts = result\n }\n\n return parts\n }\n\n function matches (ma?: Multiaddr): boolean {\n const result = match(ma)\n\n return result !== false\n }\n\n function exactMatch (ma?: Multiaddr): boolean {\n const result = match(ma)\n\n if (result === false) {\n return false\n }\n\n return result.length === 0\n }\n\n return {\n matchers,\n matches,\n exactMatch\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\nimport { CODE_P2P, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_DNS, CODE_IP4, CODE_IP6, CODE_TCP, CODE_UDP, CODE_QUIC, CODE_QUIC_V1, CODE_WS, CODE_WSS, CODE_TLS, CODE_SNI, CODE_WEBRTC_DIRECT, CODE_CERTHASH, CODE_WEBTRANSPORT, CODE_P2P_CIRCUIT, CODE_WEBRTC, CODE_HTTP, CODE_UNIX, CODE_HTTPS, CODE_MEMORY, CODE_IP6ZONE, CODE_IPCIDR } from '@multiformats/multiaddr'\nimport { and, or, optional, fmt, code, value, not } from './utils.js'\nimport type { Multiaddr, Component } from '@multiformats/multiaddr'\n\n/**\n * A matcher accepts multiaddr components and either fails to match and returns\n * false or returns a sublist of unmatched components\n */\nexport interface Matcher {\n match(parts: Component[]): Component[] | false\n}\n\n/**\n * A MultiaddrMatcher allows interpreting a multiaddr as a certain type of\n * multiaddr\n */\nexport interface MultiaddrMatcher {\n /**\n * The matchers that make up this MultiaddrMatcher - useful if you want to\n * make your own custom matchers\n */\n matchers: Matcher[]\n\n /**\n * Returns true if the passed multiaddr can be treated as this type of\n * multiaddr\n */\n matches(ma?: Multiaddr): boolean\n\n /**\n * Returns true if the passed multiaddr terminates as this type of\n * multiaddr\n */\n exactMatch(ma?: Multiaddr): boolean\n}\n\n/**\n * Matches PeerId addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { PEER_ID } from '@multiformats/multiaddr-matcher'\n *\n * PEER_ID.matches(multiaddr('/p2p/Qmfoo')) // true\n * PEER_ID.matches(multiaddr('/ipfs/Qmfoo')) // true\n * ```\n */\nconst _PEER_ID = value(CODE_P2P)\n\nexport const PEER_ID = fmt(_PEER_ID)\n\n/**\n * DNS matchers\n */\nconst _DNS4 = value(CODE_DNS4)\nconst _DNS6 = value(CODE_DNS6)\nconst _DNSADDR = value(CODE_DNSADDR)\nconst _DNS = value(CODE_DNS)\n\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4, optional(value(CODE_P2P)))\n\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6, optional(value(CODE_P2P)))\n\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR, optional(value(CODE_P2P)))\n\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))\n\nconst _IP4 = and(\n value(CODE_IP4),\n optional(value(CODE_IPCIDR))\n)\nconst _IP6 = and(\n optional(value(CODE_IP6ZONE)),\n value(CODE_IP6),\n optional(value(CODE_IPCIDR))\n)\nconst _IP = or(_IP4, _IP6)\n\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR)\n\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))))\n\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4)\n\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6)\n\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP)\n\nconst _TCP = and(_IP_OR_DOMAIN, value(CODE_TCP))\nconst _UDP = and(_IP_OR_DOMAIN, value(CODE_UDP))\n\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(and(_TCP, optional(value(CODE_P2P))))\n\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP)\n\nconst _QUIC = and(_UDP, code(CODE_QUIC), optional(value(CODE_P2P)))\nconst _QUIC_V1 = and(_UDP, code(CODE_QUIC_V1), optional(value(CODE_P2P)))\n\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUIC_V1)\n\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC)\n\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC_V1 } from '@multiformats/multiaddr-matcher'\n *\n * QUIC_V1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUIC_V1 = fmt(_QUIC_V1)\n\nconst _WEB = or(\n _IP_OR_DOMAIN,\n _TCP,\n _UDP,\n _QUIC,\n _QUIC_V1\n)\n\nconst _WebSockets = or(\n and(_WEB, code(CODE_WS), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets)\n\nconst _WebSocketsSecure = or(\n and(_WEB, code(CODE_WSS), optional(value(CODE_P2P))),\n and(_WEB, code(CODE_TLS), optional(value(CODE_SNI)), code(CODE_WS), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure)\n\nconst _WebRTCDirect = and(_UDP, code(CODE_WEBRTC_DIRECT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)))\n\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect)\n\nconst _WebTransport = and(_QUIC_V1, code(CODE_WEBTRANSPORT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)))\n\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport)\n\nconst _P2P = or(\n _WebSockets,\n _WebSocketsSecure,\n and(_TCP, optional(value(CODE_P2P))),\n and(QUIC_V0_OR_V1, optional(value(CODE_P2P))),\n and(_IP_OR_DOMAIN, optional(value(CODE_P2P))),\n _WebRTCDirect,\n _WebTransport,\n value(CODE_P2P)\n)\n\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P)\n\nconst _Circuit = and(optional(_P2P), code(CODE_P2P_CIRCUIT), not(code(CODE_WEBRTC)), optional(value(CODE_P2P)))\n\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit)\n\nconst _WebRTC = or(\n and(_P2P, code(CODE_P2P_CIRCUIT), code(CODE_WEBRTC), optional(value(CODE_P2P))),\n and(_P2P, code(CODE_WEBRTC), optional(value(CODE_P2P))),\n and(code(CODE_WEBRTC), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC)\n\nconst _HTTP = or(\n and(_IP_OR_DOMAIN, value(CODE_TCP), code(CODE_HTTP), optional(value(CODE_P2P))),\n and(_IP_OR_DOMAIN, code(CODE_HTTP), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP)\n\nconst _HTTPS = and(_IP_OR_DOMAIN, or(\n and(value(CODE_TCP, '443'), code(CODE_HTTP)),\n and(value(CODE_TCP), code(CODE_HTTPS)),\n and(value(CODE_TCP), code(CODE_TLS), code(CODE_HTTP)),\n and(code(CODE_TLS), code(CODE_HTTP)),\n code(CODE_TLS),\n code(CODE_HTTPS)\n),\noptional(value(CODE_P2P))\n)\n\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS)\n\nconst _Memory = or(\n and(value(CODE_MEMORY), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches Memory addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Memory } from '@multiformats/multiaddr-matcher'\n *\n * Memory.matches(multiaddr('/memory/0xDEADBEEF')) // true\n * ```\n */\nexport const Memory = fmt(_Memory)\n\nconst _Unix = or(\n and(value(CODE_UNIX), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches Unix addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Unix } from '@multiformats/multiaddr-matcher'\n *\n * Unix.matches(multiaddr('/unix/%2Fpath%2Fto%2Funix.socket')) // true\n * ```\n */\nexport const Unix = fmt(_Unix)\n", "import { KEEP_ALIVE } from '@libp2p/interface'\n\nconst second = 1000\nconst minute = 60 * second\n\n/**\n * The maximum number of relay reservations the relay server will accept\n */\nexport const DEFAULT_MAX_RESERVATION_STORE_SIZE = 15\n\n/**\n * How often to check for reservation expiry\n */\nexport const DEFAULT_MAX_RESERVATION_TTL = 2 * 60 * minute\n\n/**\n * How many reservation attempts to make in parallel\n */\nexport const DEFAULT_RESERVATION_CONCURRENCY = 1\n\n/**\n * How long to wait for a reservation attempt to finish\n */\nexport const DEFAULT_RESERVATION_COMPLETION_TIMEOUT = 5_000\n\n/**\n * How long to let the reservation attempt queue to grow\n */\nexport const DEFAULT_MAX_RESERVATION_QUEUE_LENGTH = 100\n\nexport const RELAY_SOURCE_TAG = 'circuit-relay-source'\n\nexport const KEEP_ALIVE_TAG = `${KEEP_ALIVE}-circuit-relay`\n\n// circuit v2 connection limits\n// https://github.com/libp2p/go-libp2p/blob/master/p2p/protocol/circuitv2/relay/resources.go#L61-L66\n\n// 2 min is the default connection duration\nexport const DEFAULT_DURATION_LIMIT = 2 * minute\n\n// 128k is the default data limit\nexport const DEFAULT_DATA_LIMIT = BigInt(1 << 17)\n\n/**\n * The hop protocol\n */\nexport const RELAY_V2_HOP_CODEC = '/libp2p/circuit/relay/0.2.0/hop'\n\n/**\n * the stop protocol\n */\nexport const RELAY_V2_STOP_CODEC = '/libp2p/circuit/relay/0.2.0/stop'\n\n/**\n * Hop messages must be exchanged inside this timeout\n */\nexport const DEFAULT_HOP_TIMEOUT = 30 * second\n\n/**\n * How long to wait before starting to advertise the relay service\n */\nexport const DEFAULT_ADVERT_BOOT_DELAY = 30 * second\n\nexport const MAX_CONNECTIONS = 300\n\nexport const DEFAULT_DISCOVERY_FILTER_SIZE = 4096\nexport const DEFAULT_DISCOVERY_FILTER_ERROR_RATE = 0.001\n", "import { decodeMessage, encodeMessage, enumeration, MaxLengthError, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface HopMessage {\n type?: HopMessage.Type\n peer?: Peer\n reservation?: Reservation\n limit?: Limit\n status?: Status\n}\n\nexport namespace HopMessage {\n export enum Type {\n RESERVE = 'RESERVE',\n CONNECT = 'CONNECT',\n STATUS = 'STATUS'\n }\n\n enum __TypeValues {\n RESERVE = 0,\n CONNECT = 1,\n STATUS = 2\n }\n\n export namespace Type {\n export const codec = (): Codec<Type> => {\n return enumeration<Type>(__TypeValues)\n }\n }\n\n let _codec: Codec<HopMessage>\n\n export const codec = (): Codec<HopMessage> => {\n if (_codec == null) {\n _codec = message<HopMessage>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.type != null) {\n w.uint32(8)\n HopMessage.Type.codec().encode(obj.type, w)\n }\n\n if (obj.peer != null) {\n w.uint32(18)\n Peer.codec().encode(obj.peer, w)\n }\n\n if (obj.reservation != null) {\n w.uint32(26)\n Reservation.codec().encode(obj.reservation, w)\n }\n\n if (obj.limit != null) {\n w.uint32(34)\n Limit.codec().encode(obj.limit, w)\n }\n\n if (obj.status != null) {\n w.uint32(40)\n Status.codec().encode(obj.status, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.type = HopMessage.Type.codec().decode(reader)\n break\n }\n case 2: {\n obj.peer = Peer.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.peer\n })\n break\n }\n case 3: {\n obj.reservation = Reservation.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.reservation\n })\n break\n }\n case 4: {\n obj.limit = Limit.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.limit\n })\n break\n }\n case 5: {\n obj.status = Status.codec().decode(reader)\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<HopMessage>): Uint8Array => {\n return encodeMessage(obj, HopMessage.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<HopMessage>): HopMessage => {\n return decodeMessage(buf, HopMessage.codec(), opts)\n }\n}\n\nexport interface StopMessage {\n type?: StopMessage.Type\n peer?: Peer\n limit?: Limit\n status?: Status\n}\n\nexport namespace StopMessage {\n export enum Type {\n CONNECT = 'CONNECT',\n STATUS = 'STATUS'\n }\n\n enum __TypeValues {\n CONNECT = 0,\n STATUS = 1\n }\n\n export namespace Type {\n export const codec = (): Codec<Type> => {\n return enumeration<Type>(__TypeValues)\n }\n }\n\n let _codec: Codec<StopMessage>\n\n export const codec = (): Codec<StopMessage> => {\n if (_codec == null) {\n _codec = message<StopMessage>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.type != null) {\n w.uint32(8)\n StopMessage.Type.codec().encode(obj.type, w)\n }\n\n if (obj.peer != null) {\n w.uint32(18)\n Peer.codec().encode(obj.peer, w)\n }\n\n if (obj.limit != null) {\n w.uint32(26)\n Limit.codec().encode(obj.limit, w)\n }\n\n if (obj.status != null) {\n w.uint32(32)\n Status.codec().encode(obj.status, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.type = StopMessage.Type.codec().decode(reader)\n break\n }\n case 2: {\n obj.peer = Peer.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.peer\n })\n break\n }\n case 3: {\n obj.limit = Limit.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.limit\n })\n break\n }\n case 4: {\n obj.status = Status.codec().decode(reader)\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<StopMessage>): Uint8Array => {\n return encodeMessage(obj, StopMessage.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<StopMessage>): StopMessage => {\n return decodeMessage(buf, StopMessage.codec(), opts)\n }\n}\n\nexport interface Peer {\n id: Uint8Array\n addrs: Uint8Array[]\n}\n\nexport namespace Peer {\n let _codec: Codec<Peer>\n\n export const codec = (): Codec<Peer> => {\n if (_codec == null) {\n _codec = message<Peer>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.id != null && obj.id.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.id)\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n id: uint8ArrayAlloc(0),\n addrs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.id = reader.bytes()\n break\n }\n case 2: {\n if (opts.limits?.addrs != null && obj.addrs.length === opts.limits.addrs) {\n throw new MaxLengthError('Decode error - map field \"addrs\" had too many elements')\n }\n\n obj.addrs.push(reader.bytes())\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Peer>): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Peer>): Peer => {\n return decodeMessage(buf, Peer.codec(), opts)\n }\n}\n\nexport interface Reservation {\n expire: bigint\n addrs: Uint8Array[]\n voucher?: Envelope\n}\n\nexport namespace Reservation {\n let _codec: Codec<Reservation>\n\n export const codec = (): Codec<Reservation> => {\n if (_codec == null) {\n _codec = message<Reservation>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.expire != null && obj.expire !== 0n)) {\n w.uint32(8)\n w.uint64(obj.expire)\n }\n\n if (obj.addrs != null) {\n for (const value of obj.addrs) {\n w.uint32(18)\n w.bytes(value)\n }\n }\n\n if (obj.voucher != null) {\n w.uint32(26)\n Envelope.codec().encode(obj.voucher, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n expire: 0n,\n addrs: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.expire = reader.uint64()\n break\n }\n case 2: {\n if (opts.limits?.addrs != null && obj.addrs.length === opts.limits.addrs) {\n throw new MaxLengthError('Decode error - map field \"addrs\" had too many elements')\n }\n\n obj.addrs.push(reader.bytes())\n break\n }\n case 3: {\n obj.voucher = Envelope.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.voucher\n })\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Reservation>): Uint8Array => {\n return encodeMessage(obj, Reservation.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Reservation>): Reservation => {\n return decodeMessage(buf, Reservation.codec(), opts)\n }\n}\n\nexport interface Limit {\n duration?: number\n data?: bigint\n}\n\nexport namespace Limit {\n let _codec: Codec<Limit>\n\n export const codec = (): Codec<Limit> => {\n if (_codec == null) {\n _codec = message<Limit>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.duration != null) {\n w.uint32(8)\n w.uint32(obj.duration)\n }\n\n if (obj.data != null) {\n w.uint32(16)\n w.uint64(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.duration = reader.uint32()\n break\n }\n case 2: {\n obj.data = reader.uint64()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Limit>): Uint8Array => {\n return encodeMessage(obj, Limit.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Limit>): Limit => {\n return decodeMessage(buf, Limit.codec(), opts)\n }\n}\n\nexport enum Status {\n UNUSED = 'UNUSED',\n OK = 'OK',\n RESERVATION_REFUSED = 'RESERVATION_REFUSED',\n RESOURCE_LIMIT_EXCEEDED = 'RESOURCE_LIMIT_EXCEEDED',\n PERMISSION_DENIED = 'PERMISSION_DENIED',\n CONNECTION_FAILED = 'CONNECTION_FAILED',\n NO_RESERVATION = 'NO_RESERVATION',\n MALFORMED_MESSAGE = 'MALFORMED_MESSAGE',\n UNEXPECTED_MESSAGE = 'UNEXPECTED_MESSAGE'\n}\n\nenum __StatusValues {\n UNUSED = 0,\n OK = 100,\n RESERVATION_REFUSED = 200,\n RESOURCE_LIMIT_EXCEEDED = 201,\n PERMISSION_DENIED = 202,\n CONNECTION_FAILED = 203,\n NO_RESERVATION = 204,\n MALFORMED_MESSAGE = 400,\n UNEXPECTED_MESSAGE = 401\n}\n\nexport namespace Status {\n export const codec = (): Codec<Status> => {\n return enumeration<Status>(__StatusValues)\n }\n}\nexport interface ReservationVoucher {\n relay: Uint8Array\n peer: Uint8Array\n expiration: bigint\n}\n\nexport namespace ReservationVoucher {\n let _codec: Codec<ReservationVoucher>\n\n export const codec = (): Codec<ReservationVoucher> => {\n if (_codec == null) {\n _codec = message<ReservationVoucher>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.relay != null && obj.relay.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.relay)\n }\n\n if ((obj.peer != null && obj.peer.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.peer)\n }\n\n if ((obj.expiration != null && obj.expiration !== 0n)) {\n w.uint32(24)\n w.uint64(obj.expiration)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n relay: uint8ArrayAlloc(0),\n peer: uint8ArrayAlloc(0),\n expiration: 0n\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.relay = reader.bytes()\n break\n }\n case 2: {\n obj.peer = reader.bytes()\n break\n }\n case 3: {\n obj.expiration = reader.uint64()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<ReservationVoucher>): Uint8Array => {\n return encodeMessage(obj, ReservationVoucher.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<ReservationVoucher>): ReservationVoucher => {\n return decodeMessage(buf, ReservationVoucher.codec(), opts)\n }\n}\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload?: ReservationVoucher\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec<Envelope>\n\n export const codec = (): Codec<Envelope> => {\n if (_codec == null) {\n _codec = message<Envelope>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if (obj.payload != null) {\n w.uint32(26)\n ReservationVoucher.codec().encode(obj.payload, w)\n }\n\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n publicKey: uint8ArrayAlloc(0),\n payloadType: uint8ArrayAlloc(0),\n signature: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.publicKey = reader.bytes()\n break\n }\n case 2: {\n obj.payloadType = reader.bytes()\n break\n }\n case 3: {\n obj.payload = ReservationVoucher.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.payload\n })\n break\n }\n case 5: {\n obj.signature = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Envelope>): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Envelope>): Envelope => {\n return decodeMessage(buf, Envelope.codec(), opts)\n }\n}\n", "/**\n * A transfer limit was hit\n */\nexport class TransferLimitError extends Error {\n constructor (message = 'Transfer limit error') {\n super(message)\n this.name = 'TransferLimitError'\n }\n}\n\n/**\n * A duration limit was hit\n */\nexport class DurationLimitError extends Error {\n constructor (message = 'Duration limit error') {\n super(message)\n this.name = 'DurationLimitError'\n }\n}\n\n/**\n * There were enough relay reservations already\n */\nexport class HadEnoughRelaysError extends Error {\n static name: string = 'HadEnoughRelaysError'\n name: string = 'HadEnoughRelaysError'\n}\n\n/**\n * An attempt to open a relayed connection over a relayed connection was made\n */\nexport class DoubleRelayError extends Error {\n static name: string = 'DoubleRelayError'\n name: string = 'DoubleRelayError'\n}\n\n/**\n * An attempt to make a reservation on a relay was made while the reservation\n * queue was full\n */\nexport class RelayQueueFullError extends Error {\n static name: string = 'RelayQueueFullError'\n name: string = 'RelayQueueFullError'\n}\n", "import { setMaxListeners } from '@libp2p/interface'\nimport { pipe } from '@libp2p/utils'\nimport { CODE_P2P_CIRCUIT } from '@multiformats/multiaddr'\nimport { P2P } from '@multiformats/multiaddr-matcher'\nimport { fmt, code, and } from '@multiformats/multiaddr-matcher/utils'\nimport { anySignal } from 'any-signal'\nimport { CID } from 'multiformats/cid'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { DurationLimitError, TransferLimitError } from './errors.js'\nimport type { RelayReservation } from './index.js'\nimport type { Limit } from './pb/index.js'\nimport type { ConnectionLimits, LoggerOptions, Stream, MessageStream, StreamMessageEvent } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nfunction countStreamBytes (source: MessageStream, limit: { remaining: bigint }, options: LoggerOptions): void {\n const limitBytes = limit.remaining\n\n const abortIfStreamByteLimitExceeded = (evt: StreamMessageEvent): void => {\n const len = BigInt(evt.data.byteLength)\n limit.remaining -= len\n\n if (limit.remaining < 0) {\n source.abort(new TransferLimitError(`data limit of ${limitBytes} bytes exceeded`))\n }\n }\n source.addEventListener('message', abortIfStreamByteLimitExceeded)\n}\n\nexport function createLimitedRelay (src: Stream, dst: Stream, abortSignal: AbortSignal, reservation: RelayReservation, options: LoggerOptions): void {\n function abortStreams (err: Error): void {\n src.abort(err)\n dst.abort(err)\n }\n\n // combine shutdown signal and reservation expiry signal\n const signals = [abortSignal, reservation.signal]\n\n if (reservation.limit?.duration != null) {\n options.log('limiting relayed connection duration to %dms', reservation.limit.duration)\n const durationSignal = AbortSignal.timeout(reservation.limit.duration)\n setMaxListeners(Infinity, durationSignal)\n signals.push(durationSignal)\n }\n\n const signal = anySignal(signals)\n setMaxListeners(Infinity, signal)\n\n let dataLimit: { remaining: bigint } | undefined\n\n if (reservation.limit?.data != null) {\n dataLimit = {\n remaining: reservation.limit.data\n }\n }\n\n const onAbort = (): void => {\n let err: Error\n\n if (abortSignal.aborted) {\n err = abortSignal.reason\n } else {\n err = new DurationLimitError(`duration limit of ${reservation.limit?.duration} ms exceeded`)\n }\n\n abortStreams(err)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n\n if (dataLimit != null) {\n countStreamBytes(dst, dataLimit, options)\n countStreamBytes(src, dataLimit, options)\n }\n\n // join the streams together\n pipe(\n src, dst, src\n )\n .catch(err => {\n abortStreams(err)\n })\n .finally(() => {\n signal.clear()\n })\n}\n\n/**\n * Convert a namespace string into a cid\n */\nexport async function namespaceToCid (namespace: string): Promise<CID> {\n const bytes = new TextEncoder().encode(namespace)\n const hash = await sha256.digest(bytes)\n\n return CID.createV0(hash)\n}\n\n/**\n * returns number of ms between now and expiration time\n */\nexport function getExpirationMilliseconds (expireTimeSeconds: bigint): number {\n const expireTimeMillis = expireTimeSeconds * BigInt(1000)\n const currentTime = new Date().getTime()\n\n // downcast to number to use with setTimeout\n return Number(expireTimeMillis - BigInt(currentTime))\n}\n\nexport class LimitTracker {\n private readonly expires?: number\n private bytes?: bigint\n\n constructor (limits?: Limit) {\n if (limits?.duration != null && limits?.duration !== 0) {\n this.expires = Date.now() + (limits.duration * 1000)\n }\n\n this.bytes = limits?.data\n\n if (this.bytes === 0n) {\n this.bytes = undefined\n }\n\n this.onData = this.onData.bind(this)\n }\n\n onData (buf: Uint8ArrayList | Uint8Array): void {\n if (this.bytes == null) {\n return\n }\n\n this.bytes -= BigInt(buf.byteLength)\n\n if (this.bytes < 0n) {\n this.bytes = 0n\n }\n }\n\n getLimits (): ConnectionLimits | undefined {\n if (this.expires == null && this.bytes == null) {\n return\n }\n\n const output = {}\n\n if (this.bytes != null) {\n const self = this\n\n Object.defineProperty(output, 'bytes', {\n get () {\n return self.bytes\n }\n })\n }\n\n if (this.expires != null) {\n const self = this\n\n Object.defineProperty(output, 'seconds', {\n get () {\n return Math.round(((self.expires ?? 0) - Date.now()) / 1000)\n }\n })\n }\n\n return output\n }\n}\n\n/**\n * A custom matcher that tells us to listen on a particular relay\n */\nexport const CircuitListen = fmt(\n and(P2P.matchers[0], code(CODE_P2P_CIRCUIT))\n)\n\n/**\n * A custom matcher that tells us to discover available relays\n */\nexport const CircuitSearch = fmt(\n code(CODE_P2P_CIRCUIT)\n)\n", "import { peerIdFromMultihash } from '@libp2p/peer-id'\nimport { base58btc } from 'multiformats/bases/base58'\nimport * as Digest from 'multiformats/hashes/digest'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable <T, R> (iter: IterableIterator<T>, map: (val: T) => R): IterableIterator<R> {\n const iterator: IterableIterator<R> = {\n [Symbol.iterator]: () => {\n return iterator\n },\n next: () => {\n const next = iter.next()\n const val = next.value\n\n if (next.done === true || val == null) {\n const result: IteratorReturnResult<any> = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n return {\n done: false,\n value: map(val)\n }\n }\n }\n\n return iterator\n}\n\nexport function peerIdFromString (str: string): PeerId {\n const multihash = Digest.decode(base58btc.decode(`z${str}`))\n return peerIdFromMultihash(multihash)\n}\n", "import { mapIterable } from './util.js'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap<string>()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap <T> {\n private readonly map: Map<string, { key: PeerId, value: T }>\n\n constructor (map?: PeerMap<T>) {\n this.map = new Map()\n\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), { key, value })\n }\n }\n }\n\n [Symbol.iterator] (): IterableIterator<[PeerId, T]> {\n return this.entries()\n }\n\n clear (): void {\n this.map.clear()\n }\n\n delete (peer: PeerId): boolean {\n return this.map.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, T]> {\n return mapIterable<[string, { key: PeerId, value: T }], [PeerId, T]>(\n this.map.entries(),\n (val) => {\n return [val[1].key, val[1].value]\n }\n )\n }\n\n forEach (fn: (value: T, key: PeerId, map: PeerMap<T>) => void): void {\n this.map.forEach((value, key) => {\n fn(value.value, value.key, this)\n })\n }\n\n get (peer: PeerId): T | undefined {\n return this.map.get(peer.toString())?.value\n }\n\n has (peer: PeerId): boolean {\n return this.map.has(peer.toString())\n }\n\n set (peer: PeerId, value: T): void {\n this.map.set(peer.toString(), { key: peer, value })\n }\n\n keys (): IterableIterator<PeerId> {\n return mapIterable<{ key: PeerId, value: T }, PeerId>(\n this.map.values(),\n (val) => {\n return val.key\n }\n )\n }\n\n values (): IterableIterator<T> {\n return mapIterable(this.map.values(), (val) => val.value)\n }\n\n get size (): number {\n return this.map.size\n }\n}\n\nexport function peerMap <T> (): PeerMap<T> {\n return new PeerMap<T>()\n}\n", "import { createScalableCuckooFilter } from '@libp2p/utils'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Filter } from '@libp2p/utils'\n\n/**\n * Uses a Cuckoo filter to implement a mechanism for deduplicating PeerIds in a\n * way that uses a smaller amount of memory than a PeerSet.\n */\nexport class PeerFilter {\n private readonly filter: Filter\n\n constructor (size: number, errorRate?: number) {\n this.filter = createScalableCuckooFilter(size, errorRate)\n }\n\n has (peerId: PeerId): boolean {\n return this.filter.has(peerId.toMultihash().bytes)\n }\n\n add (peerId: PeerId): void {\n this.filter.add(peerId.toMultihash().bytes)\n }\n\n remove (peerId: PeerId): void {\n this.filter.remove?.(peerId.toMultihash().bytes)\n }\n}\n\n/**\n * Create and return a PeerFilter. This can be used by topologies to prevent\n * them receiving duplicate notifications for a peer that connects repeatedly.\n *\n * @example\n *\n * ```TypeScript\n * import { peerFilter } from '@libp2p/peer-collections'\n * import type { Registrar } from '@libp2p/interface-internal'\n *\n * const registrar: Registrar\n *\n * registrar.register('/my/protocol/1.0.0', {\n * filter: peerFilter(),\n * onConnect: (peerId) => {\n * // will only be invoked for a given peerId once\n * }\n * })\n * ```\n *\n * @param size - The maximum number of peers expected to be added to the filter\n * @param errorRate - The acceptable error rate\n */\nexport function peerFilter (size: number, errorRate: number = 0.001): PeerFilter {\n return new PeerFilter(size, errorRate)\n}\n", "import { PeerMap } from './map.js'\nimport type { Metric, Metrics, PeerId } from '@libp2p/interface'\n\nexport interface TrackedPeerMapInit {\n name: string\n metrics?: Metrics\n}\n\nclass TrackedPeerMap<V> extends PeerMap<V> {\n private readonly metric: Metric\n\n constructor (init: Required<TrackedPeerMapInit>) {\n super()\n\n const { name, metrics } = init\n\n this.metric = metrics.registerMetric(name)\n this.updateComponentMetric()\n }\n\n set (key: PeerId, value: V): this {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: PeerId): boolean {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear (): void {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric (): void {\n this.metric.update(this.size)\n }\n}\n\n/**\n * Creates a PeerMap that reports it's size to the libp2p Metrics service\n *\n * @example\n *\n * ```Typescript\n * import { trackedPeerMap } from '@libp2p/peer-collections'\n * import { createLibp2p } from 'libp2p'\n *\n * const libp2p = await createLibp2p()\n *\n * const list = trackedPeerMap({ name: 'my_metric_name', metrics: libp2p.metrics })\n * map.set(peerId, 'value')\n * ```\n */\nexport function trackedPeerMap <V> (config: TrackedPeerMapInit): PeerMap<V> {\n const { name, metrics } = config\n let map: PeerMap<V>\n\n if (metrics != null) {\n map = new TrackedPeerMap<V>({ name, metrics })\n } else {\n map = new PeerMap<V>()\n }\n\n return map\n}\n", "/**\n * @packageDocumentation\n *\n * This module exports a `retimeableSignal` function that returns an\n * `AbortSignal` that fires an \"abort\" event after a specified number of ms.\n *\n * It has been augmented with two additional methods `reset` and `clear` which\n * change the timeout time and prevent it from firing entirely.\n *\n * @example\n *\n * ```TypeScript\n * import { retimeableSignal } from 'retimeable-signal'\n *\n * const signal = retimeableSignal(100)\n *\n * //... time passes, reset timeout to now + 100ms\n * signal.reset(100)\n *\n * // stop the signal from aborting at all\n * signal.clear()\n * ```\n *\n * ## Prior art\n *\n * This is module is inspired by the [retimer](https://www.npmjs.com/package/retimer)\n * module except that uses `setTimeout` which can cause a Node.js process to\n * stay open, this uses `AbortSignal.timeout` which does not.\n */\n\n/**\n * An abort error class that extends error\n */\nclass AbortError extends Error {\n public type: string\n public code: string | string\n\n constructor (message?: string, code?: string, name?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = name ?? 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RetimerSignalOptions {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * The name for the error thrown if the signal aborts\n */\n errorName?: string\n}\n\n/**\n * An extension to the `AbortSignal` interface that allows resetting the timer\n * after which the signal will fire it's \"abort\" event.\n */\nexport interface RetimeableAbortSignal extends AbortSignal {\n /**\n * Reset the timer. If `ms` is specified, the timer will fire this many ms in\n * the future, otherwise it will fire according to the `ms` arg originally\n * passed to `retimerSignal`.\n */\n reset(ms?: number): void\n\n /**\n * Clear the timer, the \"abort\" event will no longer be fired\n */\n clear(): void\n}\n\n/**\n * Return an AbortSignal that times out after a specified number of ms with an\n * internal timer that can be reset to fire further into the future or cleared\n * entirely\n */\nexport function retimeableSignal (ms: number, opts?: RetimerSignalOptions): RetimeableAbortSignal {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName)\n const controller = new AbortController()\n const abortHandler = (): void => {\n controller.abort(error)\n }\n\n let signal: AbortSignal | undefined = AbortSignal.timeout(ms)\n signal.addEventListener('abort', abortHandler)\n\n const retimerSignal = controller.signal as any\n retimerSignal.reset = (newMs?: number): void => {\n signal?.removeEventListener('abort', abortHandler)\n signal = AbortSignal.timeout(newMs ?? ms)\n signal.addEventListener('abort', () => {\n controller.abort(error)\n })\n }\n retimerSignal.clear = (): void => {\n signal?.removeEventListener('abort', abortHandler)\n signal = undefined\n }\n\n return retimerSignal satisfies RetimeableAbortSignal\n}\n", "import { trackedPeerMap } from '@libp2p/peer-collections'\nimport { retimeableSignal } from 'retimeable-signal'\nimport { DEFAULT_DATA_LIMIT, DEFAULT_DURATION_LIMIT, DEFAULT_MAX_RESERVATION_STORE_SIZE, DEFAULT_MAX_RESERVATION_TTL } from '../constants.js'\nimport { Status } from '../pb/index.js'\nimport type { RelayReservation, ServerReservationStoreInit } from '../index.js'\nimport type { Limit } from '../pb/index.js'\nimport type { ComponentLogger, Logger, Metrics, PeerId } from '@libp2p/interface'\nimport type { PeerMap } from '@libp2p/peer-collections'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport type ReservationStatus = Status.OK | Status.PERMISSION_DENIED | Status.RESERVATION_REFUSED\n\nexport interface ReservationStoreComponents {\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport class ReservationStore {\n public readonly reservations: PeerMap<RelayReservation>\n private readonly maxReservations: number\n private readonly applyDefaultLimit: boolean\n private readonly reservationTtl: number\n private readonly defaultDurationLimit: number\n private readonly defaultDataLimit: bigint\n private readonly log: Logger\n\n constructor (components: ReservationStoreComponents, init: ServerReservationStoreInit = {}) {\n this.log = components.logger.forComponent('libp2p:circuit-relay:server:reservation-store')\n this.maxReservations = init.maxReservations ?? DEFAULT_MAX_RESERVATION_STORE_SIZE\n this.applyDefaultLimit = init.applyDefaultLimit !== false\n this.reservationTtl = init.reservationTtl ?? DEFAULT_MAX_RESERVATION_TTL\n this.defaultDurationLimit = init.defaultDurationLimit ?? DEFAULT_DURATION_LIMIT\n this.defaultDataLimit = init.defaultDataLimit ?? DEFAULT_DATA_LIMIT\n\n this.reservations = trackedPeerMap<RelayReservation>({\n metrics: components.metrics,\n name: 'libp2p_circuit_relay_server_reservations_total'\n })\n }\n\n reserve (peer: PeerId, addr: Multiaddr, limit?: Limit): { status: ReservationStatus, expire?: number } {\n let reservation = this.reservations.get(peer)\n\n if (this.reservations.size >= this.maxReservations && reservation == null) {\n return { status: Status.RESERVATION_REFUSED }\n }\n\n const expiry = new Date(Date.now() + this.reservationTtl)\n let checkedLimit: Limit | undefined\n\n if (this.applyDefaultLimit) {\n checkedLimit = limit ?? {\n data: this.defaultDataLimit,\n duration: this.defaultDurationLimit\n }\n }\n\n if (reservation != null) {\n this.log('refreshing reservation for client %p', peer)\n reservation.signal.reset(this.reservationTtl)\n } else {\n this.log('creating new reservation for client %p', peer)\n reservation = {\n addr,\n expiry,\n limit: checkedLimit,\n signal: retimeableSignal(this.reservationTtl)\n }\n }\n\n this.reservations.set(peer, reservation)\n\n reservation.signal.addEventListener('abort', () => {\n this.reservations.delete(peer)\n })\n\n // return expiry time in seconds\n return { status: Status.OK, expire: Math.round(expiry.getTime() / 1000) }\n }\n\n removeReservation (peer: PeerId): void {\n this.reservations.delete(peer)\n }\n\n get (peer: PeerId): RelayReservation | undefined {\n return this.reservations.get(peer)\n }\n\n clear (): void {\n this.reservations.clear()\n }\n}\n", "import { ReservationVoucher } from '../pb/index.js'\nimport type { PeerId, Record } from '@libp2p/interface'\n\nexport interface ReservationVoucherOptions {\n relay: PeerId\n peer: PeerId\n expiration: bigint\n}\n\nexport class ReservationVoucherRecord implements Record {\n public readonly domain = 'libp2p-relay-rsvp'\n public readonly codec = new Uint8Array([0x03, 0x02])\n\n private readonly relay: PeerId\n private readonly peer: PeerId\n private readonly expiration: bigint\n\n constructor ({ relay, peer, expiration }: ReservationVoucherOptions) {\n this.relay = relay\n this.peer = peer\n this.expiration = expiration\n }\n\n marshal (): Uint8Array {\n return ReservationVoucher.encode({\n relay: this.relay.toMultihash().bytes,\n peer: this.peer.toMultihash().bytes,\n expiration: BigInt(this.expiration)\n })\n }\n\n equals (other: Record): boolean {\n if (!(other instanceof ReservationVoucherRecord)) {\n return false\n }\n if (!this.peer.equals(other.peer)) {\n return false\n }\n\n if (!this.relay.equals(other.relay)) {\n return false\n }\n\n if (this.expiration !== other.expiration) {\n return false\n }\n\n return true\n }\n}\n", "import { publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { peerIdFromMultihash } from '@libp2p/peer-id'\nimport { RecordEnvelope } from '@libp2p/peer-record'\nimport { pbStream } from '@libp2p/utils'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { Circuit } from '@multiformats/multiaddr-matcher'\nimport { TypedEventEmitter, setMaxListeners } from 'main-event'\nimport * as Digest from 'multiformats/hashes/digest'\nimport {\n DEFAULT_HOP_TIMEOUT,\n MAX_CONNECTIONS,\n RELAY_SOURCE_TAG,\n RELAY_V2_HOP_CODEC,\n RELAY_V2_STOP_CODEC\n} from '../constants.js'\nimport { HopMessage, Status, StopMessage } from '../pb/index.js'\nimport { createLimitedRelay } from '../utils.js'\nimport { ReservationStore } from './reservation-store.js'\nimport { ReservationVoucherRecord } from './reservation-voucher.js'\nimport type { CircuitRelayServerComponents, CircuitRelayServerInit, CircuitRelayService, RelayReservation } from '../index.js'\nimport type { Reservation } from '../pb/index.js'\nimport type { Logger, Connection, Stream, PeerId, Startable, AbortOptions } from '@libp2p/interface'\nimport type { PeerMap } from '@libp2p/peer-collections'\nimport type { ProtobufStream } from '@libp2p/utils'\n\nexport interface HopProtocolOptions {\n connection: Connection\n request: HopMessage\n stream: ProtobufStream<Stream>\n}\n\nexport interface StopOptions {\n connection: Connection\n request: StopMessage\n}\n\nexport interface RelayServerEvents {\n 'relay:reservation': CustomEvent<RelayReservation>\n 'relay:advert:success': CustomEvent<unknown>\n 'relay:advert:error': CustomEvent<Error>\n}\n\nconst defaults = {\n maxOutboundStopStreams: MAX_CONNECTIONS\n}\n\nexport class CircuitRelayServer extends TypedEventEmitter<RelayServerEvents> implements Startable, CircuitRelayService {\n private readonly components: CircuitRelayServerComponents\n private readonly reservationStore: ReservationStore\n private started: boolean\n private readonly hopTimeout: number\n private readonly shutdownController: AbortController\n private readonly maxInboundHopStreams?: number\n private readonly maxOutboundHopStreams?: number\n private readonly maxOutboundStopStreams: number\n private readonly log: Logger\n\n /**\n * Creates an instance of Relay\n */\n constructor (components: CircuitRelayServerComponents, init: CircuitRelayServerInit = {}) {\n super()\n\n this.log = components.logger.forComponent('libp2p:circuit-relay:server')\n this.components = components\n this.started = false\n this.hopTimeout = init?.hopTimeout ?? DEFAULT_HOP_TIMEOUT\n this.maxInboundHopStreams = init.maxInboundHopStreams\n this.maxOutboundHopStreams = init.maxOutboundHopStreams\n this.maxOutboundStopStreams = init.maxOutboundStopStreams ?? defaults.maxOutboundStopStreams\n this.reservationStore = new ReservationStore(components, init.reservations)\n\n this.shutdownController = new AbortController()\n setMaxListeners(Infinity, this.shutdownController.signal)\n\n this.onHop = this.onHop.bind(this)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/circuit-relay-v2-server'\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * Start Relay service\n */\n async start (): Promise<void> {\n if (this.started) {\n return\n }\n\n await this.components.registrar.handle(RELAY_V2_HOP_CODEC, this.onHop, {\n maxInboundStreams: this.maxInboundHopStreams,\n maxOutboundStreams: this.maxOutboundHopStreams,\n runOnLimitedConnection: true\n })\n\n this.started = true\n }\n\n /**\n * Stop Relay service\n */\n async stop (): Promise<void> {\n this.reservationStore.clear()\n this.shutdownController.abort()\n await this.components.registrar.unhandle(RELAY_V2_HOP_CODEC)\n\n this.started = false\n }\n\n async onHop (stream: Stream, connection: Connection): Promise<void> {\n this.log('received circuit v2 hop protocol stream from %p', connection.remotePeer)\n\n const signal = AbortSignal.timeout(this.hopTimeout)\n setMaxListeners(Infinity, signal)\n\n const options = {\n signal\n }\n const pbstr = pbStream(stream)\n\n try {\n const request: HopMessage = await pbstr.pb(HopMessage).read(options)\n\n if (request?.type == null) {\n throw new Error('request was invalid, could not read from stream')\n }\n\n this.log('received', request.type)\n\n await this.handleHopProtocol({\n connection,\n stream: pbstr,\n request\n }, options)\n } catch (err: any) {\n this.log.error('error while handling hop - %e', err)\n await pbstr.pb(HopMessage).write({\n type: HopMessage.Type.STATUS,\n status: Status.MALFORMED_MESSAGE\n }, options)\n stream.abort(err)\n }\n }\n\n async handleHopProtocol ({ stream, request, connection }: HopProtocolOptions, options: AbortOptions): Promise<void> {\n this.log('received hop message')\n switch (request.type) {\n case HopMessage.Type.RESERVE: await this.handleReserve({ stream, request, connection }, options); break\n case HopMessage.Type.CONNECT: await this.handleConnect({ stream, request, connection }, options); break\n default: {\n this.log.error('invalid hop request type %s via peer %p', request.type, connection.remotePeer)\n await stream.pb(HopMessage).write({ type: HopMessage.Type.STATUS, status: Status.UNEXPECTED_MESSAGE })\n }\n }\n }\n\n async handleReserve ({ stream, connection }: HopProtocolOptions, options: AbortOptions): Promise<void> {\n const hopstr = stream.pb(HopMessage)\n this.log('hop reserve request from %p', connection.remotePeer)\n\n if (Circuit.exactMatch(connection.remoteAddr)) {\n this.log.error('relay reservation over circuit connection denied for peer: %p', connection.remotePeer)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED }, options)\n return\n }\n\n if ((await this.components.connectionGater.denyInboundRelayReservation?.(connection.remotePeer)) === true) {\n this.log.error('reservation for %p denied by connection gater', connection.remotePeer)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED }, options)\n return\n }\n\n const result = this.reservationStore.reserve(connection.remotePeer, connection.remoteAddr)\n\n try {\n if (result.status !== Status.OK) {\n await hopstr.write({ type: HopMessage.Type.STATUS, status: result.status }, options)\n return\n }\n\n // tag relay target peer\n // result.expire is non-null if `ReservationStore.reserve` returns with status == OK\n if (result.expire != null) {\n const ttl = (result.expire * 1000) - Date.now()\n await this.components.peerStore.merge(connection.remotePeer, {\n tags: {\n [RELAY_SOURCE_TAG]: { value: 1, ttl }\n }\n }, options)\n }\n\n await hopstr.write({\n type: HopMessage.Type.STATUS,\n status: Status.OK,\n reservation: await this.makeReservation(connection.remotePeer, BigInt(result.expire ?? 0)),\n limit: this.reservationStore.get(connection.remotePeer)?.limit\n }, options)\n this.log('sent confirmation response to %s', connection.remotePeer)\n\n // close writable end of stream\n await hopstr.unwrap().unwrap().close(options)\n } catch (err) {\n this.log.error('failed to send confirmation response to %p - %e', connection.remotePeer, err)\n this.reservationStore.removeReservation(connection.remotePeer)\n\n try {\n await this.components.peerStore.merge(connection.remotePeer, {\n tags: {\n [RELAY_SOURCE_TAG]: undefined\n }\n }, options)\n } catch (err) {\n this.log.error('failed to untag relay source peer %p - %e', connection.remotePeer, err)\n }\n }\n }\n\n async makeReservation (\n remotePeer: PeerId,\n expire: bigint\n ): Promise<Reservation> {\n const addrs = []\n\n for (const relayAddr of this.components.addressManager.getAddresses()) {\n if (relayAddr.toString().includes('/p2p-circuit')) {\n continue\n }\n\n addrs.push(relayAddr.bytes)\n }\n\n const envelope = await RecordEnvelope.seal(new ReservationVoucherRecord({\n peer: remotePeer,\n relay: this.components.peerId,\n expiration: expire\n }), this.components.privateKey)\n\n return {\n addrs,\n expire,\n voucher: {\n publicKey: publicKeyToProtobuf(envelope.publicKey),\n payloadType: envelope.payloadType,\n payload: {\n peer: remotePeer.toMultihash().bytes,\n relay: this.components.peerId.toMultihash().bytes,\n expiration: expire\n },\n signature: envelope.signature\n }\n }\n }\n\n async handleConnect ({ stream, request, connection }: HopProtocolOptions, options: AbortOptions): Promise<void> {\n const hopstr = stream.pb(HopMessage)\n\n if (Circuit.matches(connection.remoteAddr)) {\n this.log.error('relay reservation over circuit connection denied for peer: %p', connection.remotePeer)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED }, options)\n return\n }\n\n this.log('hop connect request from %p', connection.remotePeer)\n\n let dstPeer: PeerId\n\n try {\n if (request.peer == null) {\n this.log.error('no peer info in hop connect request')\n throw new Error('no peer info in request')\n }\n\n request.peer.addrs.forEach(multiaddr)\n dstPeer = peerIdFromMultihash(Digest.decode(request.peer.id))\n } catch (err) {\n this.log.error('invalid hop connect request via peer %p - %e', connection.remotePeer, err)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.MALFORMED_MESSAGE }, options)\n return\n }\n\n const reservation = this.reservationStore.get(dstPeer)\n\n if (reservation == null) {\n this.log.error('hop connect denied for destination peer %p not having a reservation for %p with status %s', dstPeer, connection.remotePeer, Status.NO_RESERVATION)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.NO_RESERVATION }, options)\n return\n }\n\n if ((await this.components.connectionGater.denyOutboundRelayedConnection?.(connection.remotePeer, dstPeer)) === true) {\n this.log.error('hop connect for %p to %p denied by connection gater', connection.remotePeer, dstPeer)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED }, options)\n return\n }\n\n const connections = this.components.connectionManager.getConnections(dstPeer)\n\n if (connections.length === 0) {\n this.log('hop connect denied for destination peer %p not having a connection for %p as there is no destination connection', dstPeer, connection.remotePeer)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.NO_RESERVATION }, options)\n return\n }\n\n const destinationConnection = connections[0]\n\n const destinationStream = await this.stopHop({\n connection: destinationConnection,\n request: {\n type: StopMessage.Type.CONNECT,\n peer: {\n id: connection.remotePeer.toMultihash().bytes,\n addrs: []\n },\n limit: reservation?.limit\n }\n }, options)\n\n if (destinationStream == null) {\n this.log.error('failed to open stream to destination peer %p', destinationConnection?.remotePeer)\n await hopstr.write({ type: HopMessage.Type.STATUS, status: Status.CONNECTION_FAILED }, options)\n return\n }\n\n await hopstr.write({\n type: HopMessage.Type.STATUS,\n status: Status.OK,\n limit: reservation?.limit\n }, options)\n\n this.log('connection from %p to %p established - merging streams', connection.remotePeer, dstPeer)\n\n // Short circuit the two streams to create the relayed connection\n createLimitedRelay(stream.unwrap(), destinationStream, this.shutdownController.signal, reservation, {\n log: this.log\n })\n }\n\n /**\n * Send a STOP request to the target peer that the dialing peer wants to contact\n */\n async stopHop ({ connection, request }: StopOptions, options: AbortOptions): Promise<Stream | undefined> {\n this.log('starting circuit relay v2 stop request to %s', connection.remotePeer)\n const stream = await connection.newStream(RELAY_V2_STOP_CODEC, {\n maxOutboundStreams: this.maxOutboundStopStreams,\n runOnLimitedConnection: true,\n ...options\n })\n const pbstr = pbStream(stream)\n const stopstr = pbstr.pb(StopMessage)\n await stopstr.write(request, options)\n let response\n\n try {\n response = await stopstr.read(options)\n } catch (err) {\n this.log.error('error parsing stop message response from %p - %e', connection.remotePeer, err)\n }\n\n if (response == null) {\n this.log.error('could not read response from %p', connection.remotePeer)\n await stream.close(options)\n return\n }\n\n if (response.status === Status.OK) {\n this.log('stop request to %p was successful', connection.remotePeer)\n return pbstr.unwrap()\n }\n\n this.log('stop request failed with code %d', response.status)\n await stream.close(options)\n }\n\n get reservations (): PeerMap<RelayReservation> {\n return this.reservationStore.reservations\n }\n}\n", "/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent<T extends string = any, D = unknown> {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent<D = unknown, T extends string = any> extends Event implements ProgressEvent<T, D> {\n public type: T\n public detail: D\n\n constructor (type: T, detail?: D) {\n super(type)\n\n this.type = type\n // @ts-expect-error detail may be undefined\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions<MyOperationProgressEvents> {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions<Event extends ProgressEvent = any> {\n onProgress?: (evt: Event) => void\n}\n", "import { PeerQueue } from '@libp2p/utils'\nimport { anySignal } from 'any-signal'\nimport { TypedEventEmitter, setMaxListeners } from 'main-event'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport {\n RELAY_V2_HOP_CODEC\n} from '../constants.js'\nimport type { RelayDiscoveryComponents, RelayDiscoveryEvents, RelayDiscoveryInit } from '../index.ts'\nimport type { Logger, Peer, PeerId, PeerInfo, Startable, TopologyFilter } from '@libp2p/interface'\n\n/**\n * ReservationManager automatically makes a circuit v2 reservation on any connected\n * peers that support the circuit v2 HOP protocol.\n */\nexport class RelayDiscovery extends TypedEventEmitter<RelayDiscoveryEvents> implements Startable {\n private readonly components: RelayDiscoveryComponents\n private started: boolean\n private running: boolean\n private topologyId?: string\n private readonly log: Logger\n private discoveryController: AbortController\n private readonly filter?: TopologyFilter\n private queue?: PeerQueue\n\n constructor (components: RelayDiscoveryComponents, init: RelayDiscoveryInit = {}) {\n super()\n\n this.log = components.logger.forComponent('libp2p:circuit-relay:discover-relays')\n this.components = components\n this.started = false\n this.running = false\n this.filter = init.filter\n this.discoveryController = new AbortController()\n setMaxListeners(Infinity, this.discoveryController.signal)\n this.dialPeer = this.dialPeer.bind(this)\n this.onPeer = this.onPeer.bind(this)\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n // register a topology listener for when new peers are encountered\n // that support the hop protocol\n this.topologyId = await this.components.registrar.register(RELAY_V2_HOP_CODEC, {\n filter: this.filter,\n onConnect: (peerId) => {\n this.log.trace('discovered relay %p queue (length: %d, active %d)', peerId, this.queue?.size, this.queue?.running)\n this.safeDispatchEvent('relay:discover', { detail: peerId })\n }\n })\n\n this.started = true\n }\n\n stop (): void {\n if (this.topologyId != null) {\n this.components.registrar.unregister(this.topologyId)\n }\n\n if (this.running) {\n this.stopDiscovery()\n }\n\n this.started = false\n }\n\n /**\n * Try to listen on available hop relay connections.\n * The following order will happen while we do not have enough relays:\n *\n * 1. Check the metadata store for known relays, try to listen on the ones we are already connected to\n * 2. Dial and try to listen on the peers we know that support hop but are not connected\n * 3. Search the network - this requires a peer routing implementation to be configured but will fail gracefully\n * 4. Dial any peers discovered - this covers when no peer routing implementation has been configured but some peer discovery mechanism is also present\n */\n startDiscovery (): void {\n if (this.running) {\n return\n }\n\n this.log('start discovery')\n this.running = true\n this.discoveryController = new AbortController()\n setMaxListeners(Infinity, this.discoveryController.signal)\n\n // dial any peer we discover\n this.components.events.addEventListener('peer:discovery', this.onPeer)\n\n Promise.resolve()\n .then(async () => {\n this.log('searching peer store for relays')\n\n const peers = (await this.components.peerStore.all({\n filters: [\n // filter by a list of peers supporting RELAY_V2_HOP and ones we are not listening on\n (peer) => {\n return peer.protocols.includes(RELAY_V2_HOP_CODEC)\n }\n ],\n orders: [\n // randomize\n () => Math.random() < 0.5 ? 1 : -1,\n // prefer peers we've connected to in the past\n (a, b) => {\n const lastDialA = getLastDial(a)\n const lastDialB = getLastDial(b)\n\n if (lastDialA > lastDialB) {\n return -1\n }\n\n if (lastDialB > lastDialA) {\n return 1\n }\n\n return 0\n }\n ]\n }))\n\n for (const peer of peers) {\n this.log.trace('found relay peer %p in peer store', peer.id)\n this.safeDispatchEvent('relay:discover', { detail: peer.id })\n }\n\n this.log('found %d relay peers in peer store', peers.length)\n\n // perform random walk and dial peers - after identify has run, the network\n // topology will be notified of new relays\n const queue = this.queue = new PeerQueue({\n concurrency: 5\n })\n\n this.log('start random walk')\n\n for await (const peer of this.components.randomWalk.walk({ signal: this.discoveryController.signal })) {\n this.log.trace('found random peer %p', peer.id)\n\n if (queue.has(peer.id)) {\n this.log.trace('random peer %p was already in queue', peer.id)\n\n // skip peers already in the queue\n continue\n }\n\n if (this.components.connectionManager.getConnections(peer.id)?.length > 0) {\n this.log.trace('random peer %p was already connected', peer.id)\n\n // skip peers we are already connected to\n continue\n }\n\n if (!(await this.components.connectionManager.isDialable(peer.multiaddrs))) {\n this.log.trace('random peer %p was not dialable', peer.id, peer.multiaddrs.map(ma => ma.toString()))\n\n // skip peers we can't dial\n continue\n }\n\n if (queue.queued > 10) {\n this.log.trace('wait for space in queue for %p', peer.id)\n\n // pause the random walk until there is space in the queue\n await queue.onSizeLessThan(10, {\n signal: this.discoveryController.signal\n })\n }\n\n this.log('adding random peer %p to dial queue (length: %d, active %d)', peer.id, queue.size, queue.running)\n\n // dial the peer - this will cause identify to run and our topology to\n // be notified and we'll attempt to create reservations\n queue.add(this.dialPeer, {\n peerId: peer.id,\n signal: this.discoveryController.signal\n })\n .catch(err => {\n this.log.error('error opening connection to random peer %p - %e', peer.id, err)\n })\n }\n\n this.log('stop random walk')\n\n await queue.onIdle()\n })\n .catch(err => {\n if (!this.discoveryController.signal.aborted) {\n this.log.error('failed when finding relays on the network - %e', err)\n }\n })\n }\n\n stopDiscovery (): void {\n this.log('stop discovery')\n this.running = false\n this.discoveryController?.abort()\n this.queue?.clear()\n\n // stop dialing any peer we discover\n this.components.events.removeEventListener('peer:discovery', this.onPeer)\n }\n\n onPeer (evt: CustomEvent<PeerInfo>): void {\n this.log.trace('maybe dialing discovered peer %p', evt.detail.id)\n\n this.maybeDialPeer(evt)\n .catch(err => {\n this.log.trace('error dialing discovered peer %p - %e', evt.detail.id, err)\n })\n }\n\n async maybeDialPeer (evt: CustomEvent<PeerInfo>): Promise<void> {\n if (this.queue == null) {\n return\n }\n\n const peerId = evt.detail.id\n const multiaddrs = evt.detail.multiaddrs\n\n if (this.queue.has(peerId)) {\n this.log.trace('random peer %p was already in queue', peerId)\n\n // skip peers already in the queue\n return\n }\n\n if (this.components.connectionManager.getConnections(peerId)?.length > 0) {\n this.log.trace('random peer %p was already connected', peerId)\n\n // skip peers we are already connected to\n return\n }\n\n if (!(await this.components.connectionManager.isDialable(multiaddrs))) {\n this.log.trace('random peer %p was not dialable', peerId)\n\n // skip peers we can't dial\n return\n }\n\n this.queue?.add(this.dialPeer, {\n peerId: evt.detail.id,\n signal: this.discoveryController.signal\n })\n .catch(err => {\n this.log.error('error opening connection to discovered peer %p - %e', evt.detail.id, err)\n })\n }\n\n async dialPeer ({ peerId, signal }: { peerId: PeerId, signal?: AbortSignal }): Promise<void> {\n const combinedSignal = anySignal([AbortSignal.timeout(5_000), signal])\n setMaxListeners(Infinity, combinedSignal)\n\n try {\n await this.components.connectionManager.openConnection(peerId, {\n signal: combinedSignal\n })\n } finally {\n combinedSignal.clear()\n }\n }\n}\n\n/**\n * Returns the timestamp of the last time we connected to this peer, if we've\n * not connected to them before return 0\n */\nfunction getLastDial (peer: Peer): number {\n const lastDial = peer.metadata.get('last-dial-success')\n\n if (lastDial == null) {\n return 0\n }\n\n return new Date(uint8ArrayToString(lastDial)).getTime()\n}\n", "import { ListenError } from '@libp2p/interface'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { TypedEventEmitter, setMaxListeners } from 'main-event'\nimport { DEFAULT_RESERVATION_COMPLETION_TIMEOUT } from '../constants.js'\nimport { CircuitListen, CircuitSearch } from '../utils.js'\nimport type { RelayReservation, ReservationStore } from './reservation-store.js'\nimport type { ComponentLogger, Logger, Listener, ListenerEvents, PeerId } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface CircuitRelayTransportListenerComponents {\n peerId: PeerId\n connectionManager: ConnectionManager\n addressManager: AddressManager\n reservationStore: ReservationStore\n logger: ComponentLogger\n}\n\nexport interface CircuitRelayTransportListenerInit {\n listenTimeout?: number\n}\n\nclass CircuitRelayTransportListener extends TypedEventEmitter<ListenerEvents> implements Listener {\n private readonly connectionManager: ConnectionManager\n private readonly addressManager: AddressManager\n private readonly reservationStore: ReservationStore\n private listeningAddrs: Multiaddr[]\n private readonly log: Logger\n private readonly listenTimeout: number\n private reservationId?: string\n private relay?: PeerId\n\n constructor (components: CircuitRelayTransportListenerComponents, init: CircuitRelayTransportListenerInit = {}) {\n super()\n\n this.log = components.logger.forComponent('libp2p:circuit-relay:transport:listener')\n this.connectionManager = components.connectionManager\n this.addressManager = components.addressManager\n this.reservationStore = components.reservationStore\n this.listeningAddrs = []\n this.listenTimeout = init.listenTimeout ?? DEFAULT_RESERVATION_COMPLETION_TIMEOUT\n\n // remove listening addrs when a relay is removed\n this.reservationStore.addEventListener('relay:removed', this._onRemoveRelayPeer)\n this.reservationStore.addEventListener('relay:created-reservation', this._onAddRelayPeer)\n }\n\n _onRemoveRelayPeer = (evt: CustomEvent<RelayReservation>): void => {\n this.log('relay removed %p our relay %p', evt.detail.relay, this.relay, this.relay?.equals(evt.detail.relay))\n\n if (this.relay?.equals(evt.detail.relay) !== true) {\n return\n }\n\n this.log('relay peer removed %p', evt.detail.relay)\n\n this.listeningAddrs.forEach(ma => {\n // mark as externally dialable\n this.addressManager.removeObservedAddr(ma)\n })\n\n this.listeningAddrs = []\n\n // announce listen addresses change\n this.safeDispatchEvent('listening')\n }\n\n _onAddRelayPeer = (evt: CustomEvent<RelayReservation>): void => {\n const {\n details\n } = evt.detail\n\n if (details.type === 'configured') {\n return\n }\n\n if (details.id !== this.reservationId) {\n return\n }\n\n this.addedRelay(evt.detail)\n }\n\n async listen (addr: Multiaddr): Promise<void> {\n if (CircuitSearch.exactMatch(addr)) {\n this.log('searching for circuit relay servers')\n\n // start relay discovery\n this.reservationId = this.reservationStore.reserveRelay()\n } else if (CircuitListen.exactMatch(addr)) {\n this.log('listen on specific relay server %a', addr)\n\n const signal = AbortSignal.timeout(this.listenTimeout)\n setMaxListeners(Infinity, signal)\n\n // try to make a reservation on one particular relay\n // remove the circuit part to get the peer id of the relay\n const relayAddr = addr.decapsulate('/p2p-circuit')\n const relayConn = await this.connectionManager.openConnection(relayAddr, {\n signal\n })\n\n if (!this.reservationStore.hasReservation(relayConn.remotePeer)) {\n this.log('making reservation on peer %p', relayConn.remotePeer)\n const reservation = await this.reservationStore.addRelay(relayConn.remotePeer, 'configured')\n this.addedRelay(reservation)\n }\n } else {\n throw new ListenError(`Could not listen on p2p-circuit address \"${addr}\"`)\n }\n }\n\n getAddrs (): Multiaddr[] {\n return [...this.listeningAddrs.values()].flat()\n }\n\n updateAnnounceAddrs (): void {\n\n }\n\n async close (): Promise<void> {\n this.reservationStore.cancelReservations()\n this.listeningAddrs = []\n\n // remove listener\n this.reservationStore.removeEventListener('relay:removed', this._onRemoveRelayPeer)\n\n // announce listen addresses change\n queueMicrotask(() => {\n this.safeDispatchEvent('close')\n })\n }\n\n private addedRelay (reservation: RelayReservation): void {\n this.log('relay peer added %p', reservation.relay)\n\n this.relay = reservation.relay\n\n // add all addresses from the relay reservation\n this.listeningAddrs = reservation.details.reservation.addrs\n .map(buf => multiaddr(buf).encapsulate('/p2p-circuit'))\n\n this.listeningAddrs.forEach(ma => {\n // mark as externally dialable\n this.addressManager.confirmObservedAddr(ma, {\n type: 'transport'\n })\n })\n\n // if that succeeded announce listen addresses change\n queueMicrotask(() => {\n this.safeDispatchEvent('listening')\n })\n }\n}\n\nexport function createListener (options: CircuitRelayTransportListenerComponents): Listener {\n return new CircuitRelayTransportListener(options)\n}\n", "export const urlAlphabet =\n 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\n", "/* @ts-self-types=\"./index.d.ts\" */\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\nexport { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << Math.log2(alphabet.length - 1)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step | 0\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length >= size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size | 0, random)\nexport let nanoid = (size = 21) => {\n let id = ''\n let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))\n while (size--) {\n id += scopedUrlAlphabet[bytes[size] & 63]\n }\n return id\n}\n", "import { ListenError } from '@libp2p/interface'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { createScalableCuckooFilter, PeerQueue, pbStream } from '@libp2p/utils'\nimport { CODE_P2P, multiaddr } from '@multiformats/multiaddr'\nimport { Circuit } from '@multiformats/multiaddr-matcher'\nimport { TypedEventEmitter, setMaxListeners } from 'main-event'\nimport { nanoid } from 'nanoid'\nimport { DEFAULT_MAX_RESERVATION_QUEUE_LENGTH, DEFAULT_RESERVATION_COMPLETION_TIMEOUT, DEFAULT_RESERVATION_CONCURRENCY, KEEP_ALIVE_TAG, RELAY_V2_HOP_CODEC } from '../constants.js'\nimport { DoubleRelayError, HadEnoughRelaysError, RelayQueueFullError } from '../errors.js'\nimport { HopMessage, Status } from '../pb/index.js'\nimport { getExpirationMilliseconds } from '../utils.js'\nimport type { TransportReservationStoreComponents, TransportReservationStoreInit } from '../index.ts'\nimport type { Reservation } from '../pb/index.js'\nimport type { AbortOptions, Libp2pEvents, Logger, PeerId, PeerStore, Startable, Peer, Connection } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\nimport type { Filter } from '@libp2p/utils'\nimport type { TypedEventTarget } from 'main-event'\n\n// allow refreshing a relay reservation if it will expire in the next 10 minutes\nconst REFRESH_WINDOW = (60 * 1000) * 10\n\n// try to refresh relay reservations 5 minutes before expiry\nconst REFRESH_TIMEOUT = (60 * 1000) * 5\n\n// minimum duration before which a reservation must not be refreshed\nconst REFRESH_TIMEOUT_MIN = 30 * 1000\n\nexport type RelayType = 'discovered' | 'configured'\n\nexport interface DiscoveredRelayEntry {\n timeout: ReturnType<typeof setTimeout>\n type: 'discovered'\n reservation: Reservation\n\n /**\n * Stores the id of the connection we have to the relay\n */\n connection: string\n\n /**\n * Stores the identifier returned when the reservation was requested\n */\n id: string\n}\n\nexport interface ConfiguredRelayEntry {\n timeout: ReturnType<typeof setTimeout>\n type: 'configured'\n reservation: Reservation\n\n /**\n * Stores the id of the connection we have to the relay\n */\n connection: string\n}\n\nexport type RelayEntry = DiscoveredRelayEntry | ConfiguredRelayEntry\n\nexport interface RelayReservation {\n relay: PeerId\n details: RelayEntry\n}\n\nexport interface ReservationStoreEvents {\n 'relay:not-enough-relays': CustomEvent\n 'relay:found-enough-relays': CustomEvent\n 'relay:removed': CustomEvent<RelayReservation>\n 'relay:created-reservation': CustomEvent<RelayReservation>\n}\n\nexport class ReservationStore extends TypedEventEmitter<ReservationStoreEvents> implements Startable {\n private readonly peerId: PeerId\n private readonly connectionManager: ConnectionManager\n private readonly peerStore: PeerStore\n private readonly events: TypedEventTarget<Libp2pEvents>\n private readonly reserveQueue: PeerQueue<RelayReservation>\n private readonly reservations: PeerMap<RelayEntry>\n private readonly pendingReservations: string[]\n private readonly maxReservationQueueLength: number\n private readonly reservationCompletionTimeout: number\n private started: boolean\n private readonly log: Logger\n private relayFilter: Filter\n\n constructor (components: TransportReservationStoreComponents, init?: TransportReservationStoreInit) {\n super()\n\n this.log = components.logger.forComponent('libp2p:circuit-relay:transport:reservation-store')\n this.peerId = components.peerId\n this.connectionManager = components.connectionManager\n this.peerStore = components.peerStore\n this.events = components.events\n this.reservations = new PeerMap()\n this.pendingReservations = []\n this.maxReservationQueueLength = init?.maxReservationQueueLength ?? DEFAULT_MAX_RESERVATION_QUEUE_LENGTH\n this.reservationCompletionTimeout = init?.reservationCompletionTimeout ?? DEFAULT_RESERVATION_COMPLETION_TIMEOUT\n this.started = false\n this.relayFilter = createScalableCuckooFilter(100)\n\n // ensure we don't listen on multiple relays simultaneously\n this.reserveQueue = new PeerQueue({\n concurrency: init?.reservationConcurrency ?? DEFAULT_RESERVATION_CONCURRENCY,\n metricName: 'libp2p_relay_reservation_queue',\n metrics: components.metrics\n })\n\n // reservations are only valid while we are still connected to the relay.\n // if we had a reservation opened via that connection, remove it and maybe\n // trigger a search for new relays\n this.events.addEventListener('connection:close', (evt) => {\n const reservation = [...this.reservations.values()]\n .find(reservation => reservation.connection === evt.detail.id)\n\n if (reservation == null) {\n return\n }\n\n this.#removeReservation(evt.detail.remotePeer)\n .catch(err => {\n this.log('could not remove relay %p - %e', evt.detail, err)\n })\n })\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n afterStart (): void {\n // remove old relay tags\n void Promise.resolve()\n .then(async () => {\n const relayPeers: Peer[] = await this.peerStore.all({\n filters: [(peer) => {\n return peer.tags.has(KEEP_ALIVE_TAG)\n }]\n })\n\n this.log('removing tag from %d old relays', relayPeers.length)\n\n // remove old relay tag and redial\n await Promise.all(\n relayPeers.map(async peer => {\n await this.peerStore.merge(peer.id, {\n tags: {\n [KEEP_ALIVE_TAG]: undefined\n }\n })\n })\n )\n\n this.log('redialing %d old relays', relayPeers.length)\n await Promise.all(\n relayPeers.map(async peer => this.addRelay(peer.id, 'discovered'))\n )\n\n this.#checkReservationCount()\n })\n .catch(err => {\n this.log.error('failed to clean up and redial old relays during afterStart - %e', err)\n })\n }\n\n stop (): void {\n this.reserveQueue.clear()\n this.reservations.forEach(({ timeout }) => {\n clearTimeout(timeout)\n })\n this.reservations.clear()\n this.started = false\n }\n\n reserveRelay (): string {\n const id = nanoid()\n\n this.pendingReservations.push(id)\n\n this.#checkReservationCount()\n\n return id\n }\n\n /**\n * If the number of current relays is beneath the configured `maxReservations`\n * value, and the passed peer id is not our own, and we have a non-relayed\n * connection to the remote, and the remote peer speaks the hop protocol, try\n * to reserve a slot on the remote peer\n */\n async addRelay (peerId: PeerId, type: RelayType): Promise<RelayReservation> {\n if (this.peerId.equals(peerId)) {\n this.log.trace('not trying to use self as relay')\n throw new ListenError('Cannot use self as relay')\n }\n\n if (this.reserveQueue.size > this.maxReservationQueueLength) {\n throw new RelayQueueFullError('The reservation queue is full')\n }\n\n const existingJob = this.reserveQueue.find(peerId)\n\n if (existingJob != null) {\n this.log.trace('potential relay peer %p is already in the reservation queue', peerId)\n return existingJob.join()\n }\n\n if (this.relayFilter.has(peerId.toMultihash().bytes)) {\n throw new ListenError('The relay was previously invalid')\n }\n\n this.log.trace('try to reserve relay slot with %p', peerId)\n\n return this.reserveQueue.add(async () => {\n const start = Date.now()\n\n try {\n // allow refresh of an existing reservation if it is about to expire\n const existingReservation = this.reservations.get(peerId)\n\n if (existingReservation != null) {\n const connections = this.connectionManager.getConnections(peerId)\n let connected = false\n\n if (connections.length === 0) {\n this.log('already have relay reservation with %p but we are no longer connected', peerId)\n }\n\n if (connections.map(conn => conn.id).includes(existingReservation.connection)) {\n this.log('already have relay reservation with %p and the original connection is still open', peerId)\n connected = true\n }\n\n if (connected && getExpirationMilliseconds(existingReservation.reservation.expire) > REFRESH_WINDOW) {\n this.log('already have relay reservation with %p but we are still connected and it does not expire soon', peerId)\n return {\n relay: peerId,\n details: existingReservation\n } satisfies RelayReservation\n }\n\n await this.#removeReservation(peerId)\n }\n\n if (type === 'discovered' && this.pendingReservations.length === 0) {\n throw new HadEnoughRelaysError('Not making reservation on discovered relay because we do not need any more relays')\n }\n\n const signal = AbortSignal.timeout(this.reservationCompletionTimeout)\n setMaxListeners(Infinity, signal)\n\n const connection = await this.connectionManager.openConnection(peerId, {\n signal\n })\n\n if (Circuit.matches(connection.remoteAddr)) {\n throw new DoubleRelayError('not creating reservation over relayed connection')\n }\n\n const reservation = await this.#createReservation(connection, {\n signal\n })\n\n const expiration = getExpirationMilliseconds(reservation.expire)\n\n this.log('created reservation on relay peer %p, expiry date is %s', peerId, new Date(Date.now() + expiration).toString())\n\n // sets a lower bound on the timeout, and also don't let it go over\n // 2^31 - 1 (setTimeout will only accept signed 32 bit integers)\n const timeoutDuration = Math.min(Math.max(expiration - REFRESH_TIMEOUT, REFRESH_TIMEOUT_MIN), Math.pow(2, 31) - 1)\n\n const timeout = setTimeout(() => {\n this.log('refresh reservation to relay %p', peerId)\n\n this.addRelay(peerId, type)\n .catch(async err => {\n this.log.error('could not refresh reservation to relay %p - %e', peerId, err)\n await this.#removeReservation(peerId)\n })\n .catch(err => {\n this.log.error('could not remove expired reservation to relay %p - %e', peerId, err)\n })\n }, timeoutDuration)\n\n let res: RelayEntry\n\n // assign a reservation id if one was requested\n if (type === 'discovered') {\n const id = this.pendingReservations.pop()\n\n if (id == null) {\n throw new HadEnoughRelaysError('Made reservation on relay but did not need any more discovered relays')\n }\n\n res = {\n timeout,\n reservation,\n type,\n connection: connection.id,\n id\n }\n } else {\n res = {\n timeout,\n reservation,\n type,\n connection: connection.id\n }\n }\n\n // we've managed to create a reservation successfully\n this.reservations.set(peerId, res)\n\n // ensure we don't close the connection to the relay\n await this.peerStore.merge(peerId, {\n tags: {\n [KEEP_ALIVE_TAG]: {\n value: 1,\n ttl: expiration\n }\n }\n })\n\n // check to see if we have discovered enough relays\n this.#checkReservationCount()\n\n const result: RelayReservation = {\n relay: peerId,\n details: res\n }\n\n this.safeDispatchEvent('relay:created-reservation', {\n detail: result\n })\n\n return result\n } catch (err: any) {\n if (!(type === 'discovered' && err.name === 'HadEnoughRelaysError')) {\n this.log.error('could not reserve slot on %p after %dms - %e', peerId, Date.now() - start, err)\n }\n\n // don't try this peer again if dialing failed or they do not support\n // the hop protocol\n if (err.name === 'DialError' || err.name === 'UnsupportedProtocolError') {\n this.relayFilter.add(peerId.toMultihash().bytes)\n }\n\n // if listening failed, remove the reservation\n this.#removeReservation(peerId)\n .catch(err => {\n this.log.error('could not remove reservation on %p after reserving slot failed - %e', peerId, err)\n })\n\n throw err\n }\n }, {\n peerId\n })\n }\n\n hasReservation (peerId: PeerId): boolean {\n return this.reservations.has(peerId)\n }\n\n getReservation (peerId: PeerId): Reservation | undefined {\n return this.reservations.get(peerId)?.reservation\n }\n\n reservationCount (type?: RelayType): number {\n if (type == null) {\n return this.reservations.size\n }\n\n return [...this.reservations.values()].reduce((acc, curr) => {\n if (curr.type === type) {\n acc++\n }\n\n return acc\n }, 0)\n }\n\n cancelReservations (): void {\n [...this.reservations.values()].forEach(reservation => {\n clearTimeout(reservation.timeout)\n })\n\n this.reservations.clear()\n }\n\n async #createReservation (connection: Connection, options: AbortOptions): Promise<Reservation> {\n options.signal?.throwIfAborted()\n\n this.log('requesting reservation from %p', connection.remotePeer)\n const stream = await connection.newStream(RELAY_V2_HOP_CODEC, options)\n const pbstr = pbStream(stream)\n const hopstr = pbstr.pb(HopMessage)\n\n this.log.trace('send RESERVE to %p', connection.remotePeer)\n await hopstr.write({ type: HopMessage.Type.RESERVE }, options)\n\n let response: HopMessage\n\n try {\n this.log.trace('reading response from %p', connection.remotePeer)\n response = await hopstr.read(options)\n } catch (err: any) {\n stream.abort(err)\n throw err\n } finally {\n if (stream.status !== 'closed') {\n await stream.close(options)\n }\n }\n\n this.log.trace('read response %s', response.status)\n\n if (response.status === Status.OK && response.reservation != null) {\n // check that the returned relay has the relay address - this can be\n // omitted when requesting a reservation from a go-libp2p relay we\n // already have a reservation on\n const addresses = new Set<string>()\n addresses.add(connection.remoteAddr.toString())\n\n for (const buf of response.reservation.addrs) {\n let ma = multiaddr(buf)\n\n if (ma.getComponents().find(c => c.code === CODE_P2P) == null) {\n ma = ma.encapsulate(`/p2p/${connection.remotePeer}`)\n }\n\n // TODO: workaround for https://github.com/libp2p/go-libp2p/issues/3003\n ma = multiaddr(ma.toString().replace(\n `/p2p/${connection.remotePeer}/p2p/${connection.remotePeer}`,\n `/p2p/${connection.remotePeer}`\n ))\n\n addresses.add(ma.toString())\n }\n\n response.reservation.addrs = [...addresses].map(str => multiaddr(str).bytes)\n\n return response.reservation\n }\n\n const errMsg = `reservation failed with status ${response.status ?? 'undefined'}`\n this.log.error(errMsg)\n\n throw new Error(errMsg)\n }\n\n /**\n * Remove listen relay\n */\n async #removeReservation (peerId: PeerId): Promise<void> {\n const reservation = this.reservations.get(peerId)\n\n if (reservation == null) {\n return\n }\n\n this.log('removing relay reservation with %p from local store', peerId)\n clearTimeout(reservation.timeout)\n this.reservations.delete(peerId)\n\n // discover a new relay for this discovery request\n if (reservation.type === 'discovered') {\n this.pendingReservations.push(\n reservation.id\n )\n }\n\n // untag the relay\n await this.peerStore.merge(peerId, {\n tags: {\n [KEEP_ALIVE_TAG]: undefined\n }\n })\n\n this.safeDispatchEvent('relay:removed', {\n detail: {\n relay: peerId,\n details: reservation\n }\n })\n\n // maybe trigger discovery of new relays\n this.#checkReservationCount()\n }\n\n #checkReservationCount (): void {\n if (this.pendingReservations.length === 0) {\n this.log.trace('have discovered enough relays')\n this.reserveQueue.clear()\n this.safeDispatchEvent('relay:found-enough-relays')\n\n return\n }\n\n this.relayFilter = createScalableCuckooFilter(100)\n this.log('not discovered enough relays %d/%d', this.reservations.size, this.pendingReservations.length)\n this.safeDispatchEvent('relay:not-enough-relays')\n }\n}\n", "import { AbstractMultiaddrConnection } from '@libp2p/utils'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { AbortOptions, MultiaddrConnection, Stream } from '@libp2p/interface'\nimport type { AbstractMultiaddrConnectionInit, SendResult } from '@libp2p/utils'\n\nexport interface StreamMultiaddrConnectionInit extends Omit<AbstractMultiaddrConnectionInit, 'direction'> {\n stream: Stream\n\n /**\n * A callback invoked when data is read from the stream\n */\n onDataRead?(buf: Uint8ArrayList | Uint8Array): void\n\n /**\n * A callback invoked when data is written to the stream\n */\n onDataWrite?(buf: Uint8ArrayList | Uint8Array): void\n}\n\nclass StreamMultiaddrConnection extends AbstractMultiaddrConnection {\n private stream: Stream\n private init: StreamMultiaddrConnectionInit\n\n constructor (init: StreamMultiaddrConnectionInit) {\n super({\n ...init,\n direction: init.stream.direction\n\n })\n\n this.init = init\n this.stream = init.stream\n\n this.stream.addEventListener('close', (evt) => {\n this.onTransportClosed(evt.error)\n })\n\n this.stream.addEventListener('remoteCloseWrite', (evt) => {\n this.onRemoteCloseWrite()\n\n // close our end when the remote closes\n this.close()\n .catch(err => {\n this.abort(err)\n })\n })\n\n // count incoming bytes\n this.stream.addEventListener('message', (evt) => {\n init.onDataRead?.(evt.data)\n this.onData(evt.data)\n })\n\n // forward drain events\n this.stream.addEventListener('drain', () => {\n this.safeDispatchEvent('drain')\n })\n }\n\n sendData (data: Uint8ArrayList): SendResult {\n this.init.onDataWrite?.(data)\n\n return {\n sentBytes: data.byteLength,\n canSendMore: this.stream.send(data)\n }\n }\n\n async sendClose (options?: AbortOptions): Promise<void> {\n await this.stream.close(options)\n }\n\n sendReset (): void {\n this.stream.abort(new Error('An error occurred'))\n }\n\n sendPause (): void {\n this.stream.pause()\n }\n\n sendResume (): void {\n this.stream.resume()\n }\n}\n\n/**\n * Convert a Stream into a MultiaddrConnection.\n */\nexport function streamToMaConnection (init: StreamMultiaddrConnectionInit): MultiaddrConnection {\n return new StreamMultiaddrConnection(init)\n}\n", "import { DialError, InvalidMessageError, serviceCapabilities, serviceDependencies, start, stop, transportSymbol } from '@libp2p/interface'\nimport { peerFilter } from '@libp2p/peer-collections'\nimport { peerIdFromMultihash, peerIdFromString } from '@libp2p/peer-id'\nimport { pbStream } from '@libp2p/utils'\nimport { CODE_P2P, multiaddr } from '@multiformats/multiaddr'\nimport { Circuit } from '@multiformats/multiaddr-matcher'\nimport { setMaxListeners } from 'main-event'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CustomProgressEvent } from 'progress-events'\nimport { DEFAULT_DISCOVERY_FILTER_ERROR_RATE, DEFAULT_DISCOVERY_FILTER_SIZE, MAX_CONNECTIONS, RELAY_V2_HOP_CODEC, RELAY_V2_STOP_CODEC } from '../constants.js'\nimport { StopMessage, HopMessage, Status } from '../pb/index.js'\nimport { CircuitListen, CircuitSearch, LimitTracker } from '../utils.js'\nimport { RelayDiscovery } from './discovery.js'\nimport { createListener } from './listener.js'\nimport { ReservationStore } from './reservation-store.js'\nimport { streamToMaConnection } from './stream-to-conn.js'\nimport type { CircuitRelayTransportComponents, CircuitRelayTransportInit } from '../index.ts'\nimport type { Transport, CreateListenerOptions, Listener, Logger, Connection, Stream, OutboundConnectionUpgradeEvents, DialTransportOptions, OpenConnectionProgressEvents } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { ProgressEvent } from 'progress-events'\n\nconst isValidStop = (request: StopMessage): request is Required<StopMessage> => {\n if (request.peer == null) {\n return false\n }\n\n try {\n request.peer.addrs.forEach(multiaddr)\n } catch {\n return false\n }\n\n return true\n}\n\nconst defaults = {\n maxInboundStopStreams: MAX_CONNECTIONS,\n maxOutboundStopStreams: MAX_CONNECTIONS,\n stopTimeout: 30000\n}\n\nexport type CircuitRelayDialEvents =\n OutboundConnectionUpgradeEvents |\n OpenConnectionProgressEvents |\n ProgressEvent<'circuit-relay:open-connection'> |\n ProgressEvent<'circuit-relay:reuse-connection'> |\n ProgressEvent<'circuit-relay:open-hop-stream'> |\n ProgressEvent<'circuit-relay:write-connect-message'> |\n ProgressEvent<'circuit-relay:read-connect-response'>\n\nexport class CircuitRelayTransport implements Transport<CircuitRelayDialEvents> {\n private readonly components: CircuitRelayTransportComponents\n private readonly discovery?: RelayDiscovery\n public readonly reservationStore: ReservationStore\n private readonly maxInboundStopStreams: number\n private readonly maxOutboundStopStreams?: number\n private started: boolean\n private readonly log: Logger\n private shutdownController: AbortController\n\n constructor (components: CircuitRelayTransportComponents, init: CircuitRelayTransportInit = {}) {\n this.components = components\n this.log = components.logger.forComponent('libp2p:circuit-relay:transport')\n this.maxInboundStopStreams = init.maxInboundStopStreams ?? defaults.maxInboundStopStreams\n this.maxOutboundStopStreams = init.maxOutboundStopStreams ?? defaults.maxOutboundStopStreams\n this.shutdownController = new AbortController()\n\n this.discovery = new RelayDiscovery(components, {\n filter: init.discoveryFilter ?? peerFilter(DEFAULT_DISCOVERY_FILTER_SIZE, DEFAULT_DISCOVERY_FILTER_ERROR_RATE)\n })\n this.discovery.addEventListener('relay:discover', (evt) => {\n this.reservationStore.addRelay(evt.detail, 'discovered')\n .catch(err => {\n if (err.name !== 'HadEnoughRelaysError' && err.name !== 'RelayQueueFullError') {\n this.log.error('could not add discovered relay %p - %e', evt.detail, err)\n }\n })\n })\n this.reservationStore = new ReservationStore(components, init)\n this.reservationStore.addEventListener('relay:not-enough-relays', () => {\n this.discovery?.startDiscovery()\n })\n this.reservationStore.addEventListener('relay:found-enough-relays', () => {\n this.discovery?.stopDiscovery()\n })\n\n this.started = false\n\n this.onStop = this.onStop.bind(this)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/circuit-relay-v2-transport'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/transport',\n '@libp2p/circuit-relay-v2-transport'\n ]\n\n get [serviceDependencies] (): string[] {\n // we only need identify if discovery is enabled\n if (this.discovery != null) {\n return [\n '@libp2p/identify'\n ]\n }\n\n return []\n }\n\n readonly [transportSymbol] = true\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n this.shutdownController = new AbortController()\n setMaxListeners(Infinity, this.shutdownController.signal)\n\n await this.components.registrar.handle(RELAY_V2_STOP_CODEC, this.onStop, {\n maxInboundStreams: this.maxInboundStopStreams,\n maxOutboundStreams: this.maxOutboundStopStreams,\n runOnLimitedConnection: true\n })\n\n await start(this.discovery, this.reservationStore)\n\n this.started = true\n }\n\n async stop (): Promise<void> {\n this.shutdownController.abort()\n await stop(this.discovery, this.reservationStore)\n await this.components.registrar.unhandle(RELAY_V2_STOP_CODEC)\n\n this.started = false\n }\n\n /**\n * Dial a peer over a relay\n */\n async dial (ma: Multiaddr, options: DialTransportOptions<CircuitRelayDialEvents>): Promise<Connection> {\n // Check the multiaddr to see if it contains a relay and a destination peer\n const addrs = ma.toString().split('/p2p-circuit')\n const relayAddr = multiaddr(addrs[0])\n const destinationAddr = multiaddr(addrs[addrs.length - 1])\n const relayId = relayAddr.getComponents().find(c => c.code === CODE_P2P)?.value\n const destinationId = destinationAddr.getComponents().find(c => c.code === CODE_P2P)?.value\n\n if (relayId == null || destinationId == null) {\n const errMsg = `ircuit relay dial to ${ma.toString()} failed as address did not have both relay and destination PeerIDs`\n this.log.error(`c${errMsg}`)\n throw new DialError(`C${errMsg}`)\n }\n\n const relayPeer = peerIdFromString(relayId)\n const destinationPeer = peerIdFromString(destinationId)\n\n const relayConnections = this.components.connectionManager.getConnections(relayPeer)\n let relayConnection = relayConnections[0]\n\n if (relayConnection == null) {\n await this.components.peerStore.merge(relayPeer, {\n multiaddrs: [relayAddr]\n })\n\n options.onProgress?.(new CustomProgressEvent('circuit-relay:open-connection'))\n relayConnection = await this.components.connectionManager.openConnection(relayPeer, options)\n } else {\n options.onProgress?.(new CustomProgressEvent('circuit-relay:reuse-connection'))\n }\n\n let stream: Stream | undefined\n\n try {\n options.onProgress?.(new CustomProgressEvent('circuit-relay:open-hop-stream'))\n stream = await relayConnection.newStream(RELAY_V2_HOP_CODEC, options)\n\n const hopstr = pbStream(stream).pb(HopMessage)\n\n options.onProgress?.(new CustomProgressEvent('circuit-relay:write-connect-message'))\n await hopstr.write({\n type: HopMessage.Type.CONNECT,\n peer: {\n id: destinationPeer.toMultihash().bytes,\n addrs: [multiaddr(destinationAddr).bytes]\n }\n }, options)\n\n options.onProgress?.(new CustomProgressEvent('circuit-relay:read-connect-response'))\n const status = await hopstr.read(options)\n\n if (status.status !== Status.OK) {\n throw new InvalidMessageError(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`)\n }\n\n const limits = new LimitTracker(status.limit)\n\n const maConn = streamToMaConnection({\n stream: hopstr.unwrap().unwrap(),\n remoteAddr: ma,\n localAddr: relayAddr.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),\n onDataRead: limits.onData,\n onDataWrite: limits.onData,\n log: stream.log.newScope('circuit-relay:connection')\n })\n\n const conn = await this.components.upgrader.upgradeOutbound(maConn, {\n ...options,\n limits: limits.getLimits()\n })\n\n conn.log('outbound relayed connection established to %p with limits %o, over connection %s', conn.remotePeer, status.limit ?? 'none', relayConnection.id)\n\n return conn\n } catch (err: any) {\n this.log.error('circuit relay dial to destination %p via relay %p failed - %e', destinationPeer, relayPeer, err)\n stream?.abort(err)\n\n throw err\n }\n }\n\n /**\n * Create a listener\n */\n createListener (options: CreateListenerOptions): Listener {\n return createListener({\n peerId: this.components.peerId,\n connectionManager: this.components.connectionManager,\n addressManager: this.components.addressManager,\n reservationStore: this.reservationStore,\n logger: this.components.logger\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can listen on\n */\n listenFilter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return CircuitListen.exactMatch(ma) || CircuitSearch.exactMatch(ma)\n })\n }\n\n /**\n * Filter check for all Multiaddrs that this transport can dial\n */\n dialFilter (multiaddrs: Multiaddr[]): Multiaddr[] {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]\n\n return multiaddrs.filter((ma) => {\n return Circuit.exactMatch(ma)\n })\n }\n\n /**\n * An incoming STOP request means a remote peer wants to dial us via a relay\n */\n async onStop (stream: Stream, connection: Connection): Promise<void> {\n const signal = this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal)\n\n try {\n if (!this.reservationStore.hasReservation(connection.remotePeer)) {\n try {\n this.log('dialed via relay we did not have a reservation on, start listening on that relay address')\n await this.components.transportManager.listen([connection.remoteAddr.encapsulate('/p2p-circuit')])\n } catch (err: any) {\n // failed to refresh our hitherto unknown relay reservation but allow the connection attempt anyway\n this.log.error('failed to listen on a relay peer we were dialed via but did not have a reservation on - %e', err)\n }\n }\n\n const stopStream = pbStream(stream).pb(StopMessage)\n const request = await stopStream.read({\n signal\n })\n\n this.log('new circuit relay v2 stop stream from %p with type %s', connection.remotePeer, request.type)\n\n if (request?.type === undefined) {\n this.log.error('type was missing from circuit v2 stop protocol request from %s', connection.remotePeer)\n await stopStream.write({ type: StopMessage.Type.STATUS, status: Status.MALFORMED_MESSAGE }, {\n signal\n })\n await stream.close({\n signal\n })\n return\n }\n\n // Validate the STOP request has the required input\n if (request.type !== StopMessage.Type.CONNECT) {\n this.log.error('invalid stop connect request via peer %p', connection.remotePeer)\n await stopStream.write({ type: StopMessage.Type.STATUS, status: Status.UNEXPECTED_MESSAGE }, {\n signal\n })\n await stream.close({\n signal\n })\n return\n }\n\n if (!isValidStop(request)) {\n this.log.error('invalid stop connect request via peer %p', connection.remotePeer)\n await stopStream.write({ type: StopMessage.Type.STATUS, status: Status.MALFORMED_MESSAGE }, {\n signal\n })\n await stream.close({\n signal\n })\n return\n }\n\n const remotePeerId = peerIdFromMultihash(Digest.decode(request.peer.id))\n\n if ((await this.components.connectionGater.denyInboundRelayedConnection?.(connection.remotePeer, remotePeerId)) === true) {\n this.log.error('connection gater denied inbound relayed connection from %p', connection.remotePeer)\n await stopStream.write({ type: StopMessage.Type.STATUS, status: Status.PERMISSION_DENIED }, {\n signal\n })\n await stream.close({\n signal\n })\n return\n }\n\n this.log.trace('sending success response to %p', connection.remotePeer)\n await stopStream.write({ type: StopMessage.Type.STATUS, status: Status.OK }, {\n signal\n })\n\n const limits = new LimitTracker(request.limit)\n const remoteAddr = connection.remoteAddr.encapsulate(`/p2p-circuit/p2p/${remotePeerId.toString()}`)\n const localAddr = this.components.addressManager.getAddresses()[0]\n const maConn = streamToMaConnection({\n stream: stopStream.unwrap().unwrap(),\n remoteAddr,\n localAddr,\n onDataRead: limits.onData,\n onDataWrite: limits.onData,\n log: stream.log.newScope('circuit-relay:connection')\n })\n\n await this.components.upgrader.upgradeInbound(maConn, {\n limits: limits.getLimits(),\n signal\n })\n\n maConn.log('inbound relayed connection established to %p with limits %o, over connection %s', remotePeerId, request.limit ?? 'none', connection.id)\n } finally {\n signal?.clear()\n }\n }\n}\n"],
|
|
5
5
|
"mappings": ";sdAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,wBAAAE,GAAA,wBAAAC,GAAA,uBAAAC,GAAA,0BAAAC,KC6FM,IAAOC,GAAP,cAAuE,WAAW,CAC7EC,GAAa,IAAI,IAE1B,aAAA,CACE,MAAK,CAKP,CAEA,cAAeC,EAAY,CACzB,IAAMC,EAAY,KAAKF,GAAW,IAAIC,CAAI,EAE1C,OAAIC,GAAa,KACR,EAGFA,EAAU,MACnB,CAGA,iBAAkBD,EAAcE,EAA+BC,EAA2C,CACxG,MAAM,iBAAiBH,EAAME,EAAUC,CAAO,EAE9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S,0BAA0B,EACpD,EAED,MAAM,KAAK,WAAW,SAAS,eAAeU,EAAQ,CACpD,OAAQF,EAAO,UAAS,EACxB,OAAAW,EACD,EAEDT,EAAO,IAAI,kFAAmFY,EAAczD,EAAQ,OAAS,OAAQqD,EAAW,EAAE,CACpJ,SACEC,GAAQ,MAAK,CACf,CACF,GjJnLI,SAAUQ,GAAoBC,EAA+B,CAAA,EAAE,CACnE,OAAQC,GACC,IAAIC,GAAmBD,EAAYD,CAAI,CAElD,CAmGM,SAAUG,GAAuBH,EAAkC,CAAA,EAAE,CACzE,OAAQC,GACC,IAAIG,GAAsBH,EAAYD,CAAI,CAErD",
|
|
6
6
|
"names": ["index_exports", "__export", "RELAY_V2_HOP_CODEC", "RELAY_V2_STOP_CODEC", "circuitRelayServer", "circuitRelayTransport", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "options", "list", "callback", "event", "result", "once", "detail", "AbortError", "message", "InvalidParametersError", "message", "InvalidPublicKeyError", "StreamResetError", "message", "StreamStateError", "message", "StreamBufferError", "InvalidCIDError", "message", "InvalidMultihashError", "InvalidMessageError", "message", "DialError", "message", "ListenError", "UnsupportedKeyTypeError", "message", "StreamMessageEvent", "data", "eventInitDict", "StreamCloseEvent", "local", "error", "StreamAbortEvent", "StreamResetEvent", "peerIdSymbol", "KEEP_ALIVE", "isStartable", "obj", "start", "objs", "startables", "s", "stop", "transportSymbol", "FaultTolerance", "serviceCapabilities", "serviceDependencies", "base58_exports", "__export", "base58btc", "base58flickr", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "base", "ALPHABET", "name", "BASE_MAP", "j", "i", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "options", "create", "identity", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "sha2_browser_exports", "__export", "sha256", "sha512", "DEFAULT_MIN_DIGEST_LENGTH", "from", "name", "code", "encode", "minDigestLength", "maxDigestLength", "Hasher", "input", "options", "result", "createDigest", "digest", "truncate", "create", "sha", "name", "data", "sha256", "from", "sha512", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "toString", "array", "encoding", "base", "bases_default", "TAG_MASK", "LONG_LENGTH_MASK", "LONG_LENGTH_BYTES_MASK", "decoders", "readSequence", "readInteger", "readBitString", "readOctetString", "readNull", "readObjectIdentifier", "decodeDer", "buf", "context", "tag", "readLength", "length", "count", "str", "i", "entries", "result", "start", "end", "vals", "finalOffset", "byte", "val1", "val2", "oid", "num", "val", "unusedBits", "bytes", "encodeNumber", "value", "number", "array", "Uint8ArrayList", "encodeLength", "encodeInteger", "contents", "mask", "encodeBitString", "encodeSequence", "values", "tag", "output", "Uint8ArrayList", "buf", "encodeLength", "hashAndVerify", "key", "sig", "msg", "options", "publicKey", "result", "OID_256", "OID_384", "OID_521", "P_256_KEY_JWK", "P_384_KEY_JWK", "P_521_KEY_JWK", "P_256_KEY_LENGTH", "P_384_KEY_LENGTH", "P_521_KEY_LENGTH", "unmarshalECDSAPublicKey", "bytes", "message", "decodeDer", "pkiMessageToECDSAPublicKey", "coordinates", "offset", "x", "y", "P_256_KEY_LENGTH", "toString", "ECDSAPublicKey", "P_256_KEY_JWK", "P_384_KEY_LENGTH", "P_384_KEY_JWK", "P_521_KEY_LENGTH", "P_521_KEY_JWK", "InvalidParametersError", "publicKeyToPKIMessage", "publicKey", "encodeSequence", "encodeInteger", "getOID", "encodeBitString", "Uint8ArrayList", "fromString", "curve", "OID_256", "OID_384", "OID_521", "InvalidParametersError", "ECDSAPublicKey", "jwk", "publicKeyToPKIMessage", "identity", "publicKeyToProtobuf", "CID", "base58btc", "key", "equals", "data", "sig", "options", "hashAndVerify", "isBytes", "a", "anumber", "n", "title", "prefix", "abytes", "value", "length", "bytes", "len", "needsLen", "ofLen", "got", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "abytes", "hex", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "createHasher", "hashCons", "info", "hashC", "msg", "opts", "tmp", "randomBytes", "bytesLength", "cr", "oidNist", "suffix", "Chi", "a", "b", "c", "Maj", "HashMD", "blockLen", "outputLen", "padOffset", "isLE", "createView", "data", "aexists", "abytes", "view", "buffer", "len", "pos", "take", "dataView", "out", "aoutput", "clean", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA512_IV", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "len", "Ah", "Al", "i", "h", "l", "shrSH", "h", "_l", "s", "shrSL", "l", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add", "Ah", "Al", "Bh", "Bl", "l", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "SHA256_K", "SHA256_W", "SHA2_32B", "HashMD", "outputLen", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "_SHA256", "SHA256_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "HashMD", "outputLen", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "clean", "_SHA512", "SHA512_IV", "sha256", "createHasher", "_SHA256", "oidNist", "sha512", "createHasher", "_SHA512", "oidNist", "_0n", "_1n", "abool", "value", "title", "prefix", "abignumber", "n", "isPosBig", "anumber", "numberToHexUnpadded", "num", "hex", "abignumber", "hexToNumber", "_0n", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "copyBytes", "abytes", "numberToBytesBE", "n", "len", "anumber", "res", "hexToBytes", "numberToBytesLE", "copyBytes", "bytes", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "anumber", "u8n", "len", "NULL", "byte0", "byte1", "_maxDrbgIters", "v", "k", "i", "reset", "h", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "iter", "f", "memoized", "fn", "map", "arg", "args", "val", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_7n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "res", "_0n", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "assertIsSquare", "Fp", "root", "sqrt3mod4", "p1div4", "_4n", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "i", "t_tmp", "exponent", "FpSqrt", "_9n", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "invertedAcc", "FpLegendre", "Fp", "n", "p1mod2", "_1n", "_2n", "powered", "yes", "zero", "no", "nLength", "n", "nBitLength", "anumber", "_nBitLength", "nByteLength", "_Field", "_0n", "_1n", "ORDER", "opts", "_nbitLength", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "skipValidation", "abytes", "allowedLengths", "BYTES", "isLE", "modFromBytes", "padded", "scalar", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "condition", "Field", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "abytes", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "negateCt", "condition", "item", "neg", "normalizeZ", "c", "points", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "pointPrecomputes", "pointWindowSizes", "getW", "P", "assert0", "n", "_0n", "wNAF", "Point", "bits", "elm", "p", "d", "_1n", "point", "W", "windows", "windowSize", "calcWOpts", "points", "base", "window", "i", "precomputes", "f", "wo", "nextN", "offset", "isZero", "isNeg", "isNegF", "offsetF", "calcOffsets", "negateCt", "acc", "item", "transform", "comp", "scalar", "prev", "validateW", "mulEndoUnsafe", "k1", "k2", "p1", "p2", "createField", "order", "field", "isLE", "validateField", "Field", "createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "p", "val", "_0n", "Fp", "Fn", "params", "createKeygen", "randomSecretKey", "getPublicKey", "seed", "secretKey", "_0n", "_1n", "_2n", "_8n", "isEdValidXY", "Fp", "CURVE", "x", "y", "x2", "y2", "left", "right", "edwards", "params", "extraOpts", "validated", "createCurveFields", "Fn", "cofactor", "validateObject", "MASK", "modP", "n", "uvRatio", "u", "v", "acoord", "title", "banZero", "min", "aInRange", "aedpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "X", "Y", "Z", "is0", "zz", "assertValidMemo", "a", "d", "T", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "bytes", "zip215", "len", "copyBytes", "abytes", "abool", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "hex", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "scalar", "f", "normalizeZ", "acc", "invertedZ", "bytesToHex", "wNAF", "eddsa", "Point", "cHash", "eddsaOpts", "validateObject", "prehash", "BASE", "Fp", "Fn", "randomBytes", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "abool", "modN_LE", "hash", "bytesToNumberLE", "getPrivateScalar", "key", "len", "lengths", "abytes", "hashed", "head", "prefix", "scalar", "getExtendedPublicKey", "secretKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "rs", "verifyOpts", "verify", "sig", "publicKey", "zip215", "mid", "A", "SB", "_size", "randomSecretKey", "seed", "isValidSecretKey", "isBytes", "isValidPublicKey", "utils", "y", "size", "is25519", "u", "_1n", "createKeygen", "_1n", "_2n", "_5n", "_8n", "ed25519_CURVE_p", "ed25519_CURVE", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "_2n", "b5", "_1n", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "ED25519_SQRT_M1", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "ed25519_Point", "edwards", "ed", "opts", "eddsa", "ed25519_Point", "sha512", "adjustScalarBytes", "ed25519", "VerificationError", "message", "WebCryptoMissingError", "webcrypto_browser_default", "win", "nativeCrypto", "WebCryptoMissingError", "webcrypto_default", "webcrypto_browser_default", "PUBLIC_KEY_BYTE_LENGTH", "ed25519Supported", "webCryptoEd25519SupportedPromise", "webcrypto_default", "hashAndVerifyWebCrypto", "publicKey", "sig", "msg", "key", "webcrypto_default", "hashAndVerifyNoble", "ed25519", "hashAndVerify", "ed25519Supported", "webCryptoEd25519SupportedPromise", "isPromise", "thing", "Ed25519PublicKey", "key", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "options", "result", "hashAndVerify", "isPromise", "res", "unmarshalEd25519PublicKey", "bytes", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "Ed25519PublicKey", "ensureEd25519Key", "key", "length", "InvalidParametersError", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "MSB", "REST", "encodingLength", "value", "encodeUint8Array", "buf", "offset", "encodeUint8ArrayList", "decodeUint8Array", "b", "res", "decodeUint8ArrayList", "encode", "allocUnsafe", "decode", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "_LongBits", "lo", "hi", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "pool", "size", "SIZE", "MAX", "slab", "offset", "allocUnsafe", "buf", "Op", "fn", "len", "val", "noop", "State", "writer", "bufferPool", "pool", "alloc", "size", "allocUnsafe", "Uint8ArrayWriter", "value", "VarintOp", "writeVarint64", "LongBits", "bits", "encodeUint8Array", "encodingLength", "writeByte", "writeFixed32", "writeFloatLE", "writeDoubleLE", "writeBytes", "length", "write", "head", "tail", "buf", "pos", "writeVarint32", "writeBytesBuffer", "writeStringBuffer", "fromString", "createWriter", "encodeMessage", "message", "codec", "w", "createWriter", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "MaxLengthError", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "utils_exports", "__export", "MAX_RSA_KEY_SIZE", "generateRSAKeyPair", "jwkToJWKKeyPair", "jwkToPkcs1", "jwkToPkix", "jwkToRSAPrivateKey", "pkcs1MessageToJwk", "pkcs1MessageToRSAPrivateKey", "pkcs1ToJwk", "pkcs1ToRSAPrivateKey", "pkixMessageToJwk", "pkixMessageToRSAPublicKey", "pkixToJwk", "pkixToRSAPublicKey", "RSAPublicKey", "jwk", "digest", "utils_exports", "CID", "base58btc", "key", "equals", "data", "sig", "options", "hashAndVerify", "RSAPrivateKey", "publicKey", "message", "hashAndSign", "MAX_RSA_KEY_SIZE", "SHA2_256_CODE", "MAX_RSA_JWK_SIZE", "RSA_ALGORITHM_IDENTIFIER", "pkcs1ToJwk", "bytes", "message", "decodeDer", "pkcs1MessageToJwk", "toString", "jwkToPkcs1", "jwk", "InvalidParametersError", "encodeSequence", "encodeInteger", "fromString", "pkixToJwk", "pkixMessageToJwk", "keys", "jwkToPkix", "encodeBitString", "pkcs1ToRSAPrivateKey", "pkcs1MessageToRSAPrivateKey", "jwkToRSAPrivateKey", "pkixToRSAPublicKey", "digest", "InvalidPublicKeyError", "pkixMessageToRSAPublicKey", "hash", "sha256", "PublicKey", "KeyType", "create", "RSAPublicKey", "rsaKeySize", "jwkToJWKKeyPair", "RSAPrivateKey", "generateRSAKeyPair", "bits", "generateRSAKey", "key", "generateRSAKey", "bits", "options", "pair", "webcrypto_default", "keys", "exportKey", "hashAndSign", "key", "msg", "options", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "result", "exportKey", "pair", "InvalidParametersError", "rsaKeySize", "jwk", "fromString", "_HMAC", "hash", "key", "ahash", "abytes", "blockLen", "pad", "i", "clean", "buf", "aexists", "out", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "divNearest", "num", "den", "_2n", "_splitEndoScalar", "k", "basis", "n", "a1", "b1", "a2", "b2", "c1", "c2", "k1", "k2", "k1neg", "_0n", "k2neg", "MAX_NUM", "bitMask", "bitLen", "_1n", "validateSigFormat", "format", "validateSigOpts", "opts", "def", "optsn", "optName", "abool", "DERErr", "m", "DER", "tag", "data", "E", "dataLen", "len", "numberToHexUnpadded", "lenLen", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "hex", "bytesToNumberBE", "bytes", "int", "tlv", "abytes", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "_3n", "_4n", "weierstrass", "params", "extraOpts", "validated", "createCurveFields", "Fp", "Fn", "CURVE", "cofactor", "CURVE_ORDER", "validateObject", "endo", "lengths", "getWLengths", "assertCompressionIsSupported", "pointToBytes", "_c", "point", "isCompressed", "x", "y", "bx", "hasEvenY", "concatBytes", "pprefix", "pointFromBytes", "comp", "uncomp", "head", "tail", "y2", "weierstrassEquation", "sqrtError", "err", "evenY", "L", "isValidXY", "encodePoint", "decodePoint", "x2", "x3", "left", "right", "_4a3", "_27b2", "acoord", "title", "banZero", "aprjpoint", "other", "Point", "splitEndoScalarN", "toAffineMemo", "memoized", "p", "iz", "X", "Y", "Z", "is0", "zz", "assertValidMemo", "finishEndo", "endoBeta", "k1p", "k2p", "negateCt", "P", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "a", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "scalar", "fake", "mul", "normalizeZ", "k1f", "k2f", "f", "sc", "p1", "p2", "mulEndoUnsafe", "invertedZ", "isTorsionFree", "clearCofactor", "bytesToHex", "bits", "wNAF", "getWLengths", "Fp", "Fn", "ecdh", "Point", "ecdhOpts", "randomBytes_", "randomBytes", "lengths", "getMinHashLength", "isValidSecretKey", "secretKey", "num", "isValidPublicKey", "publicKey", "isCompressed", "comp", "publicKeyUncompressed", "l", "randomSecretKey", "seed", "mapHashToField", "abytes", "getPublicKey", "isProbPub", "item", "isBytes", "getSharedSecret", "secretKeyA", "publicKeyB", "s", "utils", "keygen", "createKeygen", "ecdsa", "hash", "ecdsaOpts", "ahash", "validateObject", "hmac", "key", "msg", "CURVE_ORDER", "fnBits", "defaultSigOpts", "hasLargeCofactor", "_2n", "isBiggerThanHalfOrder", "number", "HALF", "_1n", "validateRS", "title", "assertSmallCofactor", "validateSigLength", "bytes", "format", "validateSigFormat", "size", "sizer", "Signature", "r", "recovery", "recid", "DER", "L", "hex", "hexToBytes", "messageHash", "radj", "x", "R", "concatBytes", "pprefix", "ir", "h", "bits2int_modN", "u1", "u2", "Q", "rb", "sb", "bytesToHex", "bits2int", "bytesToNumberBE", "delta", "ORDER_MASK", "bitMask", "int2octets", "aInRange", "_0n", "validateMsgAndHash", "message", "prehash", "prepSig", "opts", "lowS", "extraEntropy", "validateSigOpts", "h1int", "d", "seedArgs", "e", "m", "k2sig", "kBytes", "k", "ik", "q", "normS", "sign", "createHmacDrbg", "verify", "signature", "end", "sig", "P", "is", "recoverPublicKey", "secp256k1_CURVE", "secp256k1_ENDO", "_2n", "sqrtMod", "y", "P", "secp256k1_CURVE", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "Pointk1", "weierstrass", "secp256k1_ENDO", "secp256k1", "ecdsa", "sha256", "hashAndVerify", "key", "sig", "msg", "options", "p", "sha256", "isPromise", "digest", "secp256k1", "err", "VerificationError", "Secp256k1PublicKey", "key", "validateSecp256k1PublicKey", "compressSecp256k1PublicKey", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "options", "hashAndVerify", "unmarshalSecp256k1PublicKey", "bytes", "Secp256k1PublicKey", "compressSecp256k1PublicKey", "key", "secp256k1", "validateSecp256k1PublicKey", "key", "secp256k1", "err", "InvalidPublicKeyError", "publicKeyFromProtobuf", "buf", "digest", "Type", "Data", "PublicKey", "data", "KeyType", "pkixToRSAPublicKey", "unmarshalEd25519PublicKey", "unmarshalSecp256k1PublicKey", "unmarshalECDSAPublicKey", "UnsupportedKeyTypeError", "publicKeyFromMultihash", "digest", "Type", "Data", "PublicKey", "data", "KeyType", "unmarshalEd25519PublicKey", "unmarshalSecp256k1PublicKey", "unmarshalECDSAPublicKey", "UnsupportedKeyTypeError", "publicKeyToProtobuf", "key", "inspect", "LIBP2P_KEY_CODE", "PeerIdImpl", "init", "peerIdSymbol", "base58btc", "CID", "id", "equals", "RSAPeerId", "Ed25519PeerId", "Secp256k1PeerId", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "URLPeerId", "url", "identity", "fromString", "other", "toString", "LIBP2P_KEY_CODE", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "peerIdFromString", "str", "decoder", "multihash", "decode", "base58btc", "peerIdFromCID", "CID", "InvalidParametersError", "peerIdFromMultihash", "peerIdFromMultihash", "multihash", "isSha256Multihash", "RSAPeerId", "isIdentityMultihash", "publicKey", "publicKeyFromMultihash", "Ed25519PeerId", "Secp256k1PeerId", "url", "toString", "URLPeerId", "InvalidMultihashError", "peerIdFromCID", "cid", "LIBP2P_KEY_CODE", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "InvalidCIDError", "identity", "sha256", "Envelope", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "encodeMessage", "buf", "decodeMessage", "InvalidSignatureError", "message", "RecordEnvelope", "_RecordEnvelope", "data", "envelopeData", "Envelope", "publicKey", "publicKeyFromProtobuf", "record", "privateKey", "options", "domain", "payloadType", "payload", "signData", "formatSignaturePayload", "signature", "envelope", "InvalidSignatureError", "init", "publicKeyToProtobuf", "other", "equals", "domainUint8Array", "fromString", "domainLength", "encode", "payloadTypeLength", "payloadLength", "Uint8ArrayList", "InvalidMultiaddrError", "ValidationError", "InvalidParametersError", "UnknownProtocolError", "Parser", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "input", "MAX_IPV6_LENGTH", "parser", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "bytesToString", "base", "buf", "toString", "stringToBytes", "fromString", "bytes2port", "port2bytes", "port", "onion2bytes", "str", "addr", "portBuf", "concat", "onion32bytes", "base32", "bytes2onion", "addrBytes", "portBytes", "ip4ToBytes", "ip", "bytes", "byte", "index", "value", "InvalidMultiaddrError", "ip6ToBytes", "offset", "sections", "i", "isv4", "isIPv4", "v4Buffer", "argv", "word", "ip4ToString", "result", "ip6ToString", "byte1", "byte2", "tuple", "url", "ip6StringToValue", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "mb2bytes", "mbstr", "bytes2mb", "integer", "value", "ValidationError", "positive", "maxValue", "max", "validate", "funcs", "fn", "validatePort", "V", "Registry", "key", "codec", "UnknownProtocolError", "alias", "code", "registry", "codecs", "ip4ToBytes", "ip4ToString", "value", "isIPv4", "ValidationError", "port2bytes", "bytes2port", "validatePort", "ip6ToBytes", "ip6ToString", "ip6StringToValue", "isIPv6", "bytesToString", "stringToBytes", "str", "val", "CID", "bytes2onion", "onion2bytes", "onion32bytes", "bytes2mb", "base64url", "mb2bytes", "bytesToComponents", "bytes", "components", "i", "code", "decode", "codec", "registry", "codeLength", "encodingLength", "size", "sizeForAddr", "sizeLength", "V", "componentLength", "component", "valueOffset", "valueBytes", "toString", "componentsToBytes", "length", "codecLength", "valueLength", "valueLengthLength", "fromString", "offset", "encodeUint8Array", "concat", "stringToComponents", "string", "InvalidMultiaddrError", "collecting", "value", "protocol", "char", "ended", "componentsToString", "inspect", "symbol", "toComponents", "addr", "isMultiaddr", "bytesToComponents", "stringToComponents", "InvalidMultiaddrError", "Multiaddr", "_Multiaddr", "#components", "#string", "#bytes", "options", "validate", "componentsToBytes", "componentsToString", "c", "ma", "addrString", "s", "i", "InvalidParametersError", "code", "index", "equals", "component", "codec", "registry", "isMultiaddr", "value", "symbol", "multiaddr", "addr", "Multiaddr", "FNV_PRIMES", "FNV_OFFSETS", "cachedEncoder", "fnv1aUint8Array", "uint8Array", "size", "fnvPrime", "hash", "index", "fnv1aEncodeInto", "string", "utf8Buffer", "remaining", "result", "fnv1a", "value", "fnv1a", "input", "seed", "numberToBuffer", "num", "hex", "fromString", "MAX_FINGERPRINT_SIZE", "Fingerprint", "buf", "hash", "seed", "fingerprintSize", "fnv", "fp", "alloc", "i", "other", "equals", "getRandomInt", "min", "max", "Bucket", "size", "fingerprint", "Fingerprint", "fp", "i", "getRandomInt", "current", "found", "maxCuckooCount", "CuckooFilter", "init", "fnv1a", "getRandomInt", "item", "fromString", "fingerprint", "Fingerprint", "j", "k", "Bucket", "rand", "n", "swapped", "inJ", "inK", "MAX_LOAD", "calculateBucketSize", "errorRate", "optimize", "maxItems", "bucketSize", "load", "filterSize", "fingerprintSize", "MAX_FINGERPRINT_SIZE", "ScalableCuckooFilter", "init", "fnv1a", "getRandomInt", "CuckooFilter", "item", "fromString", "current", "cuckoo", "curSize", "i", "acc", "curr", "createScalableCuckooFilter", "maxItems", "errorRate", "options", "optimize", "pDefer", "deferred", "resolve", "reject", "FixedFIFO", "hwm", "data", "last", "FIFO", "options", "obj", "val", "prev", "next", "AbortError", "message", "code", "pushable", "options", "_pushable", "buffer", "next", "_pushable", "getNext", "options", "onEnd", "buffer", "FIFO", "pushable", "onNext", "ended", "drain", "pDefer", "waitNext", "resolve", "reject", "next", "err", "bufferNext", "bufferError", "push", "value", "end", "_return", "_throw", "signal", "cancel", "listener", "AbortError", "opts", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "normalizeEmitter", "emitter", "addListener", "removeListener", "pEventMultiple", "event", "options", "cancel", "returnValue", "resolve", "reject", "events", "items", "onItem", "arguments_", "value", "error", "rejectHandler", "rejectionEvent", "timeout", "pTimeout", "pEvent", "arrayPromise", "promise", "array", "debounce", "func", "wait", "timeout", "output", "later", "QueueFullError", "message", "UnexpectedEOFError", "StreamClosedError", "defaultTranslate", "signal", "raceSignal", "promise", "opts", "translateError", "listener", "resolve", "reject", "JobRecipient", "signal", "pDefer", "AbortError", "randomId", "Job", "fn", "options", "err", "acc", "curr", "AbortError", "recipient", "JobRecipient", "result", "raceSignal", "Queue", "TypedEventEmitter", "init", "debounce", "job", "j", "i", "fn", "options", "QueueFullError", "Job", "result", "err", "AbortError", "pEvent", "limit", "stream", "pushable", "cleanup", "onQueueJobComplete", "evt", "onQueueFailure", "onQueueIdle", "onSignalAbort", "DEFAULT_MAX_READ_BUFFER_LENGTH", "AbstractMessageStream", "TypedEventEmitter", "init", "Uint8ArrayList", "continueSendingOnDrain", "rejectOnDrainOnClose", "evt", "StreamClosedError", "options", "raceSignal", "output", "pushable", "streamAsyncIterableOnMessageListener", "streamAsyncIterableOnCloseListener", "streamAsyncIterableOnRemoteCloseWriteListener", "data", "StreamStateError", "err", "StreamAbortEvent", "args", "StreamResetError", "StreamResetEvent", "StreamCloseEvent", "canSendMore", "totalBytes", "sentBytes", "end", "toSend", "willSend", "sendResult", "buf", "StreamMessageEvent", "StreamBufferError", "AbstractMultiaddrConnection", "AbstractMessageStream", "init", "evt", "options", "pEvent", "anySignal", "signals", "controller", "onAbort", "signal", "clear", "AbortError", "message", "code", "name", "raceSignal", "promise", "signal", "opts", "listener", "error", "resolve", "reject", "QueuelessPushable", "pDefer", "nextResult", "err", "result", "value", "options", "raceSignal", "queuelessPushable", "isAsyncIterable", "thing", "addAllToPushable", "sources", "output", "signal", "source", "item", "err", "mergeSources", "controller", "queuelessPushable", "mergeSyncSources", "syncSources", "merge", "src_default", "pipe", "first", "rest", "isDuplex", "duplex", "isIterable", "isAsyncIterable", "source", "fns", "i", "duplexPipelineFn", "rawPipe", "res", "obj", "p", "stream", "pushable", "err", "sourceWrap", "src_default", "DEFAULT_MAX_BUFFER_SIZE", "UnwrappedError", "InvalidMessageLengthError", "InvalidDataLengthError", "InvalidDataLengthLengthError", "isStream", "obj", "isMultiaddrConnection", "isEOF", "isValid", "byteStream", "stream", "opts", "maxBufferSize", "readBuffer", "Uint8ArrayList", "hasBytes", "unwrapped", "InvalidParametersError", "byteStreamOnMessageListener", "evt", "readBufferSize", "byteStreamOnCloseListener", "byteStreamOnRemoteCloseWrite", "options", "UnexpectedEOFError", "bytesToRead", "raceSignal", "toRead", "output", "data", "pEvent", "lpStream", "bytes", "encodingLength", "decodeLength", "decode", "encodeLength", "encode", "dataLength", "lengthBuffer", "buf", "err", "list", "pbStream", "lp", "proto", "value", "message", "messages", "d", "isMessageStream", "obj", "messageStreamToDuplex", "stream", "source", "pushable", "onError", "onMessage", "evt", "onRemoteCloseWrite", "onClose", "toGenerator", "gen", "done", "value", "pEvent", "pipe", "input", "sources", "PeerQueue", "Queue", "peerId", "job", "code", "vals", "component", "value", "not", "matcher", "optional", "result", "or", "matchers", "matches", "and", "fmt", "match", "ma", "parts", "exactMatch", "_PEER_ID", "value", "PEER_ID", "fmt", "_DNS4", "_DNS6", "_DNSADDR", "_DNS", "DNS4", "optional", "DNS6", "DNSADDR", "DNS", "or", "_IP4", "and", "_IP6", "_IP", "_IP_OR_DOMAIN", "IP_OR_DOMAIN", "IP4", "IP6", "IP", "_TCP", "_UDP", "TCP", "UDP", "_QUIC", "code", "_QUIC_V1", "QUIC_V0_OR_V1", "QUIC", "QUIC_V1", "_WEB", "_WebSockets", "WebSockets", "_WebSocketsSecure", "WebSocketsSecure", "_WebRTCDirect", "WebRTCDirect", "_WebTransport", "WebTransport", "_P2P", "P2P", "_Circuit", "not", "Circuit", "_WebRTC", "WebRTC", "_HTTP", "HTTP", "_HTTPS", "HTTPS", "_Memory", "Memory", "_Unix", "Unix", "second", "minute", "DEFAULT_MAX_RESERVATION_STORE_SIZE", "DEFAULT_MAX_RESERVATION_TTL", "DEFAULT_RESERVATION_CONCURRENCY", "DEFAULT_RESERVATION_COMPLETION_TIMEOUT", "DEFAULT_MAX_RESERVATION_QUEUE_LENGTH", "RELAY_SOURCE_TAG", "KEEP_ALIVE_TAG", "KEEP_ALIVE", "DEFAULT_DURATION_LIMIT", "DEFAULT_DATA_LIMIT", "RELAY_V2_HOP_CODEC", "RELAY_V2_STOP_CODEC", "DEFAULT_HOP_TIMEOUT", "DEFAULT_ADVERT_BOOT_DELAY", "MAX_CONNECTIONS", "DEFAULT_DISCOVERY_FILTER_SIZE", "DEFAULT_DISCOVERY_FILTER_ERROR_RATE", "HopMessage", "Type", "__TypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "Peer", "Reservation", "Limit", "Status", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "StopMessage", "value", "alloc", "MaxLengthError", "Envelope", "__StatusValues", "ReservationVoucher", "TransferLimitError", "message", "DurationLimitError", "HadEnoughRelaysError", "DoubleRelayError", "RelayQueueFullError", "countStreamBytes", "source", "limit", "options", "limitBytes", "abortIfStreamByteLimitExceeded", "evt", "len", "TransferLimitError", "createLimitedRelay", "src", "dst", "abortSignal", "reservation", "abortStreams", "err", "signals", "durationSignal", "signal", "anySignal", "dataLimit", "onAbort", "DurationLimitError", "pipe", "getExpirationMilliseconds", "expireTimeSeconds", "expireTimeMillis", "currentTime", "LimitTracker", "limits", "buf", "output", "self", "CircuitListen", "fmt", "and", "P2P", "code", "CircuitSearch", "mapIterable", "iter", "map", "iterator", "next", "val", "PeerMap", "map", "key", "value", "peer", "mapIterable", "val", "fn", "PeerFilter", "size", "errorRate", "createScalableCuckooFilter", "peerId", "peerFilter", "TrackedPeerMap", "PeerMap", "init", "name", "metrics", "key", "value", "deleted", "trackedPeerMap", "config", "map", "AbortError", "message", "code", "name", "retimeableSignal", "ms", "opts", "error", "controller", "abortHandler", "signal", "retimerSignal", "newMs", "ReservationStore", "components", "init", "DEFAULT_MAX_RESERVATION_STORE_SIZE", "DEFAULT_MAX_RESERVATION_TTL", "DEFAULT_DURATION_LIMIT", "DEFAULT_DATA_LIMIT", "trackedPeerMap", "peer", "addr", "limit", "reservation", "Status", "expiry", "checkedLimit", "retimeableSignal", "ReservationVoucherRecord", "_ReservationVoucherRecord", "relay", "peer", "expiration", "ReservationVoucher", "other", "defaults", "MAX_CONNECTIONS", "CircuitRelayServer", "TypedEventEmitter", "components", "init", "DEFAULT_HOP_TIMEOUT", "ReservationStore", "RELAY_V2_HOP_CODEC", "stream", "connection", "signal", "options", "pbstr", "pbStream", "request", "HopMessage", "err", "Status", "hopstr", "Circuit", "result", "ttl", "RELAY_SOURCE_TAG", "remotePeer", "expire", "addrs", "relayAddr", "envelope", "RecordEnvelope", "ReservationVoucherRecord", "publicKeyToProtobuf", "dstPeer", "multiaddr", "peerIdFromMultihash", "decode", "reservation", "connections", "destinationConnection", "destinationStream", "StopMessage", "createLimitedRelay", "RELAY_V2_STOP_CODEC", "stopstr", "response", "CustomProgressEvent", "type", "detail", "RelayDiscovery", "TypedEventEmitter", "components", "init", "RELAY_V2_HOP_CODEC", "peerId", "peers", "peer", "a", "b", "lastDialA", "getLastDial", "lastDialB", "queue", "PeerQueue", "ma", "err", "evt", "multiaddrs", "signal", "combinedSignal", "anySignal", "lastDial", "toString", "CircuitRelayTransportListener", "TypedEventEmitter", "components", "init", "DEFAULT_RESERVATION_COMPLETION_TIMEOUT", "evt", "ma", "details", "addr", "CircuitSearch", "CircuitListen", "signal", "relayAddr", "relayConn", "reservation", "ListenError", "buf", "multiaddr", "createListener", "options", "urlAlphabet", "nanoid", "size", "id", "bytes", "urlAlphabet", "REFRESH_WINDOW", "REFRESH_TIMEOUT", "REFRESH_TIMEOUT_MIN", "ReservationStore", "TypedEventEmitter", "components", "init", "PeerMap", "DEFAULT_MAX_RESERVATION_QUEUE_LENGTH", "DEFAULT_RESERVATION_COMPLETION_TIMEOUT", "createScalableCuckooFilter", "PeerQueue", "DEFAULT_RESERVATION_CONCURRENCY", "evt", "reservation", "#removeReservation", "err", "relayPeers", "peer", "KEEP_ALIVE_TAG", "#checkReservationCount", "timeout", "id", "nanoid", "peerId", "type", "ListenError", "RelayQueueFullError", "existingJob", "start", "existingReservation", "connections", "connected", "conn", "getExpirationMilliseconds", "HadEnoughRelaysError", "signal", "connection", "Circuit", "DoubleRelayError", "#createReservation", "expiration", "timeoutDuration", "res", "result", "acc", "curr", "options", "stream", "RELAY_V2_HOP_CODEC", "hopstr", "pbStream", "HopMessage", "response", "Status", "addresses", "buf", "ma", "multiaddr", "c", "str", "errMsg", "StreamMultiaddrConnection", "AbstractMultiaddrConnection", "init", "evt", "err", "data", "options", "streamToMaConnection", "isValidStop", "request", "multiaddr", "defaults", "MAX_CONNECTIONS", "CircuitRelayTransport", "components", "init", "RelayDiscovery", "peerFilter", "DEFAULT_DISCOVERY_FILTER_SIZE", "DEFAULT_DISCOVERY_FILTER_ERROR_RATE", "evt", "err", "ReservationStore", "serviceCapabilities", "serviceDependencies", "transportSymbol", "RELAY_V2_STOP_CODEC", "start", "stop", "ma", "options", "addrs", "relayAddr", "destinationAddr", "relayId", "c", "destinationId", "errMsg", "DialError", "relayPeer", "peerIdFromString", "destinationPeer", "relayConnection", "CustomProgressEvent", "stream", "RELAY_V2_HOP_CODEC", "hopstr", "pbStream", "HopMessage", "status", "Status", "InvalidMessageError", "limits", "LimitTracker", "maConn", "streamToMaConnection", "conn", "createListener", "multiaddrs", "CircuitListen", "CircuitSearch", "Circuit", "connection", "signal", "stopStream", "StopMessage", "remotePeerId", "peerIdFromMultihash", "decode", "remoteAddr", "localAddr", "circuitRelayServer", "init", "components", "CircuitRelayServer", "circuitRelayTransport", "CircuitRelayTransport"]
|