@libp2p/pubsub 10.1.13 → 10.1.14
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 +1 -1
- package/dist/index.min.js.map +4 -4
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +2 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/peer-streams.d.ts +1 -1
- package/dist/src/peer-streams.d.ts.map +1 -1
- package/dist/src/peer-streams.js +1 -1
- package/dist/src/peer-streams.js.map +1 -1
- package/package.json +12 -11
- package/src/index.ts +2 -1
- package/src/peer-streams.ts +1 -1
package/dist/index.min.js.map
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
|
-
"sources": ["../../../node_modules/eventemitter3/index.js", "../src/index.ts", "../../interface/src/peer-id.ts", "../../interface/src/pubsub.ts", "../../interface/src/errors.ts", "
|
4
|
-
"sourcesContent": ["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "/**\n * @packageDocumentation\n *\n * A set of components to be extended in order to create a pubsub implementation.\n *\n * @example\n *\n * ```TypeScript\n * import { PubSubBaseProtocol } from '@libp2p/pubsub'\n * import type { PubSubRPC, PublishResult, PubSubRPCMessage, PeerId, Message } from '@libp2p/interface'\n * import type { Uint8ArrayList } from 'uint8arraylist'\n *\n * class MyPubsubImplementation extends PubSubBaseProtocol {\n * decodeRpc (bytes: Uint8Array | Uint8ArrayList): PubSubRPC {\n * throw new Error('Not implemented')\n * }\n *\n * encodeRpc (rpc: PubSubRPC): Uint8Array {\n * throw new Error('Not implemented')\n * }\n *\n * encodeMessage (rpc: PubSubRPCMessage): Uint8Array {\n * throw new Error('Not implemented')\n * }\n *\n * async publishMessage (sender: PeerId, message: Message): Promise<PublishResult> {\n * throw new Error('Not implemented')\n * }\n * }\n * ```\n */\n\nimport { TypedEventEmitter, TopicValidatorResult, InvalidMessageError, NotStartedError, InvalidParametersError } from '@libp2p/interface'\nimport { PeerMap, PeerSet } from '@libp2p/peer-collections'\nimport { pipe } from 'it-pipe'\nimport Queue from 'p-queue'\nimport { PeerStreams as PeerStreamsImpl } from './peer-streams.js'\nimport {\n signMessage,\n verifySignature\n} from './sign.js'\nimport { toMessage, ensureArray, noSignMsgId, msgId, toRpcMessage, randomSeqno } from './utils.js'\nimport type { PubSub, Message, StrictNoSign, StrictSign, PubSubInit, PubSubEvents, PeerStreams, PubSubRPCMessage, PubSubRPC, PubSubRPCSubscription, SubscriptionChangeData, PublishResult, TopicValidatorFn, ComponentLogger, Logger, Connection, PeerId, PrivateKey, IncomingStreamData } from '@libp2p/interface'\nimport type { Registrar } from '@libp2p/interface-internal'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PubSubComponents {\n peerId: PeerId\n privateKey: PrivateKey\n registrar: Registrar\n logger: ComponentLogger\n}\n\n/**\n * PubSubBaseProtocol handles the peers and connections logic for pubsub routers\n * and specifies the API that pubsub routers should have.\n */\nexport abstract class PubSubBaseProtocol<Events extends Record<string, any> = PubSubEvents> extends TypedEventEmitter<Events> implements PubSub<Events> {\n protected log: Logger\n\n public started: boolean\n /**\n * Map of topics to which peers are subscribed to\n */\n public topics: Map<string, PeerSet>\n /**\n * List of our subscriptions\n */\n public subscriptions: Set<string>\n /**\n * Map of peer streams\n */\n public peers: PeerMap<PeerStreams>\n /**\n * The signature policy to follow by default\n */\n public globalSignaturePolicy: typeof StrictNoSign | typeof StrictSign\n /**\n * If router can relay received messages, even if not subscribed\n */\n public canRelayMessage: boolean\n /**\n * if publish should emit to self, if subscribed\n */\n public emitSelf: boolean\n /**\n * Topic validator map\n *\n * Keyed by topic\n * Topic validators are functions with the following input:\n */\n public topicValidators: Map<string, TopicValidatorFn>\n public queue: Queue\n public multicodecs: string[]\n public components: PubSubComponents\n\n private _registrarTopologyIds: string[] | undefined\n protected enabled: boolean\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n\n constructor (components: PubSubComponents, props: PubSubInit) {\n super()\n\n const {\n multicodecs = [],\n globalSignaturePolicy = 'StrictSign',\n canRelayMessage = false,\n emitSelf = false,\n messageProcessingConcurrency = 10,\n maxInboundStreams = 1,\n maxOutboundStreams = 1\n } = props\n\n this.log = components.logger.forComponent('libp2p:pubsub')\n this.components = components\n this.multicodecs = ensureArray(multicodecs)\n this.enabled = props.enabled !== false\n this.started = false\n this.topics = new Map()\n this.subscriptions = new Set()\n this.peers = new PeerMap<PeerStreams>()\n this.globalSignaturePolicy = globalSignaturePolicy === 'StrictNoSign' ? 'StrictNoSign' : 'StrictSign'\n this.canRelayMessage = canRelayMessage\n this.emitSelf = emitSelf\n this.topicValidators = new Map()\n this.queue = new Queue({ concurrency: messageProcessingConcurrency })\n this.maxInboundStreams = maxInboundStreams\n this.maxOutboundStreams = maxOutboundStreams\n\n this._onIncomingStream = this._onIncomingStream.bind(this)\n this._onPeerConnected = this._onPeerConnected.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n }\n\n // LIFECYCLE METHODS\n\n /**\n * Register the pubsub protocol onto the libp2p node.\n */\n async start (): Promise<void> {\n if (this.started || !this.enabled) {\n return\n }\n\n this.log('starting')\n\n const registrar = this.components.registrar\n // Incoming streams\n // Called after a peer dials us\n await Promise.all(this.multicodecs.map(async multicodec => {\n await registrar.handle(multicodec, this._onIncomingStream, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams\n })\n }))\n\n // register protocol with topology\n // Topology callbacks called on connection manager changes\n const topology = {\n onConnect: this._onPeerConnected,\n onDisconnect: this._onPeerDisconnected\n }\n this._registrarTopologyIds = await Promise.all(this.multicodecs.map(async multicodec => registrar.register(multicodec, topology)))\n\n this.log('started')\n this.started = true\n }\n\n /**\n * Unregister the pubsub protocol and the streams with other peers will be closed.\n */\n async stop (): Promise<void> {\n if (!this.started || !this.enabled) {\n return\n }\n\n const registrar = this.components.registrar\n\n // unregister protocol and handlers\n if (this._registrarTopologyIds != null) {\n this._registrarTopologyIds?.forEach(id => {\n registrar.unregister(id)\n })\n }\n\n await Promise.all(this.multicodecs.map(async multicodec => {\n await registrar.unhandle(multicodec)\n }))\n\n this.log('stopping')\n for (const peerStreams of this.peers.values()) {\n peerStreams.close()\n }\n\n this.peers.clear()\n this.subscriptions = new Set()\n this.started = false\n this.log('stopped')\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * On an inbound stream opened\n */\n protected _onIncomingStream (data: IncomingStreamData): void {\n const { stream, connection } = data\n const peerId = connection.remotePeer\n\n if (stream.protocol == null) {\n stream.abort(new Error('Stream was not multiplexed'))\n return\n }\n\n const peer = this.addPeer(peerId, stream.protocol)\n const inboundStream = peer.attachInboundStream(stream)\n\n this.processMessages(peerId, inboundStream, peer)\n .catch(err => { this.log(err) })\n }\n\n /**\n * Registrar notifies an established connection with pubsub protocol\n */\n protected _onPeerConnected (peerId: PeerId, conn: Connection): void {\n this.log('connected %p', peerId)\n\n // if this connection is already in use for pubsub, ignore it\n if (conn.streams.find(stream => stream.direction === 'outbound' && stream.protocol != null && this.multicodecs.includes(stream.protocol)) != null) {\n this.log('outbound pubsub streams already present on connection from %p', peerId)\n return\n }\n\n void Promise.resolve().then(async () => {\n try {\n const stream = await conn.newStream(this.multicodecs)\n\n if (stream.protocol == null) {\n stream.abort(new Error('Stream was not multiplexed'))\n return\n }\n\n const peer = this.addPeer(peerId, stream.protocol)\n await peer.attachOutboundStream(stream)\n } catch (err: any) {\n this.log.error(err)\n }\n\n // Immediately send my own subscriptions to the newly established conn\n this.send(peerId, { subscriptions: Array.from(this.subscriptions).map(sub => sub.toString()), subscribe: true })\n })\n .catch(err => {\n this.log.error(err)\n })\n }\n\n /**\n * Registrar notifies a closing connection with pubsub protocol\n */\n protected _onPeerDisconnected (peerId: PeerId, conn?: Connection): void {\n this.log('connection ended %p', peerId)\n this._removePeer(peerId)\n }\n\n /**\n * Notifies the router that a peer has been connected\n */\n addPeer (peerId: PeerId, protocol: string): PeerStreams {\n const existing = this.peers.get(peerId)\n\n // If peer streams already exists, do nothing\n if (existing != null) {\n return existing\n }\n\n // else create a new peer streams\n this.log('new peer %p', peerId)\n\n const peerStreams: PeerStreams = new PeerStreamsImpl(this.components, {\n id: peerId,\n protocol\n })\n\n this.peers.set(peerId, peerStreams)\n peerStreams.addEventListener('close', () => this._removePeer(peerId), {\n once: true\n })\n\n return peerStreams\n }\n\n /**\n * Notifies the router that a peer has been disconnected\n */\n protected _removePeer (peerId: PeerId): PeerStreams | undefined {\n const peerStreams = this.peers.get(peerId)\n if (peerStreams == null) {\n return\n }\n\n // close peer streams\n peerStreams.close()\n\n // delete peer streams\n this.log('delete peer %p', peerId)\n this.peers.delete(peerId)\n\n // remove peer from topics map\n for (const peers of this.topics.values()) {\n peers.delete(peerId)\n }\n\n return peerStreams\n }\n\n // MESSAGE METHODS\n\n /**\n * Responsible for processing each RPC message received by other peers.\n */\n async processMessages (peerId: PeerId, stream: AsyncIterable<Uint8ArrayList>, peerStreams: PeerStreams): Promise<void> {\n try {\n await pipe(\n stream,\n async (source) => {\n for await (const data of source) {\n const rpcMsg = this.decodeRpc(data)\n const messages: PubSubRPCMessage[] = []\n\n for (const msg of (rpcMsg.messages ?? [])) {\n if (msg.from == null || msg.data == null || msg.topic == null) {\n this.log('message from %p was missing from, data or topic fields, dropping', peerId)\n continue\n }\n\n messages.push({\n from: msg.from,\n data: msg.data,\n topic: msg.topic,\n sequenceNumber: msg.sequenceNumber ?? undefined,\n signature: msg.signature ?? undefined,\n key: msg.key ?? undefined\n })\n }\n\n // Since processRpc may be overridden entirely in unsafe ways,\n // the simplest/safest option here is to wrap in a function and capture all errors\n // to prevent a top-level unhandled exception\n // This processing of rpc messages should happen without awaiting full validation/execution of prior messages\n this.processRpc(peerId, peerStreams, {\n subscriptions: (rpcMsg.subscriptions ?? []).map(sub => ({\n subscribe: Boolean(sub.subscribe),\n topic: sub.topic ?? ''\n })),\n messages\n })\n .catch(err => { this.log(err) })\n }\n }\n )\n } catch (err: any) {\n this._onPeerDisconnected(peerStreams.id, err)\n }\n }\n\n /**\n * Handles an rpc request from a peer\n */\n async processRpc (from: PeerId, peerStreams: PeerStreams, rpc: PubSubRPC): Promise<boolean> {\n if (!this.acceptFrom(from)) {\n this.log('received message from unacceptable peer %p', from)\n return false\n }\n\n this.log('rpc from %p', from)\n\n const { subscriptions, messages } = rpc\n\n if (subscriptions != null && subscriptions.length > 0) {\n this.log('subscription update from %p', from)\n\n // update peer subscriptions\n subscriptions.forEach((subOpt) => {\n this.processRpcSubOpt(from, subOpt)\n })\n\n super.dispatchEvent(new CustomEvent<SubscriptionChangeData>('subscription-change', {\n detail: {\n peerId: peerStreams.id,\n subscriptions: subscriptions.map(({ topic, subscribe }) => ({\n topic: `${topic ?? ''}`,\n subscribe: Boolean(subscribe)\n }))\n }\n }))\n }\n\n if (messages != null && messages.length > 0) {\n this.log('messages from %p', from)\n\n this.queue.addAll(messages.map(message => async () => {\n if (message.topic == null || (!this.subscriptions.has(message.topic) && !this.canRelayMessage)) {\n this.log('received message we didn\\'t subscribe to. Dropping.')\n return false\n }\n\n try {\n const msg = await toMessage(message)\n\n await this.processMessage(from, msg)\n } catch (err: any) {\n this.log.error(err)\n }\n }))\n .catch(err => { this.log(err) })\n }\n\n return true\n }\n\n /**\n * Handles a subscription change from a peer\n */\n processRpcSubOpt (id: PeerId, subOpt: PubSubRPCSubscription): void {\n const t = subOpt.topic\n\n if (t == null) {\n return\n }\n\n let topicSet = this.topics.get(t)\n if (topicSet == null) {\n topicSet = new PeerSet()\n this.topics.set(t, topicSet)\n }\n\n if (subOpt.subscribe === true) {\n // subscribe peer to new topic\n topicSet.add(id)\n } else {\n // unsubscribe from existing topic\n topicSet.delete(id)\n }\n }\n\n /**\n * Handles a message from a peer\n */\n async processMessage (from: PeerId, msg: Message): Promise<void> {\n if (this.components.peerId.equals(from) && !this.emitSelf) {\n return\n }\n\n // Ensure the message is valid before processing it\n try {\n await this.validate(from, msg)\n } catch (err: any) {\n this.log('Message is invalid, dropping it. %O', err)\n return\n }\n\n if (this.subscriptions.has(msg.topic)) {\n const isFromSelf = this.components.peerId.equals(from)\n\n if (!isFromSelf || this.emitSelf) {\n super.dispatchEvent(new CustomEvent<Message>('message', {\n detail: msg\n }))\n }\n }\n\n await this.publishMessage(from, msg)\n }\n\n /**\n * The default msgID implementation\n * Child class can override this.\n */\n getMsgId (msg: Message): Promise<Uint8Array> | Uint8Array {\n const signaturePolicy = this.globalSignaturePolicy\n switch (signaturePolicy) {\n case 'StrictSign':\n if (msg.type !== 'signed') {\n throw new InvalidMessageError('Message type should be \"signed\" when signature policy is StrictSign but it was not')\n }\n\n if (msg.sequenceNumber == null) {\n throw new InvalidMessageError('Need sequence number when signature policy is StrictSign but it was missing')\n }\n\n if (msg.key == null) {\n throw new InvalidMessageError('Need key when signature policy is StrictSign but it was missing')\n }\n\n return msgId(msg.key, msg.sequenceNumber)\n case 'StrictNoSign':\n return noSignMsgId(msg.data)\n default:\n throw new InvalidMessageError('Cannot get message id: unhandled signature policy')\n }\n }\n\n /**\n * Whether to accept a message from a peer\n * Override to create a gray list\n */\n acceptFrom (id: PeerId): boolean {\n return true\n }\n\n /**\n * Decode Uint8Array into an RPC object.\n * This can be override to use a custom router protobuf.\n */\n abstract decodeRpc (bytes: Uint8Array | Uint8ArrayList): PubSubRPC\n\n /**\n * Encode RPC object into a Uint8Array.\n * This can be override to use a custom router protobuf.\n */\n abstract encodeRpc (rpc: PubSubRPC): Uint8Array\n\n /**\n * Encode RPC object into a Uint8Array.\n * This can be override to use a custom router protobuf.\n */\n abstract encodeMessage (rpc: PubSubRPCMessage): Uint8Array\n\n /**\n * Send an rpc object to a peer\n */\n send (peer: PeerId, data: { messages?: Message[], subscriptions?: string[], subscribe?: boolean }): void {\n const { messages, subscriptions, subscribe } = data\n\n this.sendRpc(peer, {\n subscriptions: (subscriptions ?? []).map(str => ({ topic: str, subscribe: Boolean(subscribe) })),\n messages: (messages ?? []).map(toRpcMessage)\n })\n }\n\n /**\n * Send an rpc object to a peer\n */\n sendRpc (peer: PeerId, rpc: PubSubRPC): void {\n const peerStreams = this.peers.get(peer)\n\n if (peerStreams == null) {\n this.log.error('Cannot send RPC to %p as there are no streams to it available', peer)\n\n return\n }\n\n if (!peerStreams.isWritable) {\n this.log.error('Cannot send RPC to %p as there is no outbound stream to it available', peer)\n\n return\n }\n\n peerStreams.write(this.encodeRpc(rpc))\n }\n\n /**\n * Validates the given message. The signature will be checked for authenticity.\n * Throws an error on invalid messages\n */\n async validate (from: PeerId, message: Message): Promise<void> {\n const signaturePolicy = this.globalSignaturePolicy\n switch (signaturePolicy) {\n case 'StrictNoSign':\n if (message.type !== 'unsigned') {\n throw new InvalidMessageError('Message type should be \"unsigned\" when signature policy is StrictNoSign but it was not')\n }\n\n // @ts-expect-error should not be present\n if (message.signature != null) {\n throw new InvalidMessageError('StrictNoSigning: signature should not be present')\n }\n\n // @ts-expect-error should not be present\n if (message.key != null) {\n throw new InvalidMessageError('StrictNoSigning: key should not be present')\n }\n\n // @ts-expect-error should not be present\n if (message.sequenceNumber != null) {\n throw new InvalidMessageError('StrictNoSigning: seqno should not be present')\n }\n break\n case 'StrictSign':\n if (message.type !== 'signed') {\n throw new InvalidMessageError('Message type should be \"signed\" when signature policy is StrictSign but it was not')\n }\n\n if (message.signature == null) {\n throw new InvalidMessageError('StrictSigning: Signing required and no signature was present')\n }\n\n if (message.sequenceNumber == null) {\n throw new InvalidMessageError('StrictSigning: Signing required and no sequenceNumber was present')\n }\n\n if (!(await verifySignature(message, this.encodeMessage.bind(this)))) {\n throw new InvalidMessageError('StrictSigning: Invalid message signature')\n }\n\n break\n default:\n throw new InvalidMessageError('Cannot validate message: unhandled signature policy')\n }\n\n const validatorFn = this.topicValidators.get(message.topic)\n if (validatorFn != null) {\n const result = await validatorFn(from, message)\n if (result === TopicValidatorResult.Reject || result === TopicValidatorResult.Ignore) {\n throw new InvalidMessageError('Message validation failed')\n }\n }\n }\n\n /**\n * Normalizes the message and signs it, if signing is enabled.\n * Should be used by the routers to create the message to send.\n */\n async buildMessage (message: { from: PeerId, topic: string, data: Uint8Array, sequenceNumber: bigint }): Promise<Message> {\n const signaturePolicy = this.globalSignaturePolicy\n switch (signaturePolicy) {\n case 'StrictSign':\n return signMessage(this.components.privateKey, message, this.encodeMessage.bind(this))\n case 'StrictNoSign':\n return Promise.resolve({\n type: 'unsigned',\n ...message\n })\n default:\n throw new InvalidMessageError('Cannot build message: unhandled signature policy')\n }\n }\n\n // API METHODS\n\n /**\n * Get a list of the peer-ids that are subscribed to one topic.\n */\n getSubscribers (topic: string): PeerId[] {\n if (!this.started) {\n throw new NotStartedError('not started yet')\n }\n\n if (topic == null) {\n throw new InvalidParametersError('Topic is required')\n }\n\n const peersInTopic = this.topics.get(topic.toString())\n\n if (peersInTopic == null) {\n return []\n }\n\n return Array.from(peersInTopic.values())\n }\n\n /**\n * Publishes messages to all subscribed peers\n */\n async publish (topic: string, data?: Uint8Array): Promise<PublishResult> {\n if (!this.started) {\n throw new Error('Pubsub has not started')\n }\n\n const message = {\n from: this.components.peerId,\n topic,\n data: data ?? new Uint8Array(0),\n sequenceNumber: randomSeqno()\n }\n\n this.log('publish topic: %s from: %p data: %m', topic, message.from, message.data)\n\n const rpcMessage = await this.buildMessage(message)\n let emittedToSelf = false\n\n // dispatch the event if we are interested\n if (this.emitSelf) {\n if (this.subscriptions.has(topic)) {\n emittedToSelf = true\n super.dispatchEvent(new CustomEvent<Message>('message', {\n detail: rpcMessage\n }))\n }\n }\n\n // send to all the other peers\n const result = await this.publishMessage(this.components.peerId, rpcMessage)\n\n if (emittedToSelf) {\n result.recipients = [...result.recipients, this.components.peerId]\n }\n\n return result\n }\n\n /**\n * Overriding the implementation of publish should handle the appropriate algorithms for the publish/subscriber implementation.\n * For example, a Floodsub implementation might simply publish each message to each topic for every peer.\n *\n * `sender` might be this peer, or we might be forwarding a message on behalf of another peer, in which case sender\n * is the peer we received the message from, which may not be the peer the message was created by.\n */\n abstract publishMessage (sender: PeerId, message: Message): Promise<PublishResult>\n\n /**\n * Subscribes to a given topic.\n */\n subscribe (topic: string): void {\n if (!this.started) {\n throw new Error('Pubsub has not started')\n }\n\n this.log('subscribe to topic: %s', topic)\n\n if (!this.subscriptions.has(topic)) {\n this.subscriptions.add(topic)\n\n for (const peerId of this.peers.keys()) {\n this.send(peerId, { subscriptions: [topic], subscribe: true })\n }\n }\n }\n\n /**\n * Unsubscribe from the given topic\n */\n unsubscribe (topic: string): void {\n if (!this.started) {\n throw new Error('Pubsub is not started')\n }\n\n super.removeEventListener(topic)\n\n const wasSubscribed = this.subscriptions.has(topic)\n\n this.log('unsubscribe from %s - am subscribed %s', topic, wasSubscribed)\n\n if (wasSubscribed) {\n this.subscriptions.delete(topic)\n\n for (const peerId of this.peers.keys()) {\n this.send(peerId, { subscriptions: [topic], subscribe: false })\n }\n }\n }\n\n /**\n * Get the list of topics which the peer is subscribed to.\n */\n getTopics (): string[] {\n if (!this.started) {\n throw new Error('Pubsub is not started')\n }\n\n return Array.from(this.subscriptions)\n }\n\n getPeers (): PeerId[] {\n if (!this.started) {\n throw new Error('Pubsub is not started')\n }\n\n return Array.from(this.peers.keys())\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 { Stream } from './connection.js'\nimport type { TypedEventTarget } from './event-target.js'\nimport type { PublicKey } from './keys.js'\nimport type { PeerId } from './peer-id.js'\nimport type { Pushable } from 'it-pushable'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * On the producing side:\n * - Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * - Enforce the fields to be present, reject otherwise.\n * - Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign'\n\n/**\n * On the producing side:\n * - Build messages without the signature, key, from and seqno fields.\n * - The corresponding protobuf key-value pairs are absent from the marshaled message, not just empty.\n *\n * On the consuming side:\n * - Enforce the fields to be absent, reject otherwise.\n * - Propagate only if the fields are absent, reject otherwise.\n * - A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface SignedMessage {\n type: 'signed'\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber: bigint\n signature: Uint8Array\n key: PublicKey\n}\n\nexport interface UnsignedMessage {\n type: 'unsigned'\n topic: string\n data: Uint8Array\n}\n\nexport type Message = SignedMessage | UnsignedMessage\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends TypedEventTarget<PeerStreamEvents> {\n id: PeerId\n protocol: string\n outboundStream?: Pushable<Uint8ArrayList>\n inboundStream?: AsyncIterable<Uint8ArrayList>\n isWritable: boolean\n\n close(): void\n write(buf: Uint8Array | Uint8ArrayList): void\n attachInboundStream(stream: Stream): AsyncIterable<Uint8ArrayList>\n attachOutboundStream(stream: Stream): Promise<Pushable<Uint8ArrayList>>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\nexport interface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent<SubscriptionChangeData>\n message: CustomEvent<Message>\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport enum TopicValidatorResult {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n Accept = 'accept',\n /**\n * The message is neither delivered nor forwarded to the network\n */\n Ignore = 'ignore',\n /**\n * The message is considered invalid, and it should be rejected\n */\n Reject = 'reject'\n}\n\nexport interface TopicValidatorFn {\n (peer: PeerId, message: Message): TopicValidatorResult | Promise<TopicValidatorResult>\n}\n\n/**\n * @deprecated This will be removed from `@libp2p/interface` in a future release, pubsub implementations should declare their own types\n */\nexport interface PubSub<Events extends Record<string, any> = PubSubEvents> extends TypedEventTarget<Events> {\n /**\n * The global signature policy controls whether or not we sill send and receive\n * signed or unsigned messages.\n *\n * Signed messages prevent spoofing message senders and should be preferred to\n * using unsigned messages.\n */\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n\n /**\n * A list of multicodecs that contain the pubsub protocol name.\n */\n multicodecs: string[]\n\n /**\n * Pubsub routers support message validators per topic, which will validate the message\n * before its propagations. They are stored in a map where keys are the topic name and\n * values are the validators.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const validateMessage = (msgTopic, msg) => {\n * const input = uint8ArrayToString(msg.data)\n * const validInputs = ['a', 'b', 'c']\n *\n * if (!validInputs.includes(input)) {\n * throw new Error('no valid input received')\n * }\n * }\n * libp2p.pubsub.topicValidators.set(topic, validateMessage)\n * ```\n */\n topicValidators: Map<string, TopicValidatorFn>\n\n getPeers(): PeerId[]\n\n /**\n * Gets a list of topics the node is subscribed to.\n *\n * ```TypeScript\n * const topics = libp2p.pubsub.getTopics()\n * ```\n */\n getTopics(): string[]\n\n /**\n * Subscribes to a pubsub topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const handler = (msg) => {\n * if (msg.topic === topic) {\n * // msg.data - pubsub data received\n * }\n * }\n *\n * libp2p.pubsub.addEventListener('message', handler)\n * libp2p.pubsub.subscribe(topic)\n * ```\n */\n subscribe(topic: string): void\n\n /**\n * Unsubscribes from a pubsub topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const handler = (msg) => {\n * // msg.data - pubsub data received\n * }\n *\n * libp2p.pubsub.removeEventListener(topic handler)\n * libp2p.pubsub.unsubscribe(topic)\n * ```\n */\n unsubscribe(topic: string): void\n\n /**\n * Gets a list of the PeerIds that are subscribed to one topic.\n *\n * @example\n *\n * ```TypeScript\n * const peerIds = libp2p.pubsub.getSubscribers(topic)\n * ```\n */\n getSubscribers(topic: string): PeerId[]\n\n /**\n * Publishes messages to the given topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const data = uint8ArrayFromString('data')\n *\n * await libp2p.pubsub.publish(topic, data)\n * ```\n */\n publish(topic: string, data: Uint8Array): Promise<PublishResult>\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent<never>\n 'stream:outbound': CustomEvent<never>\n close: CustomEvent<never>\n}\n\n/**\n * All Pubsub implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const pubSubSymbol = Symbol.for('@libp2p/pubsub')\n\n/**\n * Returns true if the passed argument is a PubSub implementation\n */\nexport function isPubSub (obj?: any): obj is PubSub {\n return Boolean(obj?.[pubSubSymbol])\n}\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 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 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 { 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 * Adds types to the EventTarget class. 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 * etc\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", "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'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest<typeof code, number> {\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\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\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\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\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 { 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): Promise<Uint8Array> {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign'])\n\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, msg.subarray())\n\n return new Uint8Array(signature, 0, signature.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify'])\n\n return crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, sig, msg.subarray())\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 } 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): Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data)\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): Promise<Uint8Array> {\n return hashAndSign(this.jwk, message)\n }\n}\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\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): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be 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);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + 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/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\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;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\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): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\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 = {};\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 should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\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 function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\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>> extends 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 super();\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: Input): this {\n aexists(this);\n data = toBytes(data);\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 setBigUint64(view, 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 should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should 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;\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://datatracker.ietf.org/doc/html/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, 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);\nexport class SHA256 extends HashMD<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\n constructor(outputLen: number = 32) {\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\nexport class SHA224 extends SHA256 {\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\nexport class SHA512 extends HashMD<SHA512> {\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 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(outputLen: number = 64) {\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\nexport class SHA384 extends SHA512 {\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\nexport class SHA512_224 extends SHA512 {\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\nexport class SHA512_256 extends SHA512 {\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.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\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 = /* @__PURE__ */ createHasher(() => new SHA512_256());\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 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = 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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\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// 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 abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\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(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\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\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// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([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// 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\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike<number>) => Uint8Array.from(arr); // another shortcut\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, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\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 = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), 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++ >= 1000) throw new Error('drbg: tried 1000 values');\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\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\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", "/**\n * Utils for modular division and finite fields.\n * A finite field over 11 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 { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\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 * TODO: remove.\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\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 // Throw if root^2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\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 if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n}\n\n// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16<T>(Fp: IField<T>, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n// const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n// const c3 = Fp.sqrt(Fp.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n// let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n// const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n// let tv4 = Fp.mul(c3, tv1); // 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// return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\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 if (P < BigInt(3)) 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. 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) not implemented, see above\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 isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\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 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): 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 MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\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\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\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'>>;\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) 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 * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\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, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\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 * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\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.CURVE.n)\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 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 { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nfunction constTimeNegate<T extends Group<T>>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport type 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 return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF<T extends Group<T>> = {\n constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group<T>[];\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\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 function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T> {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = 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 elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\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 * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.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, 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(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\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 W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const wo = calcWOpts(W, 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 return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, 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\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\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 private keys / bigints)\n */\nexport function pippenger<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n scalars: bigint[]\n): T {\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 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 T;\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<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n windowSize: number\n): (scalars: bigint[]) => T {\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 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: T) => {\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[]): T => {\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\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\nimport { Field, FpInvertBatch, mod } from './modular.ts';\n// prettier-ignore\nimport {\n abool, aInRange, bytesToHex, bytesToNumberLE, concatBytes,\n ensureBytes, memoized, numberToBytesLE, validateObject,\n type FHash, type Hex\n} from './utils.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/** Edwards curves must declare params a & d. */\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\nexport type CurveTypeWithLength = Readonly<CurveType & { nByteLength: number; nBitLength: number }>;\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType): CurveTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n _setWindowSize(windowSize: number): void;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n precompute: (windowSize?: number, point?: ExtPointType) => ExtPointType;\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\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(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n function isEdValidXY(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\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(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.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 // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint 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 { ex: x, ey: y, ez: 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 ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\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 { ex: X, ey: Y, ez: Z, et: 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 ExtPointType {\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 readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n\n constructor(ex: bigint, ey: bigint, ez: bigint, et: bigint) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez, true);\n aCoordinate('t', et);\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\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 aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.ez)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: 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.ex), this.ey, this.ez, modP(-this.et));\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 { ex: X1, ey: Y1, ez: 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 aextpoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: 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 private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([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 const n = scalar;\n aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.is0() || n === _1n) return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, 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.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[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('pointHex.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('Point.fromHex: 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('Point.fromHex: 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 static fromPrivateKey(privKey: Hex): Point {\n const { scalar } = getPrivateScalar(privKey);\n return G.multiply(scalar); // reduced one call of `toRawBytes`\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(bytesToNumberLE(hash));\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = Fp.BYTES;\n key = ensureBytes('private key', key, len);\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 = ensureBytes('hashed private key', cHash(key), 2 * len);\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(key: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(key);\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\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(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, len);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = bytesToNumberLE(sig.slice(len, 2 * 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.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), 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().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point: ExtPointType = Point.BASE): ExtPointType {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\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';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { type AffinePoint, type Group, pippenger } from './abstract/curve.ts';\nimport { type CurveFn, type ExtPointType, twistedEdwards } from './abstract/edwards.ts';\nimport {\n createHasher,\n expand_message_xmd,\n type Hasher,\n type htfBasicOpts,\n type HTFMethod,\n} from './abstract/hash-to-curve.ts';\nimport { Field, FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.ts';\nimport { montgomery, type CurveFn as XCurveFn } from './abstract/montgomery.ts';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n type Hex,\n numberToBytesLE,\n} from './abstract/utils.ts';\n\n// 2n**255n - 19n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\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\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\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_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// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_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\n/** Weird / bogus points, useful for debugging. */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Removing Fp.create() will still work, and is 10% faster on sign\n a: Fp.create(BigInt(-1)),\n // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 2n**255n - 19n\n Fp,\n // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n h: _8n,\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\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 utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\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 randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\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\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _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// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _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\nexport const ed25519_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\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: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\n\nfunction aristp(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\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) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\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): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\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.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint 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 ExtendedPoint,\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 RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n private readonly ep: ExtendedPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep: ExtendedPoint) {\n this.ep = ep;\n }\n\n static fromAffine(ap: AffinePoint<bigint>): RistPoint {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\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 * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\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: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\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(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\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) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n static msm(points: RistPoint[], scalars: bigint[]): RistPoint {\n const Fn = Field(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return pippenger(RistPoint, Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\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 numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\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: RistPoint): boolean {\n aristp(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\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 add(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255 from\n * [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nexport const RistrettoPoint: typeof RistPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n/**\n * hash-to-curve for ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B).\n */\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts): RistPoint => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\n/** @deprecated */\nexport const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint =\n hashToRistretto255; // legacy\n", "import { ed25519 as ed } from '@noble/curves/ed25519'\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\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\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\n/**\n * Generate keypair from a 32 byte uint8array\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\nexport function hashAndSign (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 function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\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 { 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 { ensureEd25519Key } from './utils.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey as Ed25519PublicKeyInterface, Ed25519PrivateKey as Ed25519PrivateKeyInterface } 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): boolean {\n return crypto.hashAndVerify(this.raw, sig, data)\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): Uint8Array {\n return crypto.hashAndSign(this.raw, message)\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 {} // eslint-disable-line no-empty-function\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, type EncodeFunction, type DecodeFunction, type 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", "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 } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\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 { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { sha256 } from '@noble/hashes/sha256'\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", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\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 } 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): boolean | Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data)\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): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.jwk, message)\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 { 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): 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\n const keys = await exportKey(pair)\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): 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\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\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): 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\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\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, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC<T extends Hash<T>> extends 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: Input) {\n super();\n ahash(hash);\n const key = toBytes(_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: Input): 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);\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: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\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 splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts;\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\nexport type Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n toAffine(iz?: T): AffinePoint<T>;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n msm(points: ProjPointType<T>[], scalars: bigint[]): ProjPointType<T>;\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nexport type CurvePointsTypeWithLength<T> = Readonly<\n CurvePointsType<T> & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>): CurvePointsTypeWithLength<T> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"splitScalar\": function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\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(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula. Takes x, returns y\u00B2.\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\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, a)), b); // x\u00B3 + a * x + b\n }\n\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 // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (isBytes(key)) key = bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\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 { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, 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 ax = Fp.mul(x, iz);\n const ay = 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: ax, y: ay };\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 (CURVE.allowInfinityPoint && !Fp.is0(p.py)) 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 // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\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 /**\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 ProjPointType<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 readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\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 const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\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 * 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 */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\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) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: 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 /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\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 { px: X1, py: Y1, pz: 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 { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: 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() {\n return this.equals(Point.ZERO);\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\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 private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n /** See docs for {@link EndomorphismOpts} */\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\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, n: N } = CURVE;\n aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\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 toAffine(iz?: T): AffinePoint<T> {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(\n curve: CurveType\n): Readonly<CurveType & { nByteLength: number; nBitLength: number }> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = bytesToNumberBE(tail);\n if (!inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\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 normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = getMinHashLength(CURVE.n);\n return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private 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(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(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: PrivKey | PubKey): boolean | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\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 CURVE.bits2int ||\n function (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 - nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = bitMask(nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, nByteLength);\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 // NOTE: we cannot assume here that msgHash 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 function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 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(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: 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 function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\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 const s = modN(ik * modN(m + r * d)); // Not using blinding here\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 = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. 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: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\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 if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\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, opts.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, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.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, opts.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, opts.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", "/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n", "/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\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 = secp256k1P;\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(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\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(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\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.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)();\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: 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 aInRange('x', x, _1n, secp256k1P); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\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 modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).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: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(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 const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\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(numTo32b(modN(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: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\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 (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\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';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\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/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\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 { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { SigningError, VerificationError } from '../../errors.js'\nimport { isPromise } from '../../util.js'\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): Uint8Array | Promise<Uint8Array> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new SigningError(String(err))\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\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): boolean | Promise<boolean> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new VerificationError(String(err))\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\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 } 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): boolean {\n return hashAndVerify(this._key, sig, data)\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): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.raw, message)\n }\n}\n", "import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\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 const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\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.ProjectivePoint.fromHex(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.randomPrivateKey()\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 { 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 { mapIterable, peerIdFromString } from './util.js'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * We can't use PeerIds as set entries because set entries 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 { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set<string>\n\n constructor (set?: PeerSet | Iterable<PeerId>) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator<PeerId> {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const peerId = peerIdFromString(str)\n\n predicate(peerId, peerId, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator<PeerId> {\n return mapIterable<string, PeerId>(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n\nexport function peerSet (): PeerSet {\n return new PeerSet()\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", "/**\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 { DeferredPromise } from 'p-defer'\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: DeferredPromise<void>\n private haveNext: DeferredPromise<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 EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\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", "// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n", "import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n id: options.id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n", "import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 0, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n\n queue.setPriority('\uD83E\uDD80', 2);\n ```\n\n In this case, the promise function with `id: '\uD83E\uDD80'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 1, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84');\n queue.add(async () => '\uD83E\uDD84', {priority: 0});\n\n queue.setPriority('\uD83E\uDD80', -1);\n ```\n Here, the promise function with `id: '\uD83E\uDD80'` executes last.\n */\n setPriority(id, priority) {\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // In case `id` is not defined.\n options.id ??= (this.#idAssigner++).toString();\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\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() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is 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 promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n", "\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator <T> (obj: AsyncIterable<T>): AsyncIterator<T>\nexport function getIterator <T> (obj: AsyncIterator<T>): AsyncIterator<T>\nexport function getIterator <T> (obj: Iterable<T>): Iterator<T>\nexport function getIterator <T> (obj: Iterator<T>): Iterator<T>\nexport function getIterator <T> (obj: any): AsyncIterator<T> | Iterator <T>\nexport function getIterator <T> (obj: any): AsyncIterator<T> | Iterator <T> {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]()\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]()\n }\n if (typeof obj.next === 'function') {\n return obj // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable')\n}\n", "export 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 { getIterator } from 'get-iterator'\nimport { isPromise } from './is-promise.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { Source } from 'it-stream-types'\n\nexport function closeSource (source: Source<unknown>, log: Logger): void {\n const res = getIterator(source).return?.()\n\n if (isPromise(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err)\n })\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\n/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError'\n code = 'ERR_UNEXPECTED_EOF'\n}\n", "export function isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n", "import * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { MAX_DATA_LENGTH } from './constants.js'\nimport { InvalidDataLengthError } from './errors.js'\nimport { isAsyncIterable } from './utils.js'\nimport type { EncoderOptions, LengthEncoderFunction } from './index.js'\nimport type { Source } from 'it-stream-types'\n\n// Helper function to validate the chunk size against maxDataLength\nfunction validateMaxDataLength (chunk: Uint8Array | Uint8ArrayList, maxDataLength: number): void {\n if (chunk.byteLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long')\n }\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = varint.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n varint.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (source: Iterable<Uint8ArrayList | Uint8Array>, options?: EncoderOptions): Generator<Uint8Array, void, undefined>\nexport function encode (source: Source<Uint8ArrayList | Uint8Array>, options?: EncoderOptions): AsyncGenerator<Uint8Array, void, undefined>\nexport function encode (source: Source<Uint8ArrayList | Uint8Array>, options?: EncoderOptions): Generator<Uint8Array, void, undefined> | AsyncGenerator<Uint8Array, void, undefined> {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n function * maybeYield (chunk: Uint8Array | Uint8ArrayList): Generator<Uint8Array, void, undefined> {\n validateMaxDataLength(chunk, maxDataLength)\n\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\n }\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const chunk of source) {\n yield * maybeYield(chunk)\n }\n })()\n }\n\n return (function * () {\n for (const chunk of source) {\n yield * maybeYield(chunk)\n }\n })()\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n validateMaxDataLength(chunk, maxDataLength)\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n", "/* eslint max-depth: [\"error\", 6] */\n\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { MAX_DATA_LENGTH, MAX_LENGTH_LENGTH } from './constants.js'\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError, UnexpectedEOFError } from './errors.js'\nimport { isAsyncIterable } from './utils.js'\nimport type { DecoderOptions, LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source } from 'it-stream-types'\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = varint.decode(buf)\n defaultDecoder.bytes = varint.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (source: Iterable<Uint8ArrayList | Uint8Array>, options?: DecoderOptions): Generator<Uint8ArrayList, void, unknown>\nexport function decode (source: Source<Uint8ArrayList | Uint8Array>, options?: DecoderOptions): AsyncGenerator<Uint8ArrayList, void, unknown>\nexport function decode (source: Source<Uint8ArrayList | Uint8Array>, options?: DecoderOptions): Generator<Uint8ArrayList, void, unknown> | AsyncGenerator<Uint8ArrayList, void, unknown> {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n function * maybeYield (): Generator<Uint8ArrayList> {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer)\n\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length')\n }\n\n if (dataLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new InvalidDataLengthLengthError('Message length length too long')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n }\n\n return (function * () {\n for (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n}\n\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number): void => { byteLength = l }\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n })\n}\n", "import { TypedEventEmitter } from '@libp2p/interface'\nimport { closeSource } from '@libp2p/utils/close-source'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport { pushable } from 'it-pushable'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { ComponentLogger, Logger, Stream, PeerId, PeerStreamEvents } from '@libp2p/interface'\nimport type { DecoderOptions as LpDecoderOptions } from 'it-length-prefixed'\nimport type { Pushable } from 'it-pushable'\n\nexport interface PeerStreamsInit {\n id: PeerId\n protocol: string\n}\n\nexport interface PeerStreamsComponents {\n logger: ComponentLogger\n}\n\nexport interface DecoderOptions extends LpDecoderOptions {\n // other custom options we might want for `attachInboundStream`\n}\n\n/**\n * Thin wrapper around a peer's inbound / outbound pubsub streams\n */\nexport class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {\n public readonly id: PeerId\n public readonly protocol: string\n /**\n * Write stream - it's preferable to use the write method\n */\n public outboundStream?: Pushable<Uint8ArrayList>\n /**\n * Read stream\n */\n public inboundStream?: AsyncIterable<Uint8ArrayList>\n /**\n * The raw outbound stream, as retrieved from conn.newStream\n */\n private _rawOutboundStream?: Stream\n /**\n * The raw inbound stream, as retrieved from the callback from libp2p.handle\n */\n private _rawInboundStream?: Stream\n /**\n * An AbortController for controlled shutdown of the inbound stream\n */\n private readonly _inboundAbortController: AbortController\n private closed: boolean\n private readonly log: Logger\n\n constructor (components: PeerStreamsComponents, init: PeerStreamsInit) {\n super()\n\n this.log = components.logger.forComponent('libp2p-pubsub:peer-streams')\n this.id = init.id\n this.protocol = init.protocol\n\n this._inboundAbortController = new AbortController()\n this.closed = false\n }\n\n /**\n * Do we have a connection to read from?\n */\n get isReadable (): boolean {\n return Boolean(this.inboundStream)\n }\n\n /**\n * Do we have a connection to write on?\n */\n get isWritable (): boolean {\n return Boolean(this.outboundStream)\n }\n\n /**\n * Send a message to this peer.\n * Throws if there is no `stream` to write to available.\n */\n write (data: Uint8Array | Uint8ArrayList): void {\n if (this.outboundStream == null) {\n const id = this.id.toString()\n throw new Error('No writable connection to ' + id)\n }\n\n this.outboundStream.push(data instanceof Uint8Array ? new Uint8ArrayList(data) : data)\n }\n\n /**\n * Attach a raw inbound stream and setup a read stream\n */\n attachInboundStream (stream: Stream, decoderOptions?: DecoderOptions): AsyncIterable<Uint8ArrayList> {\n const abortListener = (): void => {\n closeSource(stream.source, this.log)\n }\n\n this._inboundAbortController.signal.addEventListener('abort', abortListener, {\n once: true\n })\n\n // Create and attach a new inbound stream\n // The inbound stream is:\n // - abortable, set to only return on abort, rather than throw\n // - transformed with length-prefix transform\n this._rawInboundStream = stream\n this.inboundStream = pipe(\n this._rawInboundStream,\n (source) => lp.decode(source, decoderOptions)\n )\n\n this.dispatchEvent(new CustomEvent('stream:inbound'))\n return this.inboundStream\n }\n\n /**\n * Attach a raw outbound stream and setup a write stream\n */\n async attachOutboundStream (stream: Stream): Promise<Pushable<Uint8ArrayList>> {\n // If an outbound stream already exists, gently close it\n const _prevStream = this.outboundStream\n if (this.outboundStream != null) {\n // End the stream without emitting a close event\n this.outboundStream.end()\n }\n\n this._rawOutboundStream = stream\n this.outboundStream = pushable<Uint8ArrayList>({\n onEnd: (shouldEmit) => {\n // close writable side of the stream if it exists\n this._rawOutboundStream?.closeWrite()\n .catch(err => {\n this.log('error closing outbound stream', err)\n })\n\n this._rawOutboundStream = undefined\n this.outboundStream = undefined\n if (shouldEmit != null) {\n this.dispatchEvent(new CustomEvent('close'))\n }\n }\n })\n\n pipe(\n this.outboundStream,\n (source) => lp.encode(source),\n this._rawOutboundStream\n ).catch((err: Error) => {\n this.log.error(err)\n })\n\n // Only emit if the connection is new\n if (_prevStream == null) {\n this.dispatchEvent(new CustomEvent('stream:outbound'))\n }\n\n return this.outboundStream\n }\n\n /**\n * Closes the open connection to peer\n */\n close (): void {\n if (this.closed) {\n return\n }\n\n this.closed = true\n\n // End the outbound stream\n if (this.outboundStream != null) {\n this.outboundStream.end()\n }\n // End the inbound stream\n if (this.inboundStream != null) {\n this._inboundAbortController.abort()\n }\n\n this._rawOutboundStream = undefined\n this.outboundStream = undefined\n this._rawInboundStream = undefined\n this.inboundStream = undefined\n this.dispatchEvent(new CustomEvent('close'))\n }\n}\n", "import { randomBytes } from '@libp2p/crypto'\nimport { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { InvalidMessageError } from '@libp2p/interface'\nimport { peerIdFromMultihash, peerIdFromPublicKey } from '@libp2p/peer-id'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Message, PubSubRPCMessage, PublicKey } from '@libp2p/interface'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: PublicKey, seqno: bigint): Uint8Array => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n const keyBytes = publicKeyToProtobuf(key)\n\n const msgId = new Uint8Array(keyBytes.byteLength + seqnoBytes.length)\n msgId.set(keyBytes, 0)\n msgId.set(seqnoBytes, keyBytes.byteLength)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array): Uint8Array | Promise<Uint8Array> => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set<number> | number[], b: Set<number> | number[]): boolean => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function <T> (maybeArray: T | T[]): T[] {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nconst isSigned = async (message: PubSubRPCMessage): Promise<boolean> => {\n if ((message.sequenceNumber == null) || (message.from == null) || (message.signature == null)) {\n return false\n }\n // if a public key is present in the `from` field, the message should be signed\n const fromID = peerIdFromMultihash(Digest.decode(message.from))\n if (fromID.publicKey != null) {\n return true\n }\n\n if (message.key != null) {\n const signingKey = message.key\n const signingID = peerIdFromPublicKey(publicKeyFromProtobuf(signingKey))\n\n return signingID.equals(fromID)\n }\n\n return false\n}\n\nexport const toMessage = async (message: PubSubRPCMessage): Promise<Message> => {\n if (message.from == null) {\n throw new InvalidMessageError('RPC message was missing from')\n }\n\n if (!await isSigned(message)) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n const from = peerIdFromMultihash(Digest.decode(message.from))\n const key = message.key ?? from.publicKey\n\n if (key == null) {\n throw new InvalidMessageError('RPC message was missing public key')\n }\n\n const msg: Message = {\n type: 'signed',\n from,\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber ?? new Uint8Array(0)),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n key: key instanceof Uint8Array ? publicKeyFromProtobuf(key) : key\n }\n\n return msg\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.toMultihash().bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n\n key: message.key ? publicKeyToProtobuf(message.key) : undefined\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n", "import { peerIdFromPrivateKey } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toRpcMessage } from './utils.js'\nimport type { PeerId, PrivateKey, PubSubRPCMessage, PublicKey, SignedMessage } from '@libp2p/interface'\n\nexport const SignPrefix = uint8ArrayFromString('libp2p-pubsub:')\n\n/**\n * Signs the provided message with the given `peerId`\n */\nexport async function signMessage (privateKey: PrivateKey, message: { from: PeerId, topic: string, data: Uint8Array, sequenceNumber: bigint }, encode: (rpc: PubSubRPCMessage) => Uint8Array): Promise<SignedMessage> {\n // @ts-expect-error signature field is missing, added below\n const outputMessage: SignedMessage = {\n type: 'signed',\n topic: message.topic,\n data: message.data,\n sequenceNumber: message.sequenceNumber,\n from: peerIdFromPrivateKey(privateKey)\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n const bytes = uint8ArrayConcat([\n SignPrefix,\n encode(toRpcMessage(outputMessage)).subarray()\n ])\n\n outputMessage.signature = await privateKey.sign(bytes)\n outputMessage.key = privateKey.publicKey\n\n return outputMessage\n}\n\n/**\n * Verifies the signature of the given message\n */\nexport async function verifySignature (message: SignedMessage, encode: (rpc: PubSubRPCMessage) => Uint8Array): Promise<boolean> {\n if (message.type !== 'signed') {\n throw new Error('Message type must be \"signed\" to be verified')\n }\n\n if (message.signature == null) {\n throw new Error('Message must contain a signature to be verified')\n }\n\n if (message.from == null) {\n throw new Error('Message must contain a from property to be verified')\n }\n\n // Get message sans the signature\n const bytes = uint8ArrayConcat([\n SignPrefix,\n encode({\n ...toRpcMessage(message),\n signature: undefined,\n key: undefined\n }).subarray()\n ])\n\n // Get the public key\n const pubKey = messagePublicKey(message)\n\n // verify the base message\n return pubKey.verify(bytes, message.signature)\n}\n\n/**\n * Returns the PublicKey associated with the given message.\n * If no valid PublicKey can be retrieved an error will be returned.\n */\nexport function messagePublicKey (message: SignedMessage): PublicKey {\n if (message.type !== 'signed') {\n throw new Error('Message type must be \"signed\" to have a public key')\n }\n\n // should be available in the from property of the message (peer id)\n if (message.from == null) {\n throw new Error('Could not get the public key from the originator id')\n }\n\n if (message.key != null) {\n return message.key\n }\n\n if (message.from.publicKey != null) {\n return message.from.publicKey\n }\n\n // We couldn't validate pubkey is from the originator, error\n throw new Error('Could not get the public key from the originator id')\n}\n"],
|
5
|
-
"mappings": ";iqBAAA,IAAAA,GAAAC,GAAA,CAAAC,G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B,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,uBAAuB,EAGzC,MAAM,oBAAoBA,CAAK,EAE/B,IAAMuB,EAAgB,KAAK,cAAc,IAAIvB,CAAK,EAIlD,GAFA,KAAK,IAAI,yCAA0CA,EAAOuB,CAAa,EAEnEA,EAAe,CACjB,KAAK,cAAc,OAAOvB,CAAK,EAE/B,QAAWnB,KAAU,KAAK,MAAM,KAAI,EAClC,KAAK,KAAKA,EAAQ,CAAE,cAAe,CAACmB,CAAK,EAAG,UAAW,EAAK,CAAE,CAElE,CACF,CAKA,WAAS,CACP,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAO,MAAM,KAAK,KAAK,aAAa,CACtC,CAEA,UAAQ,CACN,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAO,MAAM,KAAK,KAAK,MAAM,KAAI,CAAE,CACrC",
|
6
|
-
"names": ["require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "i", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "length", "j", "index_exports", "__export", "PubSubBaseProtocol", "peerIdSymbol", "TopicValidatorResult", "pubSubSymbol", "InvalidParametersError", "message", "InvalidPublicKeyError", "InvalidMultihashError", "message", "InvalidMessageError", "message", "NotStartedError", "message", "UnsupportedKeyTypeError", "message", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "options", "list", "callback", "event", "result", "once", "detail", "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", "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", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "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", "publicKey", "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", "hashAndVerify", "crypto", "isBytes", "a", "anumber", "n", "abytes", "b", "lengths", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "abytes", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "Hash", "createHasher", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "aexists", "toBytes", "abytes", "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", "SHA256", "HashMD", "outputLen", "SHA256_IV", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA512", "HashMD", "outputLen", "SHA512_IV", "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", "sha256", "createHasher", "SHA256", "sha512", "createHasher", "SHA512", "_0n", "_1n", "isBytes", "a", "abytes", "item", "abool", "title", "value", "numberToHexUnpadded", "num", "hex", "hexToNumber", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "bytesToNumberBE", "bytesToNumberLE", "numberToBytesBE", "n", "len", "numberToBytesLE", "ensureBytes", "title", "hex", "expectedLength", "res", "hexToBytes", "e", "isBytes", "len", "concatBytes", "arrays", "sum", "i", "a", "abytes", "pad", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "u8n", "len", "u8fr", "arr", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "v", "k", "i", "reset", "h", "b", "reseed", "seed", "gen", "out", "sl", "concatBytes", "pred", "res", "validatorFns", "val", "isBytes", "object", "validateObject", "validators", "optValidators", "checkField", "fieldName", "type", "isOptional", "checkVal", "memoized", "fn", "map", "arg", "args", "val", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_8n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "res", "_0n", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "sqrt3mod4", "Fp", "p1div4", "_4n", "root", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "tonelliShanks", "P", "Q", "S", "Z", "_Fp", "Field", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "i", "t_tmp", "exponent", "FpSqrt", "_3n", "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", "ORDER", "bitLen", "isLE", "redef", "_0n", "BITS", "BYTES", "sqrtP", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "b", "c", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "constTimeNegate", "condition", "item", "neg", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "validateMSMPoints", "points", "c", "p", "i", "validateMSMScalars", "scalars", "field", "s", "pointPrecomputes", "pointWindowSizes", "getW", "P", "wNAF", "elm", "d", "base", "precomputes", "f", "wo", "offsetF", "acc", "transform", "comp", "prev", "pippenger", "fieldN", "plength", "slength", "zero", "bitLen", "MASK", "buckets", "lastBits", "sum", "j", "scalar", "resI", "sumI", "validateBasic", "curve", "validateField", "validateObject", "nLength", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "Fn", "Field", "isEdValidXY", "x", "y", "x2", "y2", "left", "right", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "abool", "aCoordinate", "title", "n", "banZero", "min", "aInRange", "aextpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "ex", "ey", "ez", "et", "points", "toInv", "FpInvertBatch", "i", "scalars", "pippenger", "windowSize", "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", "acc", "I", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getPrivateScalar", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "getExtendedPublicKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "_8n", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "PUBLIC_KEY_BYTE_LENGTH", "hashAndVerify", "publicKey", "sig", "msg", "ed25519", "Ed25519PublicKey", "key", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "hashAndVerify", "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", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "randomBytes", "length", "InvalidParametersError", "VerificationError", "message", "WebCryptoMissingError", "webcrypto_browser_default", "win", "nativeCrypto", "WebCryptoMissingError", "webcrypto_default", "webcrypto_browser_default", "utils_exports", "__export", "MAX_RSA_KEY_SIZE", "generateRSAKeyPair", "jwkToJWKKeyPair", "jwkToPkcs1", "jwkToPkix", "jwkToRSAPrivateKey", "pkcs1MessageToJwk", "pkcs1MessageToRSAPrivateKey", "pkcs1ToJwk", "pkcs1ToRSAPrivateKey", "pkixMessageToJwk", "pkixMessageToRSAPublicKey", "pkixToJwk", "pkixToRSAPublicKey", "sha256", "RSAPublicKey", "jwk", "digest", "utils_exports", "CID", "base58btc", "key", "equals", "data", "sig", "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", "pair", "webcrypto_default", "keys", "exportKey", "hashAndSign", "key", "msg", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "exportKey", "pair", "InvalidParametersError", "rsaKeySize", "jwk", "fromString", "HMAC", "Hash", "hash", "_key", "ahash", "key", "toBytes", "blockLen", "pad", "clean", "buf", "aexists", "out", "abytes", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "validateSigVerOpts", "opts", "abool", "validatePointOpts", "curve", "validateBasic", "validateObject", "endo", "Fp", "a", "DERErr", "m", "DER", "tag", "data", "E", "dataLen", "len", "numberToHexUnpadded", "lenLen", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "num", "_0n", "hex", "bytesToNumberBE", "int", "tlv", "ensureBytes", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "numToSizedHex", "size", "bytesToHex", "numberToBytesBE", "_1n", "_2n", "_3n", "_4n", "weierstrassPoints", "CURVE", "Fn", "Field", "toBytes", "_c", "point", "_isCompressed", "concatBytes", "fromBytes", "bytes", "tail", "x", "y", "weierstrassEquation", "x2", "x3", "isValidXY", "left", "right", "_4a3", "_27b2", "isWithinCurveOrder", "inRange", "normPrivateKeyToScalar", "key", "lengths", "nByteLength", "wrapPrivateKey", "N", "isBytes", "mod", "aInRange", "aprjpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "px", "py", "pz", "i", "points", "toInv", "FpInvertBatch", "P", "privateKey", "scalars", "pippenger", "windowSize", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "n", "sc", "I", "k1neg", "k1", "k2neg", "k2", "k1p", "k2p", "d", "scalar", "fake", "f1p", "f2p", "f", "Q", "G", "mul", "sum", "cofactor", "isTorsionFree", "clearCofactor", "isCompressed", "nBitLength", "wNAF", "validateOpts", "weierstrass", "curveDef", "CURVE_ORDER", "compressedLen", "uncompressedLen", "modN", "invN", "invert", "cat", "head", "y2", "sqrtError", "suffix", "isYOdd", "cl", "ul", "isBiggerThanHalfOrder", "number", "HALF", "normalizeS", "s", "slcNum", "from", "to", "Signature", "r", "recovery", "l", "msgHash", "rec", "h", "bits2int_modN", "radj", "prefix", "R", "ir", "u1", "u2", "hexToBytes", "utils", "getMinHashLength", "mapHashToField", "getPublicKey", "isProbPub", "item", "fpl", "compLen", "uncompLen", "getSharedSecret", "privateA", "publicB", "bits2int", "delta", "ORDER_MASK", "bitMask", "int2octets", "prepSig", "defaultSigOpts", "k", "hash", "randomBytes", "lowS", "prehash", "ent", "h1int", "seedArgs", "e", "seed", "k2sig", "kBytes", "ik", "q", "normS", "defaultVerOpts", "sign", "privKey", "C", "createHmacDrbg", "verify", "signature", "publicKey", "sg", "format", "isHex", "isObj", "_sig", "derError", "is", "getHash", "hash", "key", "msgs", "hmac", "concatBytes", "randomBytes", "createCurve", "curveDef", "defHash", "create", "weierstrass", "secp256k1P", "secp256k1N", "_0n", "_1n", "_2n", "divNearest", "a", "b", "sqrtMod", "y", "P", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "secp256k1", "createCurve", "k", "n", "a1", "b1", "a2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "sha256", "isPromise", "thing", "hashAndVerify", "key", "sig", "msg", "p", "sha256", "isPromise", "digest", "secp256k1", "err", "VerificationError", "Secp256k1PublicKey", "key", "validateSecp256k1PublicKey", "compressSecp256k1PublicKey", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "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", "peerIdFromPublicKey", "publicKey", "Ed25519PeerId", "Secp256k1PeerId", "RSAPeerId", "UnsupportedKeyTypeError", "peerIdFromPrivateKey", "privateKey", "peerIdFromMultihash", "multihash", "isSha256Multihash", "isIdentityMultihash", "publicKeyFromMultihash", "url", "toString", "URLPeerId", "InvalidMultihashError", "isIdentityMultihash", "multihash", "identity", "isSha256Multihash", "sha256", "mapIterable", "iter", "map", "iterator", "next", "val", "peerIdFromString", "str", "multihash", "decode", "base58btc", "peerIdFromMultihash", "PeerMap", "map", "key", "value", "peer", "mapIterable", "val", "fn", "PeerSet", "_PeerSet", "set", "key", "peer", "mapIterable", "val", "peerId", "peerIdFromString", "predicate", "str", "other", "output", "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", "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", "import_index", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "PriorityQueue", "#queue", "run", "options", "element", "index", "lowerBound", "a", "b", "id", "priority", "item", "PQueue", "EventEmitter", "#carryoverConcurrencyCount", "#isIntervalIgnored", "#intervalCount", "#intervalCap", "#interval", "#intervalEnd", "#intervalId", "#timeoutId", "#queue", "#queueClass", "#pending", "#concurrency", "#isPaused", "#throwOnTimeout", "#idAssigner", "options", "PriorityQueue", "#doesIntervalAllowAnother", "#doesConcurrentAllowAnother", "#next", "#tryToStartAnother", "#onResumeInterval", "#onInterval", "#initializeIntervalIfNeeded", "#isIntervalPaused", "now", "delay", "canInitializeInterval", "job", "#processQueue", "newConcurrency", "#throwOnAbort", "signal", "_resolve", "reject", "id", "priority", "function_", "resolve", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "#onEvent", "limit", "event", "filter", "listener", "getIterator", "obj", "isPromise", "thing", "closeSource", "source", "log", "res", "getIterator", "isPromise", "err", "InvalidMessageLengthError", "InvalidDataLengthError", "InvalidDataLengthLengthError", "UnexpectedEOFError", "isAsyncIterable", "thing", "validateMaxDataLength", "chunk", "maxDataLength", "InvalidDataLengthError", "defaultEncoder", "length", "lengthLength", "encodingLength", "lengthBuf", "allocUnsafe", "encode", "source", "options", "encodeLength", "maybeYield", "isAsyncIterable", "Uint8ArrayList", "ReadMode", "defaultDecoder", "buf", "length", "decode", "encodingLength", "source", "options", "buffer", "Uint8ArrayList", "mode", "dataLength", "lengthDecoder", "maxLengthLength", "maxDataLength", "maybeYield", "InvalidMessageLengthError", "InvalidDataLengthError", "dataLengthLength", "err", "InvalidDataLengthLengthError", "data", "isAsyncIterable", "UnexpectedEOFError", "reader", "byteLength", "varByteSource", "done", "value", "l", "PeerStreams", "TypedEventEmitter", "components", "init", "data", "id", "Uint8ArrayList", "stream", "decoderOptions", "abortListener", "closeSource", "pipe", "source", "decode", "_prevStream", "pushable", "shouldEmit", "err", "encode", "randomSeqno", "toString", "randomBytes", "msgId", "key", "seqno", "seqnoBytes", "fromString", "keyBytes", "publicKeyToProtobuf", "noSignMsgId", "data", "sha256", "ensureArray", "maybeArray", "isSigned", "message", "fromID", "peerIdFromMultihash", "decode", "signingKey", "peerIdFromPublicKey", "publicKeyFromProtobuf", "toMessage", "InvalidMessageError", "from", "key", "bigIntFromBytes", "toRpcMessage", "bigIntToBytes", "publicKeyToProtobuf", "num", "str", "fromString", "toString", "SignPrefix", "fromString", "signMessage", "privateKey", "message", "encode", "outputMessage", "peerIdFromPrivateKey", "bytes", "concat", "toRpcMessage", "verifySignature", "messagePublicKey", "PubSubBaseProtocol", "TypedEventEmitter", "components", "props", "multicodecs", "globalSignaturePolicy", "canRelayMessage", "emitSelf", "messageProcessingConcurrency", "maxInboundStreams", "maxOutboundStreams", "ensureArray", "PeerMap", "PQueue", "registrar", "multicodec", "topology", "id", "peerStreams", "data", "stream", "connection", "peerId", "peer", "inboundStream", "err", "conn", "sub", "protocol", "existing", "PeerStreams", "peers", "pipe", "source", "rpcMsg", "messages", "msg", "from", "rpc", "subscriptions", "subOpt", "topic", "subscribe", "message", "toMessage", "t", "topicSet", "PeerSet", "InvalidMessageError", "msgId", "noSignMsgId", "str", "toRpcMessage", "verifySignature", "validatorFn", "result", "TopicValidatorResult", "signMessage", "NotStartedError", "InvalidParametersError", "peersInTopic", "randomSeqno", "rpcMessage", "emittedToSelf", "wasSubscribed"]
|
3
|
+
"sources": ["../../../node_modules/eventemitter3/index.js", "../src/index.ts", "../../interface/src/peer-id.ts", "../../interface/src/pubsub.ts", "../../interface/src/errors.ts", "../../../node_modules/main-event/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/crypto.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/abstract/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", "../../crypto/src/keys/keys.ts", "../../crypto/src/random-bytes.ts", "../../crypto/src/keys/rsa/utils.ts", "../../../node_modules/@noble/hashes/src/sha256.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/_shortw_utils.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-collections/src/util.ts", "../../peer-collections/src/map.ts", "../../peer-collections/src/set.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../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", "../../../node_modules/eventemitter3/index.mjs", "../../../node_modules/p-timeout/index.js", "../../../node_modules/p-queue/dist/lower-bound.js", "../../../node_modules/p-queue/dist/priority-queue.js", "../../../node_modules/p-queue/dist/index.js", "../../../node_modules/get-iterator/src/index.ts", "../../utils/src/is-promise.ts", "../../utils/src/close-source.ts", "../../../node_modules/it-length-prefixed/src/errors.ts", "../../../node_modules/it-length-prefixed/src/utils.ts", "../../../node_modules/it-length-prefixed/src/encode.ts", "../../../node_modules/it-length-prefixed/src/decode.ts", "../src/peer-streams.ts", "../src/utils.ts", "../src/sign.ts"],
|
4
|
+
"sourcesContent": ["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "/**\n * @packageDocumentation\n *\n * A set of components to be extended in order to create a pubsub implementation.\n *\n * @example\n *\n * ```TypeScript\n * import { PubSubBaseProtocol } from '@libp2p/pubsub'\n * import type { PubSubRPC, PublishResult, PubSubRPCMessage, PeerId, Message } from '@libp2p/interface'\n * import type { Uint8ArrayList } from 'uint8arraylist'\n *\n * class MyPubsubImplementation extends PubSubBaseProtocol {\n * decodeRpc (bytes: Uint8Array | Uint8ArrayList): PubSubRPC {\n * throw new Error('Not implemented')\n * }\n *\n * encodeRpc (rpc: PubSubRPC): Uint8Array {\n * throw new Error('Not implemented')\n * }\n *\n * encodeMessage (rpc: PubSubRPCMessage): Uint8Array {\n * throw new Error('Not implemented')\n * }\n *\n * async publishMessage (sender: PeerId, message: Message): Promise<PublishResult> {\n * throw new Error('Not implemented')\n * }\n * }\n * ```\n */\n\nimport { TopicValidatorResult, InvalidMessageError, NotStartedError, InvalidParametersError } from '@libp2p/interface'\nimport { PeerMap, PeerSet } from '@libp2p/peer-collections'\nimport { pipe } from 'it-pipe'\nimport { TypedEventEmitter } from 'main-event'\nimport Queue from 'p-queue'\nimport { PeerStreams as PeerStreamsImpl } from './peer-streams.js'\nimport {\n signMessage,\n verifySignature\n} from './sign.js'\nimport { toMessage, ensureArray, noSignMsgId, msgId, toRpcMessage, randomSeqno } from './utils.js'\nimport type { PubSub, Message, StrictNoSign, StrictSign, PubSubInit, PubSubEvents, PeerStreams, PubSubRPCMessage, PubSubRPC, PubSubRPCSubscription, SubscriptionChangeData, PublishResult, TopicValidatorFn, ComponentLogger, Logger, Connection, PeerId, PrivateKey, IncomingStreamData } from '@libp2p/interface'\nimport type { Registrar } from '@libp2p/interface-internal'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PubSubComponents {\n peerId: PeerId\n privateKey: PrivateKey\n registrar: Registrar\n logger: ComponentLogger\n}\n\n/**\n * PubSubBaseProtocol handles the peers and connections logic for pubsub routers\n * and specifies the API that pubsub routers should have.\n */\nexport abstract class PubSubBaseProtocol<Events extends Record<string, any> = PubSubEvents> extends TypedEventEmitter<Events> implements PubSub<Events> {\n protected log: Logger\n\n public started: boolean\n /**\n * Map of topics to which peers are subscribed to\n */\n public topics: Map<string, PeerSet>\n /**\n * List of our subscriptions\n */\n public subscriptions: Set<string>\n /**\n * Map of peer streams\n */\n public peers: PeerMap<PeerStreams>\n /**\n * The signature policy to follow by default\n */\n public globalSignaturePolicy: typeof StrictNoSign | typeof StrictSign\n /**\n * If router can relay received messages, even if not subscribed\n */\n public canRelayMessage: boolean\n /**\n * if publish should emit to self, if subscribed\n */\n public emitSelf: boolean\n /**\n * Topic validator map\n *\n * Keyed by topic\n * Topic validators are functions with the following input:\n */\n public topicValidators: Map<string, TopicValidatorFn>\n public queue: Queue\n public multicodecs: string[]\n public components: PubSubComponents\n\n private _registrarTopologyIds: string[] | undefined\n protected enabled: boolean\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n\n constructor (components: PubSubComponents, props: PubSubInit) {\n super()\n\n const {\n multicodecs = [],\n globalSignaturePolicy = 'StrictSign',\n canRelayMessage = false,\n emitSelf = false,\n messageProcessingConcurrency = 10,\n maxInboundStreams = 1,\n maxOutboundStreams = 1\n } = props\n\n this.log = components.logger.forComponent('libp2p:pubsub')\n this.components = components\n this.multicodecs = ensureArray(multicodecs)\n this.enabled = props.enabled !== false\n this.started = false\n this.topics = new Map()\n this.subscriptions = new Set()\n this.peers = new PeerMap<PeerStreams>()\n this.globalSignaturePolicy = globalSignaturePolicy === 'StrictNoSign' ? 'StrictNoSign' : 'StrictSign'\n this.canRelayMessage = canRelayMessage\n this.emitSelf = emitSelf\n this.topicValidators = new Map()\n this.queue = new Queue({ concurrency: messageProcessingConcurrency })\n this.maxInboundStreams = maxInboundStreams\n this.maxOutboundStreams = maxOutboundStreams\n\n this._onIncomingStream = this._onIncomingStream.bind(this)\n this._onPeerConnected = this._onPeerConnected.bind(this)\n this._onPeerDisconnected = this._onPeerDisconnected.bind(this)\n }\n\n // LIFECYCLE METHODS\n\n /**\n * Register the pubsub protocol onto the libp2p node.\n */\n async start (): Promise<void> {\n if (this.started || !this.enabled) {\n return\n }\n\n this.log('starting')\n\n const registrar = this.components.registrar\n // Incoming streams\n // Called after a peer dials us\n await Promise.all(this.multicodecs.map(async multicodec => {\n await registrar.handle(multicodec, this._onIncomingStream, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams\n })\n }))\n\n // register protocol with topology\n // Topology callbacks called on connection manager changes\n const topology = {\n onConnect: this._onPeerConnected,\n onDisconnect: this._onPeerDisconnected\n }\n this._registrarTopologyIds = await Promise.all(this.multicodecs.map(async multicodec => registrar.register(multicodec, topology)))\n\n this.log('started')\n this.started = true\n }\n\n /**\n * Unregister the pubsub protocol and the streams with other peers will be closed.\n */\n async stop (): Promise<void> {\n if (!this.started || !this.enabled) {\n return\n }\n\n const registrar = this.components.registrar\n\n // unregister protocol and handlers\n if (this._registrarTopologyIds != null) {\n this._registrarTopologyIds?.forEach(id => {\n registrar.unregister(id)\n })\n }\n\n await Promise.all(this.multicodecs.map(async multicodec => {\n await registrar.unhandle(multicodec)\n }))\n\n this.log('stopping')\n for (const peerStreams of this.peers.values()) {\n peerStreams.close()\n }\n\n this.peers.clear()\n this.subscriptions = new Set()\n this.started = false\n this.log('stopped')\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * On an inbound stream opened\n */\n protected _onIncomingStream (data: IncomingStreamData): void {\n const { stream, connection } = data\n const peerId = connection.remotePeer\n\n if (stream.protocol == null) {\n stream.abort(new Error('Stream was not multiplexed'))\n return\n }\n\n const peer = this.addPeer(peerId, stream.protocol)\n const inboundStream = peer.attachInboundStream(stream)\n\n this.processMessages(peerId, inboundStream, peer)\n .catch(err => { this.log(err) })\n }\n\n /**\n * Registrar notifies an established connection with pubsub protocol\n */\n protected _onPeerConnected (peerId: PeerId, conn: Connection): void {\n this.log('connected %p', peerId)\n\n // if this connection is already in use for pubsub, ignore it\n if (conn.streams.find(stream => stream.direction === 'outbound' && stream.protocol != null && this.multicodecs.includes(stream.protocol)) != null) {\n this.log('outbound pubsub streams already present on connection from %p', peerId)\n return\n }\n\n void Promise.resolve().then(async () => {\n try {\n const stream = await conn.newStream(this.multicodecs)\n\n if (stream.protocol == null) {\n stream.abort(new Error('Stream was not multiplexed'))\n return\n }\n\n const peer = this.addPeer(peerId, stream.protocol)\n await peer.attachOutboundStream(stream)\n } catch (err: any) {\n this.log.error(err)\n }\n\n // Immediately send my own subscriptions to the newly established conn\n this.send(peerId, { subscriptions: Array.from(this.subscriptions).map(sub => sub.toString()), subscribe: true })\n })\n .catch(err => {\n this.log.error(err)\n })\n }\n\n /**\n * Registrar notifies a closing connection with pubsub protocol\n */\n protected _onPeerDisconnected (peerId: PeerId, conn?: Connection): void {\n this.log('connection ended %p', peerId)\n this._removePeer(peerId)\n }\n\n /**\n * Notifies the router that a peer has been connected\n */\n addPeer (peerId: PeerId, protocol: string): PeerStreams {\n const existing = this.peers.get(peerId)\n\n // If peer streams already exists, do nothing\n if (existing != null) {\n return existing\n }\n\n // else create a new peer streams\n this.log('new peer %p', peerId)\n\n const peerStreams: PeerStreams = new PeerStreamsImpl(this.components, {\n id: peerId,\n protocol\n })\n\n this.peers.set(peerId, peerStreams)\n peerStreams.addEventListener('close', () => this._removePeer(peerId), {\n once: true\n })\n\n return peerStreams\n }\n\n /**\n * Notifies the router that a peer has been disconnected\n */\n protected _removePeer (peerId: PeerId): PeerStreams | undefined {\n const peerStreams = this.peers.get(peerId)\n if (peerStreams == null) {\n return\n }\n\n // close peer streams\n peerStreams.close()\n\n // delete peer streams\n this.log('delete peer %p', peerId)\n this.peers.delete(peerId)\n\n // remove peer from topics map\n for (const peers of this.topics.values()) {\n peers.delete(peerId)\n }\n\n return peerStreams\n }\n\n // MESSAGE METHODS\n\n /**\n * Responsible for processing each RPC message received by other peers.\n */\n async processMessages (peerId: PeerId, stream: AsyncIterable<Uint8ArrayList>, peerStreams: PeerStreams): Promise<void> {\n try {\n await pipe(\n stream,\n async (source) => {\n for await (const data of source) {\n const rpcMsg = this.decodeRpc(data)\n const messages: PubSubRPCMessage[] = []\n\n for (const msg of (rpcMsg.messages ?? [])) {\n if (msg.from == null || msg.data == null || msg.topic == null) {\n this.log('message from %p was missing from, data or topic fields, dropping', peerId)\n continue\n }\n\n messages.push({\n from: msg.from,\n data: msg.data,\n topic: msg.topic,\n sequenceNumber: msg.sequenceNumber ?? undefined,\n signature: msg.signature ?? undefined,\n key: msg.key ?? undefined\n })\n }\n\n // Since processRpc may be overridden entirely in unsafe ways,\n // the simplest/safest option here is to wrap in a function and capture all errors\n // to prevent a top-level unhandled exception\n // This processing of rpc messages should happen without awaiting full validation/execution of prior messages\n this.processRpc(peerId, peerStreams, {\n subscriptions: (rpcMsg.subscriptions ?? []).map(sub => ({\n subscribe: Boolean(sub.subscribe),\n topic: sub.topic ?? ''\n })),\n messages\n })\n .catch(err => { this.log(err) })\n }\n }\n )\n } catch (err: any) {\n this._onPeerDisconnected(peerStreams.id, err)\n }\n }\n\n /**\n * Handles an rpc request from a peer\n */\n async processRpc (from: PeerId, peerStreams: PeerStreams, rpc: PubSubRPC): Promise<boolean> {\n if (!this.acceptFrom(from)) {\n this.log('received message from unacceptable peer %p', from)\n return false\n }\n\n this.log('rpc from %p', from)\n\n const { subscriptions, messages } = rpc\n\n if (subscriptions != null && subscriptions.length > 0) {\n this.log('subscription update from %p', from)\n\n // update peer subscriptions\n subscriptions.forEach((subOpt) => {\n this.processRpcSubOpt(from, subOpt)\n })\n\n super.dispatchEvent(new CustomEvent<SubscriptionChangeData>('subscription-change', {\n detail: {\n peerId: peerStreams.id,\n subscriptions: subscriptions.map(({ topic, subscribe }) => ({\n topic: `${topic ?? ''}`,\n subscribe: Boolean(subscribe)\n }))\n }\n }))\n }\n\n if (messages != null && messages.length > 0) {\n this.log('messages from %p', from)\n\n this.queue.addAll(messages.map(message => async () => {\n if (message.topic == null || (!this.subscriptions.has(message.topic) && !this.canRelayMessage)) {\n this.log('received message we didn\\'t subscribe to. Dropping.')\n return false\n }\n\n try {\n const msg = await toMessage(message)\n\n await this.processMessage(from, msg)\n } catch (err: any) {\n this.log.error(err)\n }\n }))\n .catch(err => { this.log(err) })\n }\n\n return true\n }\n\n /**\n * Handles a subscription change from a peer\n */\n processRpcSubOpt (id: PeerId, subOpt: PubSubRPCSubscription): void {\n const t = subOpt.topic\n\n if (t == null) {\n return\n }\n\n let topicSet = this.topics.get(t)\n if (topicSet == null) {\n topicSet = new PeerSet()\n this.topics.set(t, topicSet)\n }\n\n if (subOpt.subscribe === true) {\n // subscribe peer to new topic\n topicSet.add(id)\n } else {\n // unsubscribe from existing topic\n topicSet.delete(id)\n }\n }\n\n /**\n * Handles a message from a peer\n */\n async processMessage (from: PeerId, msg: Message): Promise<void> {\n if (this.components.peerId.equals(from) && !this.emitSelf) {\n return\n }\n\n // Ensure the message is valid before processing it\n try {\n await this.validate(from, msg)\n } catch (err: any) {\n this.log('Message is invalid, dropping it. %O', err)\n return\n }\n\n if (this.subscriptions.has(msg.topic)) {\n const isFromSelf = this.components.peerId.equals(from)\n\n if (!isFromSelf || this.emitSelf) {\n super.dispatchEvent(new CustomEvent<Message>('message', {\n detail: msg\n }))\n }\n }\n\n await this.publishMessage(from, msg)\n }\n\n /**\n * The default msgID implementation\n * Child class can override this.\n */\n getMsgId (msg: Message): Promise<Uint8Array> | Uint8Array {\n const signaturePolicy = this.globalSignaturePolicy\n switch (signaturePolicy) {\n case 'StrictSign':\n if (msg.type !== 'signed') {\n throw new InvalidMessageError('Message type should be \"signed\" when signature policy is StrictSign but it was not')\n }\n\n if (msg.sequenceNumber == null) {\n throw new InvalidMessageError('Need sequence number when signature policy is StrictSign but it was missing')\n }\n\n if (msg.key == null) {\n throw new InvalidMessageError('Need key when signature policy is StrictSign but it was missing')\n }\n\n return msgId(msg.key, msg.sequenceNumber)\n case 'StrictNoSign':\n return noSignMsgId(msg.data)\n default:\n throw new InvalidMessageError('Cannot get message id: unhandled signature policy')\n }\n }\n\n /**\n * Whether to accept a message from a peer\n * Override to create a gray list\n */\n acceptFrom (id: PeerId): boolean {\n return true\n }\n\n /**\n * Decode Uint8Array into an RPC object.\n * This can be override to use a custom router protobuf.\n */\n abstract decodeRpc (bytes: Uint8Array | Uint8ArrayList): PubSubRPC\n\n /**\n * Encode RPC object into a Uint8Array.\n * This can be override to use a custom router protobuf.\n */\n abstract encodeRpc (rpc: PubSubRPC): Uint8Array\n\n /**\n * Encode RPC object into a Uint8Array.\n * This can be override to use a custom router protobuf.\n */\n abstract encodeMessage (rpc: PubSubRPCMessage): Uint8Array\n\n /**\n * Send an rpc object to a peer\n */\n send (peer: PeerId, data: { messages?: Message[], subscriptions?: string[], subscribe?: boolean }): void {\n const { messages, subscriptions, subscribe } = data\n\n this.sendRpc(peer, {\n subscriptions: (subscriptions ?? []).map(str => ({ topic: str, subscribe: Boolean(subscribe) })),\n messages: (messages ?? []).map(toRpcMessage)\n })\n }\n\n /**\n * Send an rpc object to a peer\n */\n sendRpc (peer: PeerId, rpc: PubSubRPC): void {\n const peerStreams = this.peers.get(peer)\n\n if (peerStreams == null) {\n this.log.error('Cannot send RPC to %p as there are no streams to it available', peer)\n\n return\n }\n\n if (!peerStreams.isWritable) {\n this.log.error('Cannot send RPC to %p as there is no outbound stream to it available', peer)\n\n return\n }\n\n peerStreams.write(this.encodeRpc(rpc))\n }\n\n /**\n * Validates the given message. The signature will be checked for authenticity.\n * Throws an error on invalid messages\n */\n async validate (from: PeerId, message: Message): Promise<void> {\n const signaturePolicy = this.globalSignaturePolicy\n switch (signaturePolicy) {\n case 'StrictNoSign':\n if (message.type !== 'unsigned') {\n throw new InvalidMessageError('Message type should be \"unsigned\" when signature policy is StrictNoSign but it was not')\n }\n\n // @ts-expect-error should not be present\n if (message.signature != null) {\n throw new InvalidMessageError('StrictNoSigning: signature should not be present')\n }\n\n // @ts-expect-error should not be present\n if (message.key != null) {\n throw new InvalidMessageError('StrictNoSigning: key should not be present')\n }\n\n // @ts-expect-error should not be present\n if (message.sequenceNumber != null) {\n throw new InvalidMessageError('StrictNoSigning: seqno should not be present')\n }\n break\n case 'StrictSign':\n if (message.type !== 'signed') {\n throw new InvalidMessageError('Message type should be \"signed\" when signature policy is StrictSign but it was not')\n }\n\n if (message.signature == null) {\n throw new InvalidMessageError('StrictSigning: Signing required and no signature was present')\n }\n\n if (message.sequenceNumber == null) {\n throw new InvalidMessageError('StrictSigning: Signing required and no sequenceNumber was present')\n }\n\n if (!(await verifySignature(message, this.encodeMessage.bind(this)))) {\n throw new InvalidMessageError('StrictSigning: Invalid message signature')\n }\n\n break\n default:\n throw new InvalidMessageError('Cannot validate message: unhandled signature policy')\n }\n\n const validatorFn = this.topicValidators.get(message.topic)\n if (validatorFn != null) {\n const result = await validatorFn(from, message)\n if (result === TopicValidatorResult.Reject || result === TopicValidatorResult.Ignore) {\n throw new InvalidMessageError('Message validation failed')\n }\n }\n }\n\n /**\n * Normalizes the message and signs it, if signing is enabled.\n * Should be used by the routers to create the message to send.\n */\n async buildMessage (message: { from: PeerId, topic: string, data: Uint8Array, sequenceNumber: bigint }): Promise<Message> {\n const signaturePolicy = this.globalSignaturePolicy\n switch (signaturePolicy) {\n case 'StrictSign':\n return signMessage(this.components.privateKey, message, this.encodeMessage.bind(this))\n case 'StrictNoSign':\n return Promise.resolve({\n type: 'unsigned',\n ...message\n })\n default:\n throw new InvalidMessageError('Cannot build message: unhandled signature policy')\n }\n }\n\n // API METHODS\n\n /**\n * Get a list of the peer-ids that are subscribed to one topic.\n */\n getSubscribers (topic: string): PeerId[] {\n if (!this.started) {\n throw new NotStartedError('not started yet')\n }\n\n if (topic == null) {\n throw new InvalidParametersError('Topic is required')\n }\n\n const peersInTopic = this.topics.get(topic.toString())\n\n if (peersInTopic == null) {\n return []\n }\n\n return Array.from(peersInTopic.values())\n }\n\n /**\n * Publishes messages to all subscribed peers\n */\n async publish (topic: string, data?: Uint8Array): Promise<PublishResult> {\n if (!this.started) {\n throw new Error('Pubsub has not started')\n }\n\n const message = {\n from: this.components.peerId,\n topic,\n data: data ?? new Uint8Array(0),\n sequenceNumber: randomSeqno()\n }\n\n this.log('publish topic: %s from: %p data: %m', topic, message.from, message.data)\n\n const rpcMessage = await this.buildMessage(message)\n let emittedToSelf = false\n\n // dispatch the event if we are interested\n if (this.emitSelf) {\n if (this.subscriptions.has(topic)) {\n emittedToSelf = true\n super.dispatchEvent(new CustomEvent<Message>('message', {\n detail: rpcMessage\n }))\n }\n }\n\n // send to all the other peers\n const result = await this.publishMessage(this.components.peerId, rpcMessage)\n\n if (emittedToSelf) {\n result.recipients = [...result.recipients, this.components.peerId]\n }\n\n return result\n }\n\n /**\n * Overriding the implementation of publish should handle the appropriate algorithms for the publish/subscriber implementation.\n * For example, a Floodsub implementation might simply publish each message to each topic for every peer.\n *\n * `sender` might be this peer, or we might be forwarding a message on behalf of another peer, in which case sender\n * is the peer we received the message from, which may not be the peer the message was created by.\n */\n abstract publishMessage (sender: PeerId, message: Message): Promise<PublishResult>\n\n /**\n * Subscribes to a given topic.\n */\n subscribe (topic: string): void {\n if (!this.started) {\n throw new Error('Pubsub has not started')\n }\n\n this.log('subscribe to topic: %s', topic)\n\n if (!this.subscriptions.has(topic)) {\n this.subscriptions.add(topic)\n\n for (const peerId of this.peers.keys()) {\n this.send(peerId, { subscriptions: [topic], subscribe: true })\n }\n }\n }\n\n /**\n * Unsubscribe from the given topic\n */\n unsubscribe (topic: string): void {\n if (!this.started) {\n throw new Error('Pubsub is not started')\n }\n\n super.removeEventListener(topic)\n\n const wasSubscribed = this.subscriptions.has(topic)\n\n this.log('unsubscribe from %s - am subscribed %s', topic, wasSubscribed)\n\n if (wasSubscribed) {\n this.subscriptions.delete(topic)\n\n for (const peerId of this.peers.keys()) {\n this.send(peerId, { subscriptions: [topic], subscribe: false })\n }\n }\n }\n\n /**\n * Get the list of topics which the peer is subscribed to.\n */\n getTopics (): string[] {\n if (!this.started) {\n throw new Error('Pubsub is not started')\n }\n\n return Array.from(this.subscriptions)\n }\n\n getPeers (): PeerId[] {\n if (!this.started) {\n throw new Error('Pubsub is not started')\n }\n\n return Array.from(this.peers.keys())\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 { Stream } from './connection.js'\nimport type { PublicKey } from './keys.js'\nimport type { PeerId } from './peer-id.js'\nimport type { Pushable } from 'it-pushable'\nimport type { TypedEventTarget } from 'main-event'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/**\n * On the producing side:\n * - Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * - Enforce the fields to be present, reject otherwise.\n * - Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nexport const StrictSign = 'StrictSign'\n\n/**\n * On the producing side:\n * - Build messages without the signature, key, from and seqno fields.\n * - The corresponding protobuf key-value pairs are absent from the marshaled message, not just empty.\n *\n * On the consuming side:\n * - Enforce the fields to be absent, reject otherwise.\n * - Propagate only if the fields are absent, reject otherwise.\n * - A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nexport const StrictNoSign = 'StrictNoSign'\n\nexport type SignaturePolicy = typeof StrictSign | typeof StrictNoSign\n\nexport interface SignedMessage {\n type: 'signed'\n from: PeerId\n topic: string\n data: Uint8Array\n sequenceNumber: bigint\n signature: Uint8Array\n key: PublicKey\n}\n\nexport interface UnsignedMessage {\n type: 'unsigned'\n topic: string\n data: Uint8Array\n}\n\nexport type Message = SignedMessage | UnsignedMessage\n\nexport interface PubSubRPCMessage {\n from?: Uint8Array\n topic?: string\n data?: Uint8Array\n sequenceNumber?: Uint8Array\n signature?: Uint8Array\n key?: Uint8Array\n}\n\nexport interface PubSubRPCSubscription {\n subscribe?: boolean\n topic?: string\n}\n\nexport interface PubSubRPC {\n subscriptions: PubSubRPCSubscription[]\n messages: PubSubRPCMessage[]\n}\n\nexport interface PeerStreams extends TypedEventTarget<PeerStreamEvents> {\n id: PeerId\n protocol: string\n outboundStream?: Pushable<Uint8ArrayList>\n inboundStream?: AsyncIterable<Uint8ArrayList>\n isWritable: boolean\n\n close(): void\n write(buf: Uint8Array | Uint8ArrayList): void\n attachInboundStream(stream: Stream): AsyncIterable<Uint8ArrayList>\n attachOutboundStream(stream: Stream): Promise<Pushable<Uint8ArrayList>>\n}\n\nexport interface PubSubInit {\n enabled?: boolean\n\n multicodecs?: string[]\n\n /**\n * defines how signatures should be handled\n */\n globalSignaturePolicy?: SignaturePolicy\n\n /**\n * if can relay messages not subscribed\n */\n canRelayMessage?: boolean\n\n /**\n * if publish should emit to self, if subscribed\n */\n emitSelf?: boolean\n\n /**\n * handle this many incoming pubsub messages concurrently\n */\n messageProcessingConcurrency?: number\n\n /**\n * How many parallel incoming streams to allow on the pubsub protocol per-connection\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the pubsub protocol per-connection\n */\n maxOutboundStreams?: number\n}\n\nexport interface Subscription {\n topic: string\n subscribe: boolean\n}\n\nexport interface SubscriptionChangeData {\n peerId: PeerId\n subscriptions: Subscription[]\n}\n\nexport interface PubSubEvents {\n 'subscription-change': CustomEvent<SubscriptionChangeData>\n message: CustomEvent<Message>\n}\n\nexport interface PublishResult {\n recipients: PeerId[]\n}\n\nexport enum TopicValidatorResult {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n Accept = 'accept',\n /**\n * The message is neither delivered nor forwarded to the network\n */\n Ignore = 'ignore',\n /**\n * The message is considered invalid, and it should be rejected\n */\n Reject = 'reject'\n}\n\nexport interface TopicValidatorFn {\n (peer: PeerId, message: Message): TopicValidatorResult | Promise<TopicValidatorResult>\n}\n\n/**\n * @deprecated This will be removed from `@libp2p/interface` in a future release, pubsub implementations should declare their own types\n */\nexport interface PubSub<Events extends Record<string, any> = PubSubEvents> extends TypedEventTarget<Events> {\n /**\n * The global signature policy controls whether or not we sill send and receive\n * signed or unsigned messages.\n *\n * Signed messages prevent spoofing message senders and should be preferred to\n * using unsigned messages.\n */\n globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign\n\n /**\n * A list of multicodecs that contain the pubsub protocol name.\n */\n multicodecs: string[]\n\n /**\n * Pubsub routers support message validators per topic, which will validate the message\n * before its propagations. They are stored in a map where keys are the topic name and\n * values are the validators.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const validateMessage = (msgTopic, msg) => {\n * const input = uint8ArrayToString(msg.data)\n * const validInputs = ['a', 'b', 'c']\n *\n * if (!validInputs.includes(input)) {\n * throw new Error('no valid input received')\n * }\n * }\n * libp2p.pubsub.topicValidators.set(topic, validateMessage)\n * ```\n */\n topicValidators: Map<string, TopicValidatorFn>\n\n getPeers(): PeerId[]\n\n /**\n * Gets a list of topics the node is subscribed to.\n *\n * ```TypeScript\n * const topics = libp2p.pubsub.getTopics()\n * ```\n */\n getTopics(): string[]\n\n /**\n * Subscribes to a pubsub topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const handler = (msg) => {\n * if (msg.topic === topic) {\n * // msg.data - pubsub data received\n * }\n * }\n *\n * libp2p.pubsub.addEventListener('message', handler)\n * libp2p.pubsub.subscribe(topic)\n * ```\n */\n subscribe(topic: string): void\n\n /**\n * Unsubscribes from a pubsub topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const handler = (msg) => {\n * // msg.data - pubsub data received\n * }\n *\n * libp2p.pubsub.removeEventListener(topic handler)\n * libp2p.pubsub.unsubscribe(topic)\n * ```\n */\n unsubscribe(topic: string): void\n\n /**\n * Gets a list of the PeerIds that are subscribed to one topic.\n *\n * @example\n *\n * ```TypeScript\n * const peerIds = libp2p.pubsub.getSubscribers(topic)\n * ```\n */\n getSubscribers(topic: string): PeerId[]\n\n /**\n * Publishes messages to the given topic.\n *\n * @example\n *\n * ```TypeScript\n * const topic = 'topic'\n * const data = uint8ArrayFromString('data')\n *\n * await libp2p.pubsub.publish(topic, data)\n * ```\n */\n publish(topic: string, data: Uint8Array): Promise<PublishResult>\n}\n\nexport interface PeerStreamEvents {\n 'stream:inbound': CustomEvent<never>\n 'stream:outbound': CustomEvent<never>\n close: CustomEvent<never>\n}\n\n/**\n * All Pubsub implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const pubSubSymbol = Symbol.for('@libp2p/pubsub')\n\n/**\n * Returns true if the passed argument is a PubSub implementation\n */\nexport function isPubSub (obj?: any): obj is PubSub {\n return Boolean(obj?.[pubSubSymbol])\n}\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 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 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", "/**\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", "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'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest<typeof code, number> {\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\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\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\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\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 * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\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): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be 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);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + 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/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\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;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\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/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\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): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\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 = {};\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 should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\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 function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\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>> extends 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 super();\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: Input): this {\n aexists(this);\n data = toBytes(data);\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 setBigUint64(view, 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 should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should 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;\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://datatracker.ietf.org/doc/html/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, 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);\nexport class SHA256 extends HashMD<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\n constructor(outputLen: number = 32) {\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\nexport class SHA224 extends SHA256 {\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\nexport class SHA512 extends HashMD<SHA512> {\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 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(outputLen: number = 64) {\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\nexport class SHA384 extends SHA512 {\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\nexport class SHA512_224 extends SHA512 {\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\nexport class SHA512_256 extends SHA512 {\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.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\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 = /* @__PURE__ */ createHasher(() => new SHA512_256());\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 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = 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// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\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// 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 abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\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(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\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\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// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([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// 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\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike<number>) => Uint8Array.from(arr); // another shortcut\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, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\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 = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), 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++ >= 1000) throw new Error('drbg: tried 1000 values');\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\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\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", "/**\n * Utils for modular division and finite fields.\n * A finite field over 11 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 { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\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 * TODO: remove.\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\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 // Throw if root^2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\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 if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n}\n\n// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16<T>(Fp: IField<T>, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n// const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n// const c3 = Fp.sqrt(Fp.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n// let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n// const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n// let tv4 = Fp.mul(c3, tv1); // 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// return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\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 if (P < BigInt(3)) 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. 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) not implemented, see above\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 isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\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 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): 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 MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\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\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\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'>>;\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) 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 * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\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, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\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 * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\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.CURVE.n)\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 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 { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nfunction constTimeNegate<T extends Group<T>>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport type 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 return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF<T extends Group<T>> = {\n constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group<T>[];\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\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 function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T> {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = 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 elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\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 * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.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, 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(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\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 W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const wo = calcWOpts(W, 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 return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, 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\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\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 private keys / bigints)\n */\nexport function pippenger<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n scalars: bigint[]\n): T {\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 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 T;\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<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n windowSize: number\n): (scalars: bigint[]) => T {\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 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: T) => {\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[]): T => {\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\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\nimport { Field, FpInvertBatch, mod } from './modular.ts';\n// prettier-ignore\nimport {\n abool, aInRange, bytesToHex, bytesToNumberLE, concatBytes,\n ensureBytes, memoized, numberToBytesLE, validateObject,\n type FHash, type Hex\n} from './utils.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/** Edwards curves must declare params a & d. */\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\nexport type CurveTypeWithLength = Readonly<CurveType & { nByteLength: number; nBitLength: number }>;\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType): CurveTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n _setWindowSize(windowSize: number): void;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n precompute: (windowSize?: number, point?: ExtPointType) => ExtPointType;\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\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(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n function isEdValidXY(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\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(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.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 // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint 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 { ex: x, ey: y, ez: 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 ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\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 { ex: X, ey: Y, ez: Z, et: 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 ExtPointType {\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 readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n\n constructor(ex: bigint, ey: bigint, ez: bigint, et: bigint) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez, true);\n aCoordinate('t', et);\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\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 aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.ez)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: 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.ex), this.ey, this.ez, modP(-this.et));\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 { ex: X1, ey: Y1, ez: 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 aextpoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: 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 private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([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 const n = scalar;\n aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.is0() || n === _1n) return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, 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.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[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('pointHex.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('Point.fromHex: 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('Point.fromHex: 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 static fromPrivateKey(privKey: Hex): Point {\n const { scalar } = getPrivateScalar(privKey);\n return G.multiply(scalar); // reduced one call of `toRawBytes`\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(bytesToNumberLE(hash));\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = Fp.BYTES;\n key = ensureBytes('private key', key, len);\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 = ensureBytes('hashed private key', cHash(key), 2 * len);\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(key: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(key);\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\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(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, len);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = bytesToNumberLE(sig.slice(len, 2 * 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.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), 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().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point: ExtPointType = Point.BASE): ExtPointType {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\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';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { type AffinePoint, type Group, pippenger } from './abstract/curve.ts';\nimport { type CurveFn, type ExtPointType, twistedEdwards } from './abstract/edwards.ts';\nimport {\n createHasher,\n expand_message_xmd,\n type Hasher,\n type htfBasicOpts,\n type HTFMethod,\n} from './abstract/hash-to-curve.ts';\nimport { Field, FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.ts';\nimport { montgomery, type CurveFn as XCurveFn } from './abstract/montgomery.ts';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n type Hex,\n numberToBytesLE,\n} from './abstract/utils.ts';\n\n// 2n**255n - 19n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\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\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\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_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// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_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\n/** Weird / bogus points, useful for debugging. */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Removing Fp.create() will still work, and is 10% faster on sign\n a: Fp.create(BigInt(-1)),\n // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 2n**255n - 19n\n Fp,\n // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n h: _8n,\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\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 utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\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 randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\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\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _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// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _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\nexport const ed25519_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\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: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\n\nfunction aristp(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\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) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\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): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\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.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint 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 ExtendedPoint,\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 RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n private readonly ep: ExtendedPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep: ExtendedPoint) {\n this.ep = ep;\n }\n\n static fromAffine(ap: AffinePoint<bigint>): RistPoint {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\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 * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\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: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\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(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\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) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n static msm(points: RistPoint[], scalars: bigint[]): RistPoint {\n const Fn = Field(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return pippenger(RistPoint, Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\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 numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\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: RistPoint): boolean {\n aristp(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\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 add(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255 from\n * [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nexport const RistrettoPoint: typeof RistPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n/**\n * hash-to-curve for ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B).\n */\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts): RistPoint => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\n/** @deprecated */\nexport const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint =\n hashToRistretto255; // legacy\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'\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.randomPrivateKey()\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\nfunction 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\nfunction 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 {} // eslint-disable-line no-empty-function\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, type EncodeFunction, type DecodeFunction, type 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", "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 } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\n}\n", "import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { sha256 } from '@noble/hashes/sha256'\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", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\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, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC<T extends Hash<T>> extends 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: Input) {\n super();\n ahash(hash);\n const key = toBytes(_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: Input): 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);\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: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\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 splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts;\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\nexport type Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n toAffine(iz?: T): AffinePoint<T>;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n msm(points: ProjPointType<T>[], scalars: bigint[]): ProjPointType<T>;\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nexport type CurvePointsTypeWithLength<T> = Readonly<\n CurvePointsType<T> & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>): CurvePointsTypeWithLength<T> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"splitScalar\": function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\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(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\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\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula. Takes x, returns y\u00B2.\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\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, a)), b); // x\u00B3 + a * x + b\n }\n\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 // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (isBytes(key)) key = bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\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 { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, 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 ax = Fp.mul(x, iz);\n const ay = 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: ax, y: ay };\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 (CURVE.allowInfinityPoint && !Fp.is0(p.py)) 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 // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\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 /**\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 ProjPointType<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 readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\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 const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\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 * 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 */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\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) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: 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 /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\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 { px: X1, py: Y1, pz: 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 { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: 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() {\n return this.equals(Point.ZERO);\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\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 private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n /** See docs for {@link EndomorphismOpts} */\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\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, n: N } = CURVE;\n aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\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 toAffine(iz?: T): AffinePoint<T> {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(\n curve: CurveType\n): Readonly<CurveType & { nByteLength: number; nBitLength: number }> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = bytesToNumberBE(tail);\n if (!inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\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 normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = getMinHashLength(CURVE.n);\n return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private 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(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(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: PrivKey | PubKey): boolean | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\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 CURVE.bits2int ||\n function (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 - nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = bitMask(nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, nByteLength);\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 // NOTE: we cannot assume here that msgHash 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 function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 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(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: 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 function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\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 const s = modN(ik * modN(m + r * d)); // Not using blinding here\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 = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. 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: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\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 if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\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, opts.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, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.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, opts.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, opts.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", "/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n", "/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\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 = secp256k1P;\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(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\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(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\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.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)();\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: 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 aInRange('x', x, _1n, secp256k1P); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\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 modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).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: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(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 const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\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(numTo32b(modN(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: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\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 (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\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';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\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/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\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 } as const\n ))();\n\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n", "import { secp256k1 as secp } from '@noble/curves/secp256k1'\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).toDERRawBytes()\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).toDERRawBytes()\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 })\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 } 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'\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 const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\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.ProjectivePoint.fromHex(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.randomPrivateKey()\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 { 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 { mapIterable, peerIdFromString } from './util.js'\nimport type { PeerId } from '@libp2p/interface'\n\n/**\n * We can't use PeerIds as set entries because set entries 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 { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n private readonly set: Set<string>\n\n constructor (set?: PeerSet | Iterable<PeerId>) {\n this.set = new Set()\n\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString())\n }\n }\n }\n\n get size (): number {\n return this.set.size\n }\n\n [Symbol.iterator] (): IterableIterator<PeerId> {\n return this.values()\n }\n\n add (peer: PeerId): void {\n this.set.add(peer.toString())\n }\n\n clear (): void {\n this.set.clear()\n }\n\n delete (peer: PeerId): void {\n this.set.delete(peer.toString())\n }\n\n entries (): IterableIterator<[PeerId, PeerId]> {\n return mapIterable<[string, string], [PeerId, PeerId]>(\n this.set.entries(),\n (val) => {\n const peerId = peerIdFromString(val[0])\n\n return [peerId, peerId]\n }\n )\n }\n\n forEach (predicate: (peerId: PeerId, index: PeerId, set: PeerSet) => void): void {\n this.set.forEach((str) => {\n const peerId = peerIdFromString(str)\n\n predicate(peerId, peerId, this)\n })\n }\n\n has (peer: PeerId): boolean {\n return this.set.has(peer.toString())\n }\n\n values (): IterableIterator<PeerId> {\n return mapIterable<string, PeerId>(\n this.set.values(),\n (val) => {\n return peerIdFromString(val)\n }\n )\n }\n\n intersection (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n difference (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId)\n }\n }\n\n return output\n }\n\n union (other: PeerSet): PeerSet {\n const output = new PeerSet()\n\n for (const peerId of other) {\n output.add(peerId)\n }\n\n for (const peerId of this) {\n output.add(peerId)\n }\n\n return output\n }\n}\n\nexport function peerSet (): PeerSet {\n return new PeerSet()\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", "/**\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 EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\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", "// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n", "import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n id: options.id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n", "import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 0, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n\n queue.setPriority('\uD83E\uDD80', 2);\n ```\n\n In this case, the promise function with `id: '\uD83E\uDD80'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '\uD83E\uDD84', {priority: 1});\n queue.add(async () => '\uD83E\uDD80', {priority: 1, id: '\uD83E\uDD80'});\n queue.add(async () => '\uD83E\uDD84');\n queue.add(async () => '\uD83E\uDD84', {priority: 0});\n\n queue.setPriority('\uD83E\uDD80', -1);\n ```\n Here, the promise function with `id: '\uD83E\uDD80'` executes last.\n */\n setPriority(id, priority) {\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // In case `id` is not defined.\n options.id ??= (this.#idAssigner++).toString();\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\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() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is 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 promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n", "\n// If the passed object is an (async) iterable, then get the iterator\n// If it's probably an iterator already (i.e. has next function) return it\n// else throw\nexport function getIterator <T> (obj: AsyncIterable<T>): AsyncIterator<T>\nexport function getIterator <T> (obj: AsyncIterator<T>): AsyncIterator<T>\nexport function getIterator <T> (obj: Iterable<T>): Iterator<T>\nexport function getIterator <T> (obj: Iterator<T>): Iterator<T>\nexport function getIterator <T> (obj: any): AsyncIterator<T> | Iterator <T>\nexport function getIterator <T> (obj: any): AsyncIterator<T> | Iterator <T> {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]()\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]()\n }\n if (typeof obj.next === 'function') {\n return obj // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable')\n}\n", "export 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 { getIterator } from 'get-iterator'\nimport { isPromise } from './is-promise.js'\nimport type { Logger } from '@libp2p/logger'\nimport type { Source } from 'it-stream-types'\n\nexport function closeSource (source: Source<unknown>, log: Logger): void {\n const res = getIterator(source).return?.()\n\n if (isPromise(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err)\n })\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\n/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError'\n code = 'ERR_UNEXPECTED_EOF'\n}\n", "export function isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n", "import * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { MAX_DATA_LENGTH } from './constants.js'\nimport { InvalidDataLengthError } from './errors.js'\nimport { isAsyncIterable } from './utils.js'\nimport type { EncoderOptions, LengthEncoderFunction } from './index.js'\nimport type { Source } from 'it-stream-types'\n\n// Helper function to validate the chunk size against maxDataLength\nfunction validateMaxDataLength (chunk: Uint8Array | Uint8ArrayList, maxDataLength: number): void {\n if (chunk.byteLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long')\n }\n}\n\nconst defaultEncoder: LengthEncoderFunction = (length) => {\n const lengthLength = varint.encodingLength(length)\n const lengthBuf = allocUnsafe(lengthLength)\n\n varint.encode(length, lengthBuf)\n\n defaultEncoder.bytes = lengthLength\n\n return lengthBuf\n}\ndefaultEncoder.bytes = 0\n\nexport function encode (source: Iterable<Uint8ArrayList | Uint8Array>, options?: EncoderOptions): Generator<Uint8Array, void, undefined>\nexport function encode (source: Source<Uint8ArrayList | Uint8Array>, options?: EncoderOptions): AsyncGenerator<Uint8Array, void, undefined>\nexport function encode (source: Source<Uint8ArrayList | Uint8Array>, options?: EncoderOptions): Generator<Uint8Array, void, undefined> | AsyncGenerator<Uint8Array, void, undefined> {\n options = options ?? {}\n\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n function * maybeYield (chunk: Uint8Array | Uint8ArrayList): Generator<Uint8Array, void, undefined> {\n validateMaxDataLength(chunk, maxDataLength)\n\n // length + data\n const length = encodeLength(chunk.byteLength)\n\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length\n } else {\n yield * length\n }\n\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk\n } else {\n yield * chunk\n }\n }\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const chunk of source) {\n yield * maybeYield(chunk)\n }\n })()\n }\n\n return (function * () {\n for (const chunk of source) {\n yield * maybeYield(chunk)\n }\n })()\n}\n\nencode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {\n options = options ?? {}\n const encodeLength = options.lengthEncoder ?? defaultEncoder\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n validateMaxDataLength(chunk, maxDataLength)\n\n return new Uint8ArrayList(\n encodeLength(chunk.byteLength),\n chunk\n )\n}\n", "/* eslint max-depth: [\"error\", 6] */\n\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { MAX_DATA_LENGTH, MAX_LENGTH_LENGTH } from './constants.js'\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError, UnexpectedEOFError } from './errors.js'\nimport { isAsyncIterable } from './utils.js'\nimport type { DecoderOptions, LengthDecoderFunction } from './index.js'\nimport type { Reader } from 'it-reader'\nimport type { Source } from 'it-stream-types'\n\nenum ReadMode {\n LENGTH,\n DATA\n}\n\nconst defaultDecoder: LengthDecoderFunction = (buf) => {\n const length = varint.decode(buf)\n defaultDecoder.bytes = varint.encodingLength(length)\n\n return length\n}\ndefaultDecoder.bytes = 0\n\nexport function decode (source: Iterable<Uint8ArrayList | Uint8Array>, options?: DecoderOptions): Generator<Uint8ArrayList, void, unknown>\nexport function decode (source: Source<Uint8ArrayList | Uint8Array>, options?: DecoderOptions): AsyncGenerator<Uint8ArrayList, void, unknown>\nexport function decode (source: Source<Uint8ArrayList | Uint8Array>, options?: DecoderOptions): Generator<Uint8ArrayList, void, unknown> | AsyncGenerator<Uint8ArrayList, void, unknown> {\n const buffer = new Uint8ArrayList()\n let mode = ReadMode.LENGTH\n let dataLength = -1\n\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH\n\n function * maybeYield (): Generator<Uint8ArrayList> {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer)\n\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length')\n }\n\n if (dataLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long')\n }\n\n const dataLengthLength = lengthDecoder.bytes\n buffer.consume(dataLengthLength)\n\n if (options?.onLength != null) {\n options.onLength(dataLength)\n }\n\n mode = ReadMode.DATA\n } catch (err: any) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new InvalidDataLengthLengthError('Message length length too long')\n }\n\n break\n }\n\n throw err\n }\n }\n\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break\n }\n\n const data = buffer.sublist(0, dataLength)\n buffer.consume(dataLength)\n\n if (options?.onData != null) {\n options.onData(data)\n }\n\n yield data\n\n mode = ReadMode.LENGTH\n }\n }\n }\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n }\n\n return (function * () {\n for (const buf of source) {\n buffer.append(buf)\n\n yield * maybeYield()\n }\n\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input')\n }\n })()\n}\n\ndecode.fromReader = (reader: Reader, options?: DecoderOptions) => {\n let byteLength = 1 // Read single byte chunks until the length is known\n\n const varByteSource = (async function * () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength)\n\n if (done === true) {\n return\n }\n\n if (value != null) {\n yield value\n }\n } catch (err: any) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null }\n }\n throw err\n } finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1\n }\n }\n }())\n\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l: number): void => { byteLength = l }\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n })\n}\n", "import { closeSource } from '@libp2p/utils/close-source'\nimport * as lp from 'it-length-prefixed'\nimport { pipe } from 'it-pipe'\nimport { pushable } from 'it-pushable'\nimport { TypedEventEmitter } from 'main-event'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport type { ComponentLogger, Logger, Stream, PeerId, PeerStreamEvents } from '@libp2p/interface'\nimport type { DecoderOptions as LpDecoderOptions } from 'it-length-prefixed'\nimport type { Pushable } from 'it-pushable'\n\nexport interface PeerStreamsInit {\n id: PeerId\n protocol: string\n}\n\nexport interface PeerStreamsComponents {\n logger: ComponentLogger\n}\n\nexport interface DecoderOptions extends LpDecoderOptions {\n // other custom options we might want for `attachInboundStream`\n}\n\n/**\n * Thin wrapper around a peer's inbound / outbound pubsub streams\n */\nexport class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {\n public readonly id: PeerId\n public readonly protocol: string\n /**\n * Write stream - it's preferable to use the write method\n */\n public outboundStream?: Pushable<Uint8ArrayList>\n /**\n * Read stream\n */\n public inboundStream?: AsyncIterable<Uint8ArrayList>\n /**\n * The raw outbound stream, as retrieved from conn.newStream\n */\n private _rawOutboundStream?: Stream\n /**\n * The raw inbound stream, as retrieved from the callback from libp2p.handle\n */\n private _rawInboundStream?: Stream\n /**\n * An AbortController for controlled shutdown of the inbound stream\n */\n private readonly _inboundAbortController: AbortController\n private closed: boolean\n private readonly log: Logger\n\n constructor (components: PeerStreamsComponents, init: PeerStreamsInit) {\n super()\n\n this.log = components.logger.forComponent('libp2p-pubsub:peer-streams')\n this.id = init.id\n this.protocol = init.protocol\n\n this._inboundAbortController = new AbortController()\n this.closed = false\n }\n\n /**\n * Do we have a connection to read from?\n */\n get isReadable (): boolean {\n return Boolean(this.inboundStream)\n }\n\n /**\n * Do we have a connection to write on?\n */\n get isWritable (): boolean {\n return Boolean(this.outboundStream)\n }\n\n /**\n * Send a message to this peer.\n * Throws if there is no `stream` to write to available.\n */\n write (data: Uint8Array | Uint8ArrayList): void {\n if (this.outboundStream == null) {\n const id = this.id.toString()\n throw new Error('No writable connection to ' + id)\n }\n\n this.outboundStream.push(data instanceof Uint8Array ? new Uint8ArrayList(data) : data)\n }\n\n /**\n * Attach a raw inbound stream and setup a read stream\n */\n attachInboundStream (stream: Stream, decoderOptions?: DecoderOptions): AsyncIterable<Uint8ArrayList> {\n const abortListener = (): void => {\n closeSource(stream.source, this.log)\n }\n\n this._inboundAbortController.signal.addEventListener('abort', abortListener, {\n once: true\n })\n\n // Create and attach a new inbound stream\n // The inbound stream is:\n // - abortable, set to only return on abort, rather than throw\n // - transformed with length-prefix transform\n this._rawInboundStream = stream\n this.inboundStream = pipe(\n this._rawInboundStream,\n (source) => lp.decode(source, decoderOptions)\n )\n\n this.dispatchEvent(new CustomEvent('stream:inbound'))\n return this.inboundStream\n }\n\n /**\n * Attach a raw outbound stream and setup a write stream\n */\n async attachOutboundStream (stream: Stream): Promise<Pushable<Uint8ArrayList>> {\n // If an outbound stream already exists, gently close it\n const _prevStream = this.outboundStream\n if (this.outboundStream != null) {\n // End the stream without emitting a close event\n this.outboundStream.end()\n }\n\n this._rawOutboundStream = stream\n this.outboundStream = pushable<Uint8ArrayList>({\n onEnd: (shouldEmit) => {\n // close writable side of the stream if it exists\n this._rawOutboundStream?.closeWrite()\n .catch(err => {\n this.log('error closing outbound stream', err)\n })\n\n this._rawOutboundStream = undefined\n this.outboundStream = undefined\n if (shouldEmit != null) {\n this.dispatchEvent(new CustomEvent('close'))\n }\n }\n })\n\n pipe(\n this.outboundStream,\n (source) => lp.encode(source),\n this._rawOutboundStream\n ).catch((err: Error) => {\n this.log.error(err)\n })\n\n // Only emit if the connection is new\n if (_prevStream == null) {\n this.dispatchEvent(new CustomEvent('stream:outbound'))\n }\n\n return this.outboundStream\n }\n\n /**\n * Closes the open connection to peer\n */\n close (): void {\n if (this.closed) {\n return\n }\n\n this.closed = true\n\n // End the outbound stream\n if (this.outboundStream != null) {\n this.outboundStream.end()\n }\n // End the inbound stream\n if (this.inboundStream != null) {\n this._inboundAbortController.abort()\n }\n\n this._rawOutboundStream = undefined\n this.outboundStream = undefined\n this._rawInboundStream = undefined\n this.inboundStream = undefined\n this.dispatchEvent(new CustomEvent('close'))\n }\n}\n", "import { randomBytes } from '@libp2p/crypto'\nimport { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { InvalidMessageError } from '@libp2p/interface'\nimport { peerIdFromMultihash, peerIdFromPublicKey } from '@libp2p/peer-id'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Message, PubSubRPCMessage, PublicKey } from '@libp2p/interface'\n\n/**\n * Generate a random sequence number\n */\nexport function randomSeqno (): bigint {\n return BigInt(`0x${uint8ArrayToString(randomBytes(8), 'base16')}`)\n}\n\n/**\n * Generate a message id, based on the `key` and `seqno`\n */\nexport const msgId = (key: PublicKey, seqno: bigint): Uint8Array => {\n const seqnoBytes = uint8ArrayFromString(seqno.toString(16).padStart(16, '0'), 'base16')\n const keyBytes = publicKeyToProtobuf(key)\n\n const msgId = new Uint8Array(keyBytes.byteLength + seqnoBytes.length)\n msgId.set(keyBytes, 0)\n msgId.set(seqnoBytes, keyBytes.byteLength)\n\n return msgId\n}\n\n/**\n * Generate a message id, based on message `data`\n */\nexport const noSignMsgId = (data: Uint8Array): Uint8Array | Promise<Uint8Array> => {\n return sha256.encode(data)\n}\n\n/**\n * Check if any member of the first set is also a member\n * of the second set\n */\nexport const anyMatch = (a: Set<number> | number[], b: Set<number> | number[]): boolean => {\n let bHas\n if (Array.isArray(b)) {\n bHas = (val: number) => b.includes(val)\n } else {\n bHas = (val: number) => b.has(val)\n }\n\n for (const val of a) {\n if (bHas(val)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Make everything an array\n */\nexport const ensureArray = function <T> (maybeArray: T | T[]): T[] {\n if (!Array.isArray(maybeArray)) {\n return [maybeArray]\n }\n\n return maybeArray\n}\n\nconst isSigned = async (message: PubSubRPCMessage): Promise<boolean> => {\n if ((message.sequenceNumber == null) || (message.from == null) || (message.signature == null)) {\n return false\n }\n // if a public key is present in the `from` field, the message should be signed\n const fromID = peerIdFromMultihash(Digest.decode(message.from))\n if (fromID.publicKey != null) {\n return true\n }\n\n if (message.key != null) {\n const signingKey = message.key\n const signingID = peerIdFromPublicKey(publicKeyFromProtobuf(signingKey))\n\n return signingID.equals(fromID)\n }\n\n return false\n}\n\nexport const toMessage = async (message: PubSubRPCMessage): Promise<Message> => {\n if (message.from == null) {\n throw new InvalidMessageError('RPC message was missing from')\n }\n\n if (!await isSigned(message)) {\n return {\n type: 'unsigned',\n topic: message.topic ?? '',\n data: message.data ?? new Uint8Array(0)\n }\n }\n\n const from = peerIdFromMultihash(Digest.decode(message.from))\n const key = message.key ?? from.publicKey\n\n if (key == null) {\n throw new InvalidMessageError('RPC message was missing public key')\n }\n\n const msg: Message = {\n type: 'signed',\n from,\n topic: message.topic ?? '',\n sequenceNumber: bigIntFromBytes(message.sequenceNumber ?? new Uint8Array(0)),\n data: message.data ?? new Uint8Array(0),\n signature: message.signature ?? new Uint8Array(0),\n key: key instanceof Uint8Array ? publicKeyFromProtobuf(key) : key\n }\n\n return msg\n}\n\nexport const toRpcMessage = (message: Message): PubSubRPCMessage => {\n if (message.type === 'signed') {\n return {\n from: message.from.toMultihash().bytes,\n data: message.data,\n sequenceNumber: bigIntToBytes(message.sequenceNumber),\n topic: message.topic,\n signature: message.signature,\n\n key: message.key ? publicKeyToProtobuf(message.key) : undefined\n }\n }\n\n return {\n data: message.data,\n topic: message.topic\n }\n}\n\nexport const bigIntToBytes = (num: bigint): Uint8Array => {\n let str = num.toString(16)\n\n if (str.length % 2 !== 0) {\n str = `0${str}`\n }\n\n return uint8ArrayFromString(str, 'base16')\n}\n\nexport const bigIntFromBytes = (num: Uint8Array): bigint => {\n return BigInt(`0x${uint8ArrayToString(num, 'base16')}`)\n}\n", "import { peerIdFromPrivateKey } from '@libp2p/peer-id'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toRpcMessage } from './utils.js'\nimport type { PeerId, PrivateKey, PubSubRPCMessage, PublicKey, SignedMessage } from '@libp2p/interface'\n\nexport const SignPrefix = uint8ArrayFromString('libp2p-pubsub:')\n\n/**\n * Signs the provided message with the given `peerId`\n */\nexport async function signMessage (privateKey: PrivateKey, message: { from: PeerId, topic: string, data: Uint8Array, sequenceNumber: bigint }, encode: (rpc: PubSubRPCMessage) => Uint8Array): Promise<SignedMessage> {\n // @ts-expect-error signature field is missing, added below\n const outputMessage: SignedMessage = {\n type: 'signed',\n topic: message.topic,\n data: message.data,\n sequenceNumber: message.sequenceNumber,\n from: peerIdFromPrivateKey(privateKey)\n }\n\n // Get the message in bytes, and prepend with the pubsub prefix\n const bytes = uint8ArrayConcat([\n SignPrefix,\n encode(toRpcMessage(outputMessage)).subarray()\n ])\n\n outputMessage.signature = await privateKey.sign(bytes)\n outputMessage.key = privateKey.publicKey\n\n return outputMessage\n}\n\n/**\n * Verifies the signature of the given message\n */\nexport async function verifySignature (message: SignedMessage, encode: (rpc: PubSubRPCMessage) => Uint8Array): Promise<boolean> {\n if (message.type !== 'signed') {\n throw new Error('Message type must be \"signed\" to be verified')\n }\n\n if (message.signature == null) {\n throw new Error('Message must contain a signature to be verified')\n }\n\n if (message.from == null) {\n throw new Error('Message must contain a from property to be verified')\n }\n\n // Get message sans the signature\n const bytes = uint8ArrayConcat([\n SignPrefix,\n encode({\n ...toRpcMessage(message),\n signature: undefined,\n key: undefined\n }).subarray()\n ])\n\n // Get the public key\n const pubKey = messagePublicKey(message)\n\n // verify the base message\n return pubKey.verify(bytes, message.signature)\n}\n\n/**\n * Returns the PublicKey associated with the given message.\n * If no valid PublicKey can be retrieved an error will be returned.\n */\nexport function messagePublicKey (message: SignedMessage): PublicKey {\n if (message.type !== 'signed') {\n throw new Error('Message type must be \"signed\" to have a public key')\n }\n\n // should be available in the from property of the message (peer id)\n if (message.from == null) {\n throw new Error('Could not get the public key from the originator id')\n }\n\n if (message.key != null) {\n return message.key\n }\n\n if (message.from.publicKey != null) {\n return message.from.publicKey\n }\n\n // We couldn't validate pubkey is from the originator, error\n throw new Error('Could not get the public key from the originator id')\n}\n"],
|
5
|
+
"mappings": ";iqBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,cAEA,IAAIC,GAAM,OAAO,UAAU,eACvBC,GAAS,IASb,SAASC,IAAS,CAAC,CASf,OAAO,SACTA,GAAO,UAAY,OAAO,OAAO,IAAI,EAMhC,IAAIA,GAAO,EAAE,YAAWD,GAAS,KAYxC,SAASE,GAAGC,EAAIC,EAASC,EAAM,CAC7B,KAAK,GAAKF,EACV,KAAK,QAAUC,EACf,KAAK,KAAOC,GAAQ,EACtB,CAaA,SAASC,GAAYC,EAASC,EAAOL,EAAIC,EAASC,EAAM,CACtD,GAAI,OAAOF,GAAO,WAChB,MAAM,IAAI,UAAU,iCAAiC,EAGvD,IAAIM,EAAW,IAAIP,GAAGC,EAAIC,GAAWG,EAASF,CAAI,EAC9CK,EAAMV,GAASA,GAASQ,EAAQA,EAEpC,OAAKD,EAAQ,QAAQG,CAAG,EACdH,EAAQ,QAAQG,CAAG,EAAE,GAC1BH,EAAQ,QAAQG,CAAG,EAAI,CAACH,EAAQ,QAAQG,CAAG,EAAGD,CAAQ,EADxBF,EAAQ,QAAQG,CAAG,EAAE,KAAKD,CAAQ,GAD1CF,EAAQ,QAAQG,CAAG,EAAID,EAAUF,EAAQ,gBAI7DA,CACT,CASA,SAASI,GAAWJ,EAASG,EAAK,CAC5B,EAAEH,EAAQ,eAAiB,EAAGA,EAAQ,QAAU,IAAIN,GACnD,OAAOM,EAAQ,QAAQG,CAAG,CACjC,CASA,SAASE,IAAe,CACtB,KAAK,QAAU,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,EACT,CAAC,GAKN,IAAMP,EAAS,MAAM,KAAK,eAAe,KAAK,WAAW,OAAQO,CAAU,EAE3E,OAAIC,IACFR,EAAO,WAAa,CAAC,GAAGA,EAAO,WAAY,KAAK,WAAW,MAAM,GAG5DA,CACT,CAcA,UAAWd,EAAa,CACtB,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,wBAAwB,EAK1C,GAFA,KAAK,IAAI,yBAA0BA,CAAK,EAEpC,CAAC,KAAK,cAAc,IAAIA,CAAK,EAAG,CAClC,KAAK,cAAc,IAAIA,CAAK,EAE5B,QAAWnB,KAAU,KAAK,MAAM,KAAI,EAClC,KAAK,KAAKA,EAAQ,CAAE,cAAe,CAACmB,CAAK,EAAG,UAAW,EAAI,CAAE,CAEjE,CACF,CAKA,YAAaA,EAAa,CACxB,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,uBAAuB,EAGzC,MAAM,oBAAoBA,CAAK,EAE/B,IAAMuB,EAAgB,KAAK,cAAc,IAAIvB,CAAK,EAIlD,GAFA,KAAK,IAAI,yCAA0CA,EAAOuB,CAAa,EAEnEA,EAAe,CACjB,KAAK,cAAc,OAAOvB,CAAK,EAE/B,QAAWnB,KAAU,KAAK,MAAM,KAAI,EAClC,KAAK,KAAKA,EAAQ,CAAE,cAAe,CAACmB,CAAK,EAAG,UAAW,EAAK,CAAE,CAElE,CACF,CAKA,WAAS,CACP,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAO,MAAM,KAAK,KAAK,aAAa,CACtC,CAEA,UAAQ,CACN,GAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAO,MAAM,KAAK,KAAK,MAAM,KAAI,CAAE,CACrC",
|
6
|
+
"names": ["require_eventemitter3", "__commonJSMin", "exports", "module", "has", "prefix", "Events", "EE", "fn", "context", "once", "addListener", "emitter", "event", "listener", "evt", "clearEvent", "EventEmitter", "names", "events", "name", "handlers", "i", "l", "ee", "listeners", "a1", "a2", "a3", "a4", "a5", "len", "args", "length", "j", "index_exports", "__export", "PubSubBaseProtocol", "peerIdSymbol", "TopicValidatorResult", "pubSubSymbol", "InvalidParametersError", "message", "InvalidPublicKeyError", "InvalidMultihashError", "message", "InvalidMessageError", "message", "NotStartedError", "message", "UnsupportedKeyTypeError", "message", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "options", "list", "callback", "event", "result", "once", "detail", "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", "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", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "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", "crypto", "isBytes", "a", "anumber", "n", "abytes", "b", "lengths", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "abytes", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "Hash", "createHasher", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "aexists", "toBytes", "abytes", "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", "SHA256", "HashMD", "outputLen", "SHA256_IV", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA512", "HashMD", "outputLen", "SHA512_IV", "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", "sha256", "createHasher", "SHA256", "sha512", "createHasher", "SHA512", "_0n", "_1n", "isBytes", "a", "abytes", "item", "abool", "title", "value", "numberToHexUnpadded", "num", "hex", "hexToNumber", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "bytesToNumberBE", "bytesToNumberLE", "numberToBytesBE", "n", "len", "numberToBytesLE", "ensureBytes", "title", "hex", "expectedLength", "res", "hexToBytes", "e", "isBytes", "len", "concatBytes", "arrays", "sum", "i", "a", "abytes", "pad", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "u8n", "len", "u8fr", "arr", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "v", "k", "i", "reset", "h", "b", "reseed", "seed", "gen", "out", "sl", "concatBytes", "pred", "res", "validatorFns", "val", "isBytes", "object", "validateObject", "validators", "optValidators", "checkField", "fieldName", "type", "isOptional", "checkVal", "memoized", "fn", "map", "arg", "args", "val", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_8n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "res", "_0n", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "sqrt3mod4", "Fp", "p1div4", "_4n", "root", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "tonelliShanks", "P", "Q", "S", "Z", "_Fp", "Field", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "i", "t_tmp", "exponent", "FpSqrt", "_3n", "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", "ORDER", "bitLen", "isLE", "redef", "_0n", "BITS", "BYTES", "sqrtP", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "b", "c", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "constTimeNegate", "condition", "item", "neg", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "validateMSMPoints", "points", "c", "p", "i", "validateMSMScalars", "scalars", "field", "s", "pointPrecomputes", "pointWindowSizes", "getW", "P", "wNAF", "elm", "d", "base", "precomputes", "f", "wo", "offsetF", "acc", "transform", "comp", "prev", "pippenger", "fieldN", "plength", "slength", "zero", "bitLen", "MASK", "buckets", "lastBits", "sum", "j", "scalar", "resI", "sumI", "validateBasic", "curve", "validateField", "validateObject", "nLength", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "Fn", "Field", "isEdValidXY", "x", "y", "x2", "y2", "left", "right", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "abool", "aCoordinate", "title", "n", "banZero", "min", "aInRange", "aextpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "ex", "ey", "ez", "et", "points", "toInv", "FpInvertBatch", "i", "scalars", "pippenger", "windowSize", "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", "acc", "I", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getPrivateScalar", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "getExtendedPublicKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "_8n", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "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", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "randomBytes", "length", "InvalidParametersError", "utils_exports", "__export", "MAX_RSA_KEY_SIZE", "generateRSAKeyPair", "jwkToJWKKeyPair", "jwkToPkcs1", "jwkToPkix", "jwkToRSAPrivateKey", "pkcs1MessageToJwk", "pkcs1MessageToRSAPrivateKey", "pkcs1ToJwk", "pkcs1ToRSAPrivateKey", "pkixMessageToJwk", "pkixMessageToRSAPublicKey", "pkixToJwk", "pkixToRSAPublicKey", "sha256", "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", "hash", "_key", "ahash", "key", "toBytes", "blockLen", "pad", "clean", "buf", "aexists", "out", "abytes", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "validateSigVerOpts", "opts", "abool", "validatePointOpts", "curve", "validateBasic", "validateObject", "endo", "Fp", "a", "DERErr", "m", "DER", "tag", "data", "E", "dataLen", "len", "numberToHexUnpadded", "lenLen", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "num", "_0n", "hex", "bytesToNumberBE", "int", "tlv", "ensureBytes", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "numToSizedHex", "size", "bytesToHex", "numberToBytesBE", "_1n", "_2n", "_3n", "_4n", "weierstrassPoints", "CURVE", "Fn", "Field", "toBytes", "_c", "point", "_isCompressed", "concatBytes", "fromBytes", "bytes", "tail", "x", "y", "weierstrassEquation", "x2", "x3", "isValidXY", "left", "right", "_4a3", "_27b2", "isWithinCurveOrder", "inRange", "normPrivateKeyToScalar", "key", "lengths", "nByteLength", "wrapPrivateKey", "N", "isBytes", "mod", "aInRange", "aprjpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "px", "py", "pz", "i", "points", "toInv", "FpInvertBatch", "P", "privateKey", "scalars", "pippenger", "windowSize", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "n", "sc", "I", "k1neg", "k1", "k2neg", "k2", "k1p", "k2p", "d", "scalar", "fake", "f1p", "f2p", "f", "Q", "G", "mul", "sum", "cofactor", "isTorsionFree", "clearCofactor", "isCompressed", "nBitLength", "wNAF", "validateOpts", "weierstrass", "curveDef", "CURVE_ORDER", "compressedLen", "uncompressedLen", "modN", "invN", "invert", "cat", "head", "y2", "sqrtError", "suffix", "isYOdd", "cl", "ul", "isBiggerThanHalfOrder", "number", "HALF", "normalizeS", "s", "slcNum", "from", "to", "Signature", "r", "recovery", "l", "msgHash", "rec", "h", "bits2int_modN", "radj", "prefix", "R", "ir", "u1", "u2", "hexToBytes", "utils", "getMinHashLength", "mapHashToField", "getPublicKey", "isProbPub", "item", "fpl", "compLen", "uncompLen", "getSharedSecret", "privateA", "publicB", "bits2int", "delta", "ORDER_MASK", "bitMask", "int2octets", "prepSig", "defaultSigOpts", "k", "hash", "randomBytes", "lowS", "prehash", "ent", "h1int", "seedArgs", "e", "seed", "k2sig", "kBytes", "ik", "q", "normS", "defaultVerOpts", "sign", "privKey", "C", "createHmacDrbg", "verify", "signature", "publicKey", "sg", "format", "isHex", "isObj", "_sig", "derError", "is", "getHash", "hash", "key", "msgs", "hmac", "concatBytes", "randomBytes", "createCurve", "curveDef", "defHash", "create", "weierstrass", "secp256k1P", "secp256k1N", "_0n", "_1n", "_2n", "divNearest", "a", "b", "sqrtMod", "y", "P", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "secp256k1", "createCurve", "k", "n", "a1", "b1", "a2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "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", "peerIdFromPublicKey", "publicKey", "Ed25519PeerId", "Secp256k1PeerId", "RSAPeerId", "UnsupportedKeyTypeError", "peerIdFromPrivateKey", "privateKey", "peerIdFromMultihash", "multihash", "isSha256Multihash", "isIdentityMultihash", "publicKeyFromMultihash", "url", "toString", "URLPeerId", "InvalidMultihashError", "isIdentityMultihash", "multihash", "identity", "isSha256Multihash", "sha256", "mapIterable", "iter", "map", "iterator", "next", "val", "peerIdFromString", "str", "multihash", "decode", "base58btc", "peerIdFromMultihash", "PeerMap", "map", "key", "value", "peer", "mapIterable", "val", "fn", "PeerSet", "_PeerSet", "set", "key", "peer", "mapIterable", "val", "peerId", "peerIdFromString", "predicate", "str", "other", "output", "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", "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", "import_index", "TimeoutError", "message", "AbortError", "getDOMException", "errorMessage", "getAbortedReason", "signal", "reason", "pTimeout", "promise", "options", "milliseconds", "fallback", "customTimers", "timer", "abortHandler", "cancelablePromise", "resolve", "reject", "timeoutError", "error", "lowerBound", "array", "value", "comparator", "first", "count", "step", "it", "PriorityQueue", "#queue", "run", "options", "element", "index", "lowerBound", "a", "b", "id", "priority", "item", "PQueue", "EventEmitter", "#carryoverConcurrencyCount", "#isIntervalIgnored", "#intervalCount", "#intervalCap", "#interval", "#intervalEnd", "#intervalId", "#timeoutId", "#queue", "#queueClass", "#pending", "#concurrency", "#isPaused", "#throwOnTimeout", "#idAssigner", "options", "PriorityQueue", "#doesIntervalAllowAnother", "#doesConcurrentAllowAnother", "#next", "#tryToStartAnother", "#onResumeInterval", "#onInterval", "#initializeIntervalIfNeeded", "#isIntervalPaused", "now", "delay", "canInitializeInterval", "job", "#processQueue", "newConcurrency", "#throwOnAbort", "signal", "_resolve", "reject", "id", "priority", "function_", "resolve", "operation", "pTimeout", "result", "error", "TimeoutError", "functions", "#onEvent", "limit", "event", "filter", "listener", "getIterator", "obj", "isPromise", "thing", "closeSource", "source", "log", "res", "getIterator", "isPromise", "err", "InvalidMessageLengthError", "InvalidDataLengthError", "InvalidDataLengthLengthError", "UnexpectedEOFError", "isAsyncIterable", "thing", "validateMaxDataLength", "chunk", "maxDataLength", "InvalidDataLengthError", "defaultEncoder", "length", "lengthLength", "encodingLength", "lengthBuf", "allocUnsafe", "encode", "source", "options", "encodeLength", "maybeYield", "isAsyncIterable", "Uint8ArrayList", "ReadMode", "defaultDecoder", "buf", "length", "decode", "encodingLength", "source", "options", "buffer", "Uint8ArrayList", "mode", "dataLength", "lengthDecoder", "maxLengthLength", "maxDataLength", "maybeYield", "InvalidMessageLengthError", "InvalidDataLengthError", "dataLengthLength", "err", "InvalidDataLengthLengthError", "data", "isAsyncIterable", "UnexpectedEOFError", "reader", "byteLength", "varByteSource", "done", "value", "l", "PeerStreams", "TypedEventEmitter", "components", "init", "data", "id", "Uint8ArrayList", "stream", "decoderOptions", "abortListener", "closeSource", "pipe", "source", "decode", "_prevStream", "pushable", "shouldEmit", "err", "encode", "randomSeqno", "toString", "randomBytes", "msgId", "key", "seqno", "seqnoBytes", "fromString", "keyBytes", "publicKeyToProtobuf", "noSignMsgId", "data", "sha256", "ensureArray", "maybeArray", "isSigned", "message", "fromID", "peerIdFromMultihash", "decode", "signingKey", "peerIdFromPublicKey", "publicKeyFromProtobuf", "toMessage", "InvalidMessageError", "from", "key", "bigIntFromBytes", "toRpcMessage", "bigIntToBytes", "publicKeyToProtobuf", "num", "str", "fromString", "toString", "SignPrefix", "fromString", "signMessage", "privateKey", "message", "encode", "outputMessage", "peerIdFromPrivateKey", "bytes", "concat", "toRpcMessage", "verifySignature", "messagePublicKey", "PubSubBaseProtocol", "TypedEventEmitter", "components", "props", "multicodecs", "globalSignaturePolicy", "canRelayMessage", "emitSelf", "messageProcessingConcurrency", "maxInboundStreams", "maxOutboundStreams", "ensureArray", "PeerMap", "PQueue", "registrar", "multicodec", "topology", "id", "peerStreams", "data", "stream", "connection", "peerId", "peer", "inboundStream", "err", "conn", "sub", "protocol", "existing", "PeerStreams", "peers", "pipe", "source", "rpcMsg", "messages", "msg", "from", "rpc", "subscriptions", "subOpt", "topic", "subscribe", "message", "toMessage", "t", "topicSet", "PeerSet", "InvalidMessageError", "msgId", "noSignMsgId", "str", "toRpcMessage", "verifySignature", "validatorFn", "result", "TopicValidatorResult", "signMessage", "NotStartedError", "InvalidParametersError", "peersInTopic", "randomSeqno", "rpcMessage", "emittedToSelf", "wasSubscribed"]
|
7
7
|
}
|