libp2p 2.8.5 → 2.8.6
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 +16 -29
- package/dist/index.min.js.map +7 -0
- package/dist/src/content-routing.d.ts.map +1 -1
- package/dist/src/content-routing.js +15 -5
- package/dist/src/content-routing.js.map +1 -1
- package/dist/src/peer-routing.d.ts.map +1 -1
- package/dist/src/peer-routing.js +6 -2
- package/dist/src/peer-routing.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +10 -10
- package/src/content-routing.ts +30 -13
- package/src/peer-routing.ts +12 -8
- package/src/version.ts +1 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../node_modules/eventemitter3/index.js", "../../../node_modules/hashlru/index.js", "../../../node_modules/merge-options/node_modules/is-plain-obj/index.js", "../../../node_modules/merge-options/index.js", "../../../node_modules/netmask/lib/netmask.js", "../../../node_modules/retry/lib/retry_operation.js", "../../../node_modules/retry/lib/retry.js", "../../../node_modules/retry/index.js", "../src/index.ts", "../../interface/src/connection.ts", "../../interface/src/content-routing.ts", "../../interface/src/peer-discovery.ts", "../../interface/src/peer-id.ts", "../../interface/src/peer-routing.ts", "../../interface/src/peer-store.ts", "../../interface/src/transport.ts", "../../interface/src/errors.ts", "../../interface/src/event-target.ts", "../../interface/src/startable.ts", "../../interface/src/index.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/multiformats/src/bases/base10.ts", "../../../node_modules/multiformats/src/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/multiformats/src/basics.ts", "../../../node_modules/uint8arrays/src/util/bases.ts", "../../../node_modules/uint8arrays/src/from-string.ts", "../../../node_modules/uint8arrays/src/to-string.ts", "../../crypto/src/keys/rsa/der.ts", "../../crypto/src/keys/ecdsa/index.ts", "../../crypto/src/keys/ecdsa/utils.ts", "../../crypto/src/keys/ecdsa/ecdsa.ts", "../../../node_modules/@noble/hashes/src/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/keys/ed25519/index.browser.ts", "../../crypto/src/keys/ed25519/ed25519.ts", "../../crypto/src/keys/ed25519/utils.ts", "../../../node_modules/uint8-varint/src/index.ts", "../../../node_modules/protons-runtime/src/utils/float.ts", "../../../node_modules/protons-runtime/src/utils/longbits.ts", "../../../node_modules/protons-runtime/src/utils/utf8.ts", "../../../node_modules/protons-runtime/src/utils/reader.ts", "../../../node_modules/protons-runtime/src/decode.ts", "../../../node_modules/protons-runtime/src/utils/pool.ts", "../../../node_modules/protons-runtime/src/utils/writer.ts", "../../../node_modules/protons-runtime/src/encode.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../../node_modules/protons-runtime/src/index.ts", "../../crypto/src/keys/keys.ts", "../../crypto/src/random-bytes.ts", "../../crypto/src/errors.ts", "../../crypto/src/webcrypto/webcrypto.browser.ts", "../../crypto/src/webcrypto/index.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/util.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", "../../../node_modules/progress-events/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/@multiformats/dns/src/utils/get-types.ts", "../../../node_modules/@multiformats/dns/src/utils/to-dns-response.ts", "../../../node_modules/@multiformats/dns/src/resolvers/dns-json-over-https.ts", "../../../node_modules/@multiformats/dns/src/resolvers/default.browser.ts", "../../../node_modules/@multiformats/dns/src/utils/cache.ts", "../../../node_modules/@multiformats/dns/src/dns.ts", "../../../node_modules/@multiformats/dns/src/index.ts", "../../../node_modules/@chainsafe/is-ip/src/parser.ts", "../../../node_modules/@chainsafe/is-ip/src/parse.ts", "../../../node_modules/@chainsafe/netmask/src/util.ts", "../../../node_modules/@chainsafe/netmask/src/ip.ts", "../../../node_modules/@chainsafe/netmask/src/cidr.ts", "../../../node_modules/@chainsafe/netmask/src/ipnet.ts", "../../../node_modules/@chainsafe/is-ip/src/is-ip.ts", "../../../node_modules/@multiformats/multiaddr/src/ip.ts", "../../../node_modules/@multiformats/multiaddr/src/protocols-table.ts", "../../../node_modules/@multiformats/multiaddr/src/convert.ts", "../../../node_modules/@multiformats/multiaddr/src/codec.ts", "../../../node_modules/@multiformats/multiaddr/src/multiaddr.ts", "../../../node_modules/@multiformats/multiaddr/src/index.ts", "../../../node_modules/@multiformats/multiaddr/src/resolvers/dnsaddr.ts", "../../../node_modules/merge-options/index.mjs", "../src/config.ts", "../../../node_modules/weald/node_modules/ms/dist/index.mjs", "../../../node_modules/weald/src/common.ts", "../../../node_modules/weald/src/browser.ts", "../../../node_modules/weald/src/index.ts", "../../logger/src/index.ts", "../../peer-collections/src/util.ts", "../../peer-collections/src/map.ts", "../../peer-collections/src/set.ts", "../../../node_modules/@sindresorhus/fnv1a/index.js", "../../utils/src/filters/hashes.ts", "../../utils/src/filters/fingerprint.ts", "../../utils/src/filters/utils.ts", "../../utils/src/filters/bucket.ts", "../../utils/src/filters/cuckoo-filter.ts", "../../utils/src/filters/scalable-cuckoo-filter.ts", "../../peer-record/src/envelope/envelope.ts", "../../peer-record/src/envelope/errors.ts", "../../peer-record/src/envelope/index.ts", "../../utils/src/array-equals.ts", "../../peer-record/src/peer-record/consts.ts", "../../peer-record/src/peer-record/peer-record.ts", "../../peer-record/src/peer-record/index.ts", "../../../node_modules/it-all/src/index.ts", "../../../node_modules/observable-webworkers/src/index.ts", "../../../node_modules/mortice/src/constants.ts", "../../../node_modules/mortice/src/utils.ts", "../../../node_modules/mortice/src/browser.ts", "../../../node_modules/mortice/src/index.ts", "../../peer-store/src/pb/peer.ts", "../../peer-store/src/utils/bytes-to-peer.ts", "../../peer-store/src/utils/peer-equals.ts", "../../../node_modules/interface-datastore/src/key.ts", "../../peer-store/src/utils/peer-id-to-datastore-key.ts", "../../peer-store/src/utils/dedupe-addresses.ts", "../../peer-store/src/utils/to-peer-pb.ts", "../../peer-store/src/store.ts", "../../peer-store/src/index.ts", "../../../node_modules/interface-store/src/errors.ts", "../../../node_modules/it-drain/src/index.ts", "../../../node_modules/it-peekable/src/index.ts", "../../../node_modules/it-filter/src/index.ts", "../../../node_modules/it-sort/src/index.ts", "../../../node_modules/it-take/src/index.ts", "../../../node_modules/datastore-core/src/base.ts", "../../../node_modules/datastore-core/src/memory.ts", "../../utils/src/debounce.ts", "../../utils/src/private-ip.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/utils.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/index.ts", "../src/address-manager/dns-mappings.ts", "../src/address-manager/ip-mappings.ts", "../../utils/src/multiaddr/is-link-local.ts", "../../utils/src/multiaddr/is-ip-based.ts", "../../utils/src/multiaddr/is-private.ts", "../src/address-manager/observed-addresses.ts", "../../utils/src/multiaddr/is-network-address.ts", "../src/address-manager/transport-addresses.ts", "../src/address-manager/index.ts", "../src/errors.ts", "../src/components.ts", "../src/config/connection-gater.browser.ts", "../../../node_modules/delay/index.js", "../../utils/src/errors.ts", "../../utils/src/rate-limiter.ts", "../src/get-peer.ts", "../../utils/src/close.ts", "../src/connection-manager/constants.defaults.ts", "../src/connection-manager/constants.browser.ts", "../src/connection-manager/utils.ts", "../src/connection-manager/connection-pruner.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/it-pushable/src/fifo.ts", "../../../node_modules/it-pushable/src/index.ts", "../../../node_modules/race-event/src/index.ts", "../../../node_modules/race-signal/src/index.ts", "../../utils/src/queue/recipient.ts", "../../utils/src/queue/job.ts", "../../utils/src/queue/index.ts", "../../utils/src/priority-queue.ts", "../../../node_modules/any-signal/src/index.ts", "../../../node_modules/is-loopback-addr/src/index.ts", "../../utils/src/multiaddr/is-loopback.ts", "../src/connection-manager/address-sorter.ts", "../src/connection-manager/dial-queue.ts", "../../utils/src/peer-queue.ts", "../../../node_modules/p-retry/index.js", "../../../node_modules/is-network-error/index.js", "../src/connection-manager/reconnect-queue.ts", "../src/connection-manager/index.ts", "../../utils/src/moving-average.ts", "../../utils/src/adaptive-timeout.ts", "../../../node_modules/it-queueless-pushable/src/index.ts", "../../../node_modules/it-byte-stream/src/errors.ts", "../../../node_modules/it-byte-stream/src/index.ts", "../src/connection-monitor.ts", "../../../node_modules/it-merge/src/index.ts", "../src/content-routing.ts", "../../../node_modules/it-parallel/src/index.ts", "../src/peer-routing.ts", "../src/random-walk.ts", "../src/registrar.ts", "../../utils/src/tracked-map.ts", "../src/transport-manager.ts", "../../multistream-select/src/constants.ts", "../../../node_modules/it-length-prefixed-stream/src/errors.ts", "../../../node_modules/it-length-prefixed-stream/src/index.ts", "../../multistream-select/src/multistream.ts", "../../multistream-select/src/select.ts", "../../multistream-select/node_modules/it-length-prefixed/src/errors.ts", "../../multistream-select/node_modules/it-length-prefixed/src/utils.ts", "../../multistream-select/node_modules/it-length-prefixed/src/encode.ts", "../../multistream-select/node_modules/it-length-prefixed/src/decode.ts", "../../multistream-select/src/handle.ts", "../src/connection/index.ts", "../src/upgrader.ts", "../src/version.ts", "../src/user-agent.browser.ts", "../src/libp2p.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", "module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n", "'use strict';\n\nmodule.exports = value => {\n\tif (Object.prototype.toString.call(value) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || prototype === Object.prototype;\n};\n", "'use strict';\nconst isOptionObject = require('is-plain-obj');\n\nconst {hasOwnProperty} = Object.prototype;\nconst {propertyIsEnumerable} = Object;\nconst defineProperty = (object, name, value) => Object.defineProperty(object, name, {\n\tvalue,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true\n});\n\nconst globalThis = this;\nconst defaultMergeOptions = {\n\tconcatArrays: false,\n\tignoreUndefined: false\n};\n\nconst getEnumerableOwnPropertyKeys = value => {\n\tconst keys = [];\n\n\tfor (const key in value) {\n\t\tif (hasOwnProperty.call(value, key)) {\n\t\t\tkeys.push(key);\n\t\t}\n\t}\n\n\t/* istanbul ignore else */\n\tif (Object.getOwnPropertySymbols) {\n\t\tconst symbols = Object.getOwnPropertySymbols(value);\n\n\t\tfor (const symbol of symbols) {\n\t\t\tif (propertyIsEnumerable.call(value, symbol)) {\n\t\t\t\tkeys.push(symbol);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn keys;\n};\n\nfunction clone(value) {\n\tif (Array.isArray(value)) {\n\t\treturn cloneArray(value);\n\t}\n\n\tif (isOptionObject(value)) {\n\t\treturn cloneOptionObject(value);\n\t}\n\n\treturn value;\n}\n\nfunction cloneArray(array) {\n\tconst result = array.slice(0, 0);\n\n\tgetEnumerableOwnPropertyKeys(array).forEach(key => {\n\t\tdefineProperty(result, key, clone(array[key]));\n\t});\n\n\treturn result;\n}\n\nfunction cloneOptionObject(object) {\n\tconst result = Object.getPrototypeOf(object) === null ? Object.create(null) : {};\n\n\tgetEnumerableOwnPropertyKeys(object).forEach(key => {\n\t\tdefineProperty(result, key, clone(object[key]));\n\t});\n\n\treturn result;\n}\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {string[]} keys keys to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nconst mergeKeys = (merged, source, keys, config) => {\n\tkeys.forEach(key => {\n\t\tif (typeof source[key] === 'undefined' && config.ignoreUndefined) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Do not recurse into prototype chain of merged\n\t\tif (key in merged && merged[key] !== Object.getPrototypeOf(merged)) {\n\t\t\tdefineProperty(merged, key, merge(merged[key], source[key], config));\n\t\t} else {\n\t\t\tdefineProperty(merged, key, clone(source[key]));\n\t\t}\n\t});\n\n\treturn merged;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n *\n * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat)\n */\nconst concatArrays = (merged, source, config) => {\n\tlet result = merged.slice(0, 0);\n\tlet resultIndex = 0;\n\n\t[merged, source].forEach(array => {\n\t\tconst indices = [];\n\n\t\t// `result.concat(array)` with cloning\n\t\tfor (let k = 0; k < array.length; k++) {\n\t\t\tif (!hasOwnProperty.call(array, k)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tindices.push(String(k));\n\n\t\t\tif (array === merged) {\n\t\t\t\t// Already cloned\n\t\t\t\tdefineProperty(result, resultIndex++, array[k]);\n\t\t\t} else {\n\t\t\t\tdefineProperty(result, resultIndex++, clone(array[k]));\n\t\t\t}\n\t\t}\n\n\t\t// Merge non-index keys\n\t\tresult = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config);\n\t});\n\n\treturn result;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nfunction merge(merged, source, config) {\n\tif (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) {\n\t\treturn concatArrays(merged, source, config);\n\t}\n\n\tif (!isOptionObject(source) || !isOptionObject(merged)) {\n\t\treturn clone(source);\n\t}\n\n\treturn mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config);\n}\n\nmodule.exports = function (...options) {\n\tconst config = merge(clone(defaultMergeOptions), (this !== globalThis && this) || {}, defaultMergeOptions);\n\tlet merged = {_: {}};\n\n\tfor (const option of options) {\n\t\tif (option === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!isOptionObject(option)) {\n\t\t\tthrow new TypeError('`' + option + '` is not an Option Object');\n\t\t}\n\n\t\tmerged = merge(merged, {_: option}, config);\n\t}\n\n\treturn merged._;\n};\n", "// Generated by CoffeeScript 1.12.7\n(function() {\n var Netmask, atob, chr, chr0, chrA, chra, ip2long, long2ip;\n\n long2ip = function(long) {\n var a, b, c, d;\n a = (long & (0xff << 24)) >>> 24;\n b = (long & (0xff << 16)) >>> 16;\n c = (long & (0xff << 8)) >>> 8;\n d = long & 0xff;\n return [a, b, c, d].join('.');\n };\n\n ip2long = function(ip) {\n var b, c, i, j, n, ref;\n b = [];\n for (i = j = 0; j <= 3; i = ++j) {\n if (ip.length === 0) {\n break;\n }\n if (i > 0) {\n if (ip[0] !== '.') {\n throw new Error('Invalid IP');\n }\n ip = ip.substring(1);\n }\n ref = atob(ip), n = ref[0], c = ref[1];\n ip = ip.substring(c);\n b.push(n);\n }\n if (ip.length !== 0) {\n throw new Error('Invalid IP');\n }\n switch (b.length) {\n case 1:\n if (b[0] > 0xFFFFFFFF) {\n throw new Error('Invalid IP');\n }\n return b[0] >>> 0;\n case 2:\n if (b[0] > 0xFF || b[1] > 0xFFFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1]) >>> 0;\n case 3:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0;\n case 4:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFF || b[3] > 0xFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0;\n default:\n throw new Error('Invalid IP');\n }\n };\n\n chr = function(b) {\n return b.charCodeAt(0);\n };\n\n chr0 = chr('0');\n\n chra = chr('a');\n\n chrA = chr('A');\n\n atob = function(s) {\n var base, dmax, i, n, start;\n n = 0;\n base = 10;\n dmax = '9';\n i = 0;\n if (s.length > 1 && s[i] === '0') {\n if (s[i + 1] === 'x' || s[i + 1] === 'X') {\n i += 2;\n base = 16;\n } else if ('0' <= s[i + 1] && s[i + 1] <= '9') {\n i++;\n base = 8;\n dmax = '7';\n }\n }\n start = i;\n while (i < s.length) {\n if ('0' <= s[i] && s[i] <= dmax) {\n n = (n * base + (chr(s[i]) - chr0)) >>> 0;\n } else if (base === 16) {\n if ('a' <= s[i] && s[i] <= 'f') {\n n = (n * base + (10 + chr(s[i]) - chra)) >>> 0;\n } else if ('A' <= s[i] && s[i] <= 'F') {\n n = (n * base + (10 + chr(s[i]) - chrA)) >>> 0;\n } else {\n break;\n }\n } else {\n break;\n }\n if (n > 0xFFFFFFFF) {\n throw new Error('too large');\n }\n i++;\n }\n if (i === start) {\n throw new Error('empty octet');\n }\n return [n, i];\n };\n\n Netmask = (function() {\n function Netmask(net, mask) {\n var error, i, j, ref;\n if (typeof net !== 'string') {\n throw new Error(\"Missing `net' parameter\");\n }\n if (!mask) {\n ref = net.split('/', 2), net = ref[0], mask = ref[1];\n }\n if (!mask) {\n mask = 32;\n }\n if (typeof mask === 'string' && mask.indexOf('.') > -1) {\n try {\n this.maskLong = ip2long(mask);\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid mask: \" + mask);\n }\n for (i = j = 32; j >= 0; i = --j) {\n if (this.maskLong === (0xffffffff << (32 - i)) >>> 0) {\n this.bitmask = i;\n break;\n }\n }\n } else if (mask || mask === 0) {\n this.bitmask = parseInt(mask, 10);\n this.maskLong = 0;\n if (this.bitmask > 0) {\n this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0;\n }\n } else {\n throw new Error(\"Invalid mask: empty\");\n }\n try {\n this.netLong = (ip2long(net) & this.maskLong) >>> 0;\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid net address: \" + net);\n }\n if (!(this.bitmask <= 32)) {\n throw new Error(\"Invalid mask for ip4: \" + mask);\n }\n this.size = Math.pow(2, 32 - this.bitmask);\n this.base = long2ip(this.netLong);\n this.mask = long2ip(this.maskLong);\n this.hostmask = long2ip(~this.maskLong);\n this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base;\n this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1);\n this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : void 0;\n }\n\n Netmask.prototype.contains = function(ip) {\n if (typeof ip === 'string' && (ip.indexOf('/') > 0 || ip.split('.').length !== 4)) {\n ip = new Netmask(ip);\n }\n if (ip instanceof Netmask) {\n return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);\n } else {\n return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;\n }\n };\n\n Netmask.prototype.next = function(count) {\n if (count == null) {\n count = 1;\n }\n return new Netmask(long2ip(this.netLong + (this.size * count)), this.mask);\n };\n\n Netmask.prototype.forEach = function(fn) {\n var index, lastLong, long;\n long = ip2long(this.first);\n lastLong = ip2long(this.last);\n index = 0;\n while (long <= lastLong) {\n fn(long2ip(long), long, index);\n index++;\n long++;\n }\n };\n\n Netmask.prototype.toString = function() {\n return this.base + \"/\" + this.bitmask;\n };\n\n return Netmask;\n\n })();\n\n exports.ip2long = ip2long;\n\n exports.long2ip = long2ip;\n\n exports.Netmask = Netmask;\n\n}).call(this);\n", "function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n", "var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n", "module.exports = require('./lib/retry');", "/**\n * @packageDocumentation\n *\n * Use the `createLibp2p` function to create a libp2p node.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n *\n * const node = await createLibp2p({\n * // ...other options\n * })\n * ```\n */\n\nimport { generateKeyPair } from '@libp2p/crypto/keys'\nimport { peerIdFromPrivateKey } from '@libp2p/peer-id'\nimport { validateConfig } from './config.js'\nimport { Libp2p as Libp2pClass } from './libp2p.js'\nimport type { AddressManagerInit, AddressFilter } from './address-manager/index.js'\nimport type { Components } from './components.js'\nimport type { ConnectionManagerInit } from './connection-manager/index.js'\nimport type { ConnectionMonitorInit } from './connection-monitor.js'\nimport type { TransportManagerInit } from './transport-manager.js'\nimport type { Libp2p, ServiceMap, ComponentLogger, NodeInfo, ConnectionProtector, ConnectionEncrypter, ConnectionGater, ContentRouting, Metrics, PeerDiscovery, PeerRouting, StreamMuxerFactory, Transport, PrivateKey } from '@libp2p/interface'\nimport type { PersistentPeerStoreInit } from '@libp2p/peer-store'\nimport type { DNS } from '@multiformats/dns'\nimport type { Datastore } from 'interface-datastore'\n\nexport type ServiceFactoryMap<T extends ServiceMap = ServiceMap> = {\n [Property in keyof T]: (components: Components & T) => T[Property]\n}\n\nexport type { AddressManagerInit, AddressFilter }\n\n/**\n * For Libp2p configurations and modules details read the [Configuration Document](https://github.com/libp2p/js-libp2p/tree/main/doc/CONFIGURATION.md).\n */\nexport interface Libp2pInit<T extends ServiceMap = ServiceMap> {\n /**\n * The private key is used in cryptographic operations and the Peer ID derived\n * from it's corresponding public key is used to identify the node to other\n * peers on the network.\n *\n * If this is not passed a new Ed25519 private key will be generated.\n */\n privateKey?: PrivateKey\n\n /**\n * Metadata about the node - implementation name, version number, etc\n */\n nodeInfo?: Partial<NodeInfo>\n\n /**\n * Addresses for transport listening and to advertise to the network\n */\n addresses?: AddressManagerInit\n\n /**\n * libp2p Connection Manager configuration\n */\n connectionManager?: ConnectionManagerInit\n\n /**\n * libp2p Connection Monitor configuration\n */\n connectionMonitor?: ConnectionMonitorInit\n\n /**\n * A connection gater can deny new connections based on user criteria\n */\n connectionGater?: ConnectionGater\n\n /**\n * libp2p transport manager configuration\n */\n transportManager?: TransportManagerInit\n\n /**\n * An optional datastore to persist peer information, DHT records, etc.\n *\n * An in-memory datastore will be used if one is not provided.\n */\n datastore?: Datastore\n\n /**\n * libp2p PeerStore configuration\n */\n peerStore?: PersistentPeerStoreInit\n\n /**\n * Transports are low-level communication channels\n */\n transports?: Array<(components: Components) => Transport>\n\n /**\n * Stream muxers allow the creation of many data streams over a single\n * connection.\n */\n streamMuxers?: Array<(components: Components) => StreamMuxerFactory>\n\n /**\n * Connection encrypters ensure that data sent over connections cannot be\n * eavesdropped on, and that the remote peer possesses the private key that\n * corresponds to the public key that it's Peer ID is derived from.\n */\n connectionEncrypters?: Array<(components: Components) => ConnectionEncrypter>\n\n /**\n * Peer discovery mechanisms allow finding peers on the network\n */\n peerDiscovery?: Array<(components: Components) => PeerDiscovery>\n\n /**\n * Peer routers provide implementations for peer routing queries\n */\n peerRouters?: Array<(components: Components) => PeerRouting>\n\n /**\n * Content routers provide implementations for content routing queries\n */\n contentRouters?: Array<(components: Components) => ContentRouting>\n\n /**\n * A Metrics implementation can be supplied to collect metrics on this node\n */\n metrics?(components: Components): Metrics\n\n /**\n * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys\n */\n connectionProtector?(components: Components): ConnectionProtector\n\n /**\n * Arbitrary libp2p modules\n */\n services?: ServiceFactoryMap<T>\n\n /**\n * An optional logging implementation that can be used to write runtime logs.\n *\n * Set the `DEBUG` env var or the `debug` key on LocalStorage to see logs.\n *\n * @example\n *\n * Node.js:\n *\n * ```console\n * $ DEBUG=\"*libp2p:*\" node myscript.js\n * ```\n *\n * Browsers:\n *\n * ```TypeScript\n * localStorage.setItem('debug', '*libp2p:*')\n * ```\n */\n logger?: ComponentLogger\n\n /**\n * An optional DNS resolver configuration. If omitted the default DNS resolver\n * for the platform will be used which means `node:dns` on Node.js and\n * DNS-JSON-over-HTTPS for browsers using Google and Cloudflare servers.\n */\n dns?: DNS\n}\n\nexport type { Libp2p, ConnectionManagerInit, ConnectionMonitorInit, TransportManagerInit }\n\nexport type Libp2pOptions<T extends ServiceMap = ServiceMap> = Libp2pInit<T> & { start?: boolean }\n\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n *\n * The node will be started unless `start: false` is passed as an option.\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { tcp } from '@libp2p/tcp'\n * import { mplex } from '@libp2p/mplex'\n * import { noise } from '@chainsafe/libp2p-noise'\n * import { yamux } from '@chainsafe/libp2p-yamux'\n *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [yamux(), mplex()],\n * connectionEncrypters: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p <T extends ServiceMap = ServiceMap> (options: Libp2pOptions<T> = {}): Promise<Libp2p<T>> {\n options.privateKey ??= await generateKeyPair('Ed25519')\n\n const node = new Libp2pClass({\n ...await validateConfig(options),\n peerId: peerIdFromPrivateKey(options.privateKey)\n })\n\n if (options.start !== false) {\n await node.start()\n }\n\n return node\n}\n", "import type { AbortOptions, Logger } from './index.js'\nimport type { PeerId } from './peer-id.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Duplex, Source } from 'it-stream-types'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface ConnectionTimeline {\n /**\n * When the connection was opened\n */\n open: number\n\n /**\n * When the MultiaddrConnection was upgraded to a Connection - e.g. the type\n * of connection encryption and multiplexing was negotiated.\n */\n upgraded?: number\n\n /**\n * When the connection was closed.\n */\n close?: number\n}\n\n/**\n * Outbound connections are opened by the local node, inbound streams are opened by the remote\n */\nexport type Direction = 'inbound' | 'outbound'\n\nexport interface StreamTimeline {\n /**\n * A timestamp of when the stream was opened\n */\n open: number\n\n /**\n * A timestamp of when the stream was closed for both reading and writing\n */\n close?: number\n\n /**\n * A timestamp of when the stream was closed for reading\n */\n closeRead?: number\n\n /**\n * A timestamp of when the stream was closed for writing\n */\n closeWrite?: number\n\n /**\n * A timestamp of when the stream was reset\n */\n reset?: number\n\n /**\n * A timestamp of when the stream was aborted\n */\n abort?: number\n}\n\n/**\n * The states a stream can be in\n */\nexport type StreamStatus = 'open' | 'closing' | 'closed' | 'aborted' | 'reset'\n\n/**\n * The states the readable end of a stream can be in\n *\n * ready - the readable end is ready for reading\n * closing - the readable end is closing\n * closed - the readable end has closed\n */\nexport type ReadStatus = 'ready' | 'closing' | 'closed'\n\n/**\n * The states the writable end of a stream can be in\n *\n * ready - the writable end is ready for writing\n * writing - the writable end is in the process of being written to\n * done - the source passed to the `.sink` function yielded all values without error\n * closing - the writable end is closing\n * closed - the writable end has closed\n */\nexport type WriteStatus = 'ready' | 'writing' | 'done' | 'closing' | 'closed'\n\n/**\n * A Stream is a data channel between two peers that\n * can be written to and read from at both ends.\n *\n * It may be encrypted and multiplexed depending on the\n * configuration of the nodes.\n */\nexport interface Stream extends Duplex<AsyncGenerator<Uint8ArrayList>, Source<Uint8ArrayList | Uint8Array>, Promise<void>> {\n /**\n * Closes the stream for **reading** *and* **writing**.\n *\n * Any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `CLOSE` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink and the source will return normally.\n */\n close(options?: AbortOptions): Promise<void>\n\n /**\n * Closes the stream for **reading**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * This function is called automatically by the muxer when it receives a `CLOSE` message from the remote.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeRead(options?: AbortOptions): Promise<void>\n\n /**\n * Closes the stream for **writing**. If iterating over the source of this stream in a `for await of` loop, it will return (exit the loop) after any buffered data has been consumed.\n *\n * The source will return normally, the sink will continue to consume.\n */\n closeWrite(options?: AbortOptions): Promise<void>\n\n /**\n * Closes the stream for **reading** *and* **writing**. This should be called when a *local error* has occurred.\n *\n * Note, if called without an error any buffered data in the source can still be consumed and the stream will end normally.\n *\n * This will cause a `RESET` message to be sent to the remote, *unless* the sink has already ended.\n *\n * The sink will return and the source will throw.\n */\n abort(err: Error): void\n\n /**\n * Unique identifier for a stream. Identifiers are not unique across muxers.\n */\n id: string\n\n /**\n * Outbound streams are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the stream\n */\n timeline: StreamTimeline\n\n /**\n * The protocol negotiated for this stream\n */\n protocol?: string\n\n /**\n * User defined stream metadata\n */\n metadata: Record<string, any>\n\n /**\n * The current status of the stream\n */\n status: StreamStatus\n\n /**\n * The current status of the readable end of the stream\n */\n readStatus: ReadStatus\n\n /**\n * The current status of the writable end of the stream\n */\n writeStatus: WriteStatus\n\n /**\n * The stream logger\n */\n log: Logger\n}\n\nexport interface NewStreamOptions extends AbortOptions {\n /**\n * If specified, and no handler has been registered with the registrar for the\n * successfully negotiated protocol, use this as the max outbound stream limit\n * for the protocol\n */\n maxOutboundStreams?: number\n\n /**\n * Opt-in to running over a limited connection - one that has restrictions\n * on the amount of data that may be transferred or how long it may be open for.\n *\n * These limits are typically enforced by a relay server, if the protocol\n * will be transferring a lot of data or the stream will be open for a long time\n * consider upgrading to a direct connection before opening the stream.\n *\n * @default false\n */\n runOnLimitedConnection?: boolean\n\n /**\n * By default when negotiating a protocol the dialer writes then protocol name\n * then reads the response.\n *\n * When a only a single protocol is being negotiated on an outbound stream,\n * and the stream is written to before being read from, we can optimistically\n * write the protocol name and the first chunk of data together in the first\n * message.\n *\n * Reading and handling the protocol response is done asynchronously, which\n * means we can skip a round trip on writing to newly opened streams which\n * significantly reduces the time-to-first-byte on a stream.\n *\n * The side-effect of this is that the underlying stream won't negotiate the\n * protocol until either data is written to or read from the stream so it will\n * not be opened on the remote until this is done.\n *\n * Pass `false` here to optimistically write the protocol name and first chunk\n * of data in the first message.\n *\n * If multiple protocols are being negotiated, negotiation is always completed\n * in full before the stream is returned so this option has no effect.\n *\n * @default true\n */\n negotiateFully?: boolean\n}\n\nexport type ConnectionStatus = 'open' | 'closing' | 'closed'\n\n/**\n * Connection limits are present on connections that are only allowed to\n * transfer a certain amount of bytes or be open for a certain number\n * of seconds.\n *\n * These limits are applied by Circuit Relay v2 servers, for example and\n * the connection will normally be closed abruptly if the limits are\n * exceeded.\n */\nexport interface ConnectionLimits {\n /**\n * If present this is the number of bytes remaining that may be\n * transferred over this connection\n */\n bytes?: bigint\n\n /**\n * If present this is the number of seconds that this connection will\n * remain open for\n */\n seconds?: number\n}\n\n/**\n * A Connection is a high-level representation of a connection\n * to a remote peer that may have been secured by encryption and\n * multiplexed, depending on the configuration of the nodes\n * between which the connection is made.\n */\nexport interface Connection {\n /**\n * The unique identifier for this connection\n */\n id: string\n\n /**\n * The address of the remote end of the connection\n */\n remoteAddr: Multiaddr\n\n /**\n * The id of the peer at the remote end of the connection\n */\n remotePeer: PeerId\n\n /**\n * A list of tags applied to this connection\n */\n tags: string[]\n\n /**\n * A list of open streams on this connection\n */\n streams: Stream[]\n\n /**\n * Outbound connections are opened by the local node, inbound streams are opened by the remote\n */\n direction: Direction\n\n /**\n * Lifecycle times for the connection\n */\n timeline: ConnectionTimeline\n\n /**\n * The multiplexer negotiated for this connection\n */\n multiplexer?: string\n\n /**\n * The encryption protocol negotiated for this connection\n */\n encryption?: string\n\n /**\n * The current status of the connection\n */\n status: ConnectionStatus\n\n /**\n * If present, this connection has limits applied to it, perhaps by an\n * intermediate relay. Once the limits have been reached the connection will\n * be closed by the relay.\n */\n limits?: ConnectionLimits\n\n /**\n * The time in milliseconds it takes to make a round trip to the remote peer.\n *\n * This is updated periodically by the connection monitor.\n */\n rtt?: number\n\n /**\n * Create a new stream on this connection and negotiate one of the passed protocols\n */\n newStream(protocols: string | string[], options?: NewStreamOptions): Promise<Stream>\n\n /**\n * Gracefully close the connection. All queued data will be written to the\n * underlying transport.\n */\n close(options?: AbortOptions): Promise<void>\n\n /**\n * Immediately close the connection, any queued data will be discarded\n */\n abort(err: Error): void\n\n /**\n * The connection logger\n */\n log: Logger\n}\n\nexport const connectionSymbol = Symbol.for('@libp2p/connection')\n\nexport function isConnection (other: any): other is Connection {\n return other != null && Boolean(other[connectionSymbol])\n}\n\nexport interface ConnectionProtector {\n /**\n * Takes a given Connection and creates a private encryption stream\n * between its two peers from the PSK the Protector instance was\n * created with.\n */\n protect(connection: MultiaddrConnection, options?: AbortOptions): Promise<MultiaddrConnection>\n}\n\nexport interface MultiaddrConnectionTimeline {\n /**\n * When the connection was opened\n */\n open: number\n\n /**\n * When the MultiaddrConnection was upgraded to a Connection - the type of\n * connection encryption and multiplexing was negotiated.\n */\n upgraded?: number\n\n /**\n * When the connection was closed.\n */\n close?: number\n}\n\n/**\n * A MultiaddrConnection is returned by transports after dialing\n * a peer. It is a low-level primitive and is the raw connection\n * without encryption or stream multiplexing.\n */\nexport interface MultiaddrConnection extends Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>> {\n /**\n * Gracefully close the connection. All queued data will be written to the\n * underlying transport.\n */\n close(options?: AbortOptions): Promise<void>\n\n /**\n * Immediately close the connection, any queued data will be discarded\n */\n abort(err: Error): void\n\n /**\n * The address of the remote end of the connection\n */\n remoteAddr: Multiaddr\n\n /**\n * When connection life cycle events occurred\n */\n timeline: MultiaddrConnectionTimeline\n\n /**\n * The multiaddr connection logger\n */\n log: Logger\n}\n", "import type { RoutingOptions } from './index.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { CID } from 'multiformats/cid'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * Partial<ContentRouting> instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const contentRoutingSymbol = Symbol.for('@libp2p/content-routing')\n\n/**\n * Implementers of this interface can provide a ContentRouting implementation to\n * interested callers.\n */\nexport interface ContentRoutingProvider {\n [contentRoutingSymbol]: Partial<ContentRouting>\n}\n\nexport interface ContentRouting {\n /**\n * The implementation of this method should ensure that network peers know the\n * caller can provide content that corresponds to the passed CID.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n * await contentRouting.provide(cid)\n * ```\n */\n provide(cid: CID, options?: RoutingOptions): Promise<void>\n\n /**\n * If network peers need to be periodically reminded that the caller can\n * provide content corresponding to the passed CID, call this function to no\n * longer remind them.\n */\n cancelReprovide (key: CID, options?: RoutingOptions): Promise<void>\n\n /**\n * Find the providers of the passed CID.\n *\n * @example\n *\n * ```TypeScript\n * // Iterate over the providers found for the given cid\n * for await (const provider of contentRouting.findProviders(cid)) {\n * console.log(provider.id, provider.multiaddrs)\n * }\n * ```\n */\n findProviders(cid: CID, options?: RoutingOptions): AsyncIterable<PeerInfo>\n\n /**\n * Puts a value corresponding to the passed key in a way that can later be\n * retrieved by another network peer using the get method.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n * const key = '/key'\n * const value = uint8ArrayFromString('oh hello there')\n *\n * await contentRouting.put(key, value)\n * ```\n */\n put(key: Uint8Array, value: Uint8Array, options?: RoutingOptions): Promise<void>\n\n /**\n * Retrieves a value from the network corresponding to the passed key.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n *\n * const key = '/key'\n * const value = await contentRouting.get(key)\n * ```\n */\n get(key: Uint8Array, options?: RoutingOptions): Promise<Uint8Array>\n}\n", "import type { TypedEventTarget } from './event-target.js'\nimport type { PeerInfo } from './peer-info.js'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery')\n\n/**\n * Implementers of this interface can provide a PeerDiscovery implementation to\n * interested callers.\n */\nexport interface PeerDiscoveryProvider {\n [peerDiscoverySymbol]: PeerDiscovery\n}\n\nexport interface PeerDiscoveryEvents {\n 'peer': CustomEvent<PeerInfo>\n}\n\n/**\n * A class that implements the `PeerDiscovery` interface uses an\n * implementation-specific method to discover peers. These peers are then added\n * to the peer store for use by other system components and services.\n */\nexport interface PeerDiscovery extends TypedEventTarget<PeerDiscoveryEvents> {}\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 { RoutingOptions } from './index.js'\nimport type { PeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how `Symbol.Iterable`\n * can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerRoutingSymbol = Symbol.for('@libp2p/peer-routing')\n\n/**\n * Implementers of this interface can provide a PeerRouting implementation to\n * interested callers.\n */\nexport interface PeerRoutingProvider {\n [peerRoutingSymbol]: Partial<PeerRouting>\n}\n\nexport interface PeerRouting {\n /**\n * Searches the network for peer info corresponding to the passed peer id.\n *\n * @example\n *\n * ```TypeScript\n * // ...\n * const peer = await peerRouting.findPeer(peerId, options)\n * ```\n */\n findPeer(peerId: PeerId, options?: RoutingOptions): Promise<PeerInfo>\n\n /**\n * Search the network for peers that are closer to the passed key. Peer\n * info should be yielded in ever-increasing closeness to the key.\n *\n * @example\n *\n * ```TypeScript\n * // Iterate over the closest peers found for the given key\n * for await (const peer of peerRouting.getClosestPeers(key)) {\n * console.log(peer.id, peer.multiaddrs)\n * }\n * ```\n */\n getClosestPeers(key: Uint8Array, options?: RoutingOptions): AsyncIterable<PeerInfo>\n}\n", "import type { PublicKey } from './keys.js'\nimport type { PeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * When a peer that is tagged with this prefix disconnects, we will attempt to\n * redial it, up to a limit.\n *\n * To allow multiple components to add/remove their own keep-alive tags without\n * accidentally overwriting those of other components, attach a unique suffix to\n * the tag, e.g. `keep-alive-circuit-relay` or `keep-alive-kad-dht`, etc.\n */\nexport const KEEP_ALIVE = 'keep-alive'\n\n/**\n * A multiaddr with an optional flag that indicates if its trustworthy\n */\nexport interface Address {\n /**\n * Peer multiaddr\n */\n multiaddr: Multiaddr\n\n /**\n * Obtained from a signed peer record\n */\n isCertified: boolean\n}\n\n/**\n * Data stored in the peer store about peers\n */\nexport interface Peer {\n /**\n * Peer's peer-id instance\n */\n id: PeerId\n\n /**\n * Peer's addresses containing a list of multiaddrs and a isCertified field\n * indicating if the address was loaded from a signed peer record or not\n */\n addresses: Address[]\n\n /**\n * Peer's supported protocols\n */\n protocols: string[]\n\n /**\n * Peer's metadata map\n */\n metadata: Map<string, Uint8Array>\n\n /**\n * Tags a peer has\n */\n tags: Map<string, Tag>\n\n /**\n * The last peer record envelope received\n */\n peerRecordEnvelope?: Uint8Array\n}\n\n/**\n * Peer data used to update the peer store\n */\nexport interface PeerData {\n /**\n * Peer's addresses containing its multiaddrs and metadata - multiaddrs\n * passed here can be treated as certified if the `isCertifed` value is\n * set to true.\n *\n * If both addresses and multiaddrs are specified they will be merged\n * together with entries in addresses taking precedence.\n */\n addresses?: Address[]\n\n /**\n * Peer's multiaddrs - any multiaddrs passed here will be treated as\n * uncertified.\n *\n * If both addresses and multiaddrs are specified they will be merged\n * together with entries in addresses taking precedence.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Peer's supported protocols\n */\n protocols?: string[]\n\n /**\n * Peer's metadata map. When merging pass undefined as values to remove metadata.\n */\n metadata?: Map<string, Uint8Array | undefined> | Record<string, Uint8Array | undefined>\n\n /**\n * Peer tags. When merging pass undefined as values to remove tags.\n */\n tags?: Map<string, TagOptions | undefined> | Record<string, TagOptions | undefined>\n\n /**\n * If this Peer has an RSA key, it's public key can be set with this property.\n *\n * The byte array should be the protobuf encoded form of the public key.\n */\n publicKey?: PublicKey\n\n /**\n * The last peer record envelope received\n */\n peerRecordEnvelope?: Uint8Array\n}\n\nexport interface TagOptions {\n /**\n * An optional tag value (1-100)\n */\n value?: number\n\n /**\n * An optional duration in ms after which the tag will expire\n */\n ttl?: number\n}\n\nexport interface Tag {\n /**\n * The tag value\n */\n value: number\n}\n\n/**\n * A predicate by which to filter lists of peers\n */\nexport interface PeerQueryFilter { (peer: Peer): boolean }\n\n/**\n * A predicate by which to sort lists of peers\n */\nexport interface PeerQueryOrder { (a: Peer, b: Peer): -1 | 0 | 1 }\n\n/**\n * A query for getting lists of peers\n */\nexport interface PeerQuery {\n filters?: PeerQueryFilter[]\n orders?: PeerQueryOrder[]\n limit?: number\n offset?: number\n}\n\nexport interface PeerStore {\n /**\n * Loop over every peer - the looping is async because we read from a\n * datastore but the peer operation is sync, this is to prevent\n * long-lived peer operations causing deadlocks over the datastore\n * which can happen if they try to access the peer store during the\n * loop\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.forEach(peer => {\n * // ...\n * })\n * ```\n */\n forEach(fn: (peer: Peer) => void, query?: PeerQuery): Promise<void>\n\n /**\n * Returns all peers in the peer store.\n *\n * @example\n *\n * ```TypeScript\n * for (const peer of await peerStore.all()) {\n * // ...\n * }\n * ```\n */\n all(query?: PeerQuery): Promise<Peer[]>\n\n /**\n * Delete all data stored for the passed peer\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.addressBook.set(peerId, multiaddrs)\n * await peerStore.addressBook.get(peerId)\n * // multiaddrs[]\n *\n * await peerStore.delete(peerId)\n *\n * await peerStore.addressBook.get(peerId)\n * // []\n * ```\n */\n delete(peerId: PeerId): Promise<void>\n\n /**\n * Returns true if the passed PeerId is in the peer store\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.has(peerId)\n * // false\n * await peerStore.addressBook.add(peerId, multiaddrs)\n * await peerStore.has(peerId)\n * // true\n * ```\n */\n has(peerId: PeerId): Promise<boolean>\n\n /**\n * Returns all data stored for the passed PeerId\n *\n * @example\n *\n * ```TypeScript\n * const peer = await peerStore.get(peerId)\n * // { .. }\n * ```\n */\n get(peerId: PeerId): Promise<Peer>\n\n /**\n * Returns a PeerInfo object for the passed peer id. This is similar to `get`\n * except the returned value contains fewer fields and is often used to\n * exchange peer information with other systems.\n *\n * The returned object can be passed to `JSON.stringify` without any\n * additional processing.\n *\n * @see https://docs.libp2p.io/concepts/fundamentals/peers/#peer-info\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await peerStore.getInfo(peerId)\n *\n * console.info(JSON.stringify(peerInfo))\n * // {\n * // id: 'peerId'\n * // multiaddrs: [\n * // '...'\n * // ]\n * // }\n * ```\n */\n getInfo (peerId: PeerId): Promise<PeerInfo>\n\n /**\n * Adds a peer to the peer store, overwriting any existing data\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.save(peerId, {\n * multiaddrs\n * })\n * ```\n */\n save(id: PeerId, data: PeerData): Promise<Peer>\n\n /**\n * Adds a peer to the peer store, overwriting only the passed fields\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.patch(peerId, {\n * multiaddrs\n * })\n * ```\n */\n patch(id: PeerId, data: PeerData): Promise<Peer>\n\n /**\n * Adds a peer to the peer store, deeply merging any existing data.\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.merge(peerId, {\n * multiaddrs\n * })\n * ```\n */\n merge(id: PeerId, data: PeerData): Promise<Peer>\n\n /**\n * Unmarshal and verify a signed peer record, extract the multiaddrs and\n * overwrite the stored addresses for the peer.\n *\n * Optionally pass an expected PeerId to verify that the peer record was\n * signed by that peer.\n *\n * @example\n *\n * ```TypeScript\n * await peerStore.consumePeerRecord(buf, expectedPeer)\n * ```\n */\n consumePeerRecord(buf: Uint8Array, expectedPeer?: PeerId): Promise<boolean>\n}\n", "import type { Connection, ConnectionLimits, MultiaddrConnection } from './connection.js'\nimport type { TypedEventTarget } from './event-target.js'\nimport type { AbortOptions, ClearableSignal, ConnectionEncrypter } from './index.js'\nimport type { StreamMuxerFactory } from './stream-muxer.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\nexport interface ListenerEvents {\n /**\n * This event signals to the transport manager that the listening addresses\n * have changed and may be emitted at any point and/or multiple times\n */\n 'listening': CustomEvent\n\n /**\n * Emitted if listening on an address failed\n */\n 'error': CustomEvent<Error>\n\n /**\n * Emitted when the listener has been shut down, has no open connections and\n * will no longer accept new connections\n */\n 'close': CustomEvent\n}\n\nexport interface Listener extends TypedEventTarget<ListenerEvents> {\n /**\n * Start a listener\n */\n listen(multiaddr: Multiaddr): Promise<void>\n /**\n * Get listen addresses\n */\n getAddrs(): Multiaddr[]\n /**\n * Close listener\n *\n * @returns {Promise<void>}\n */\n close(): Promise<void>\n /**\n * Allows transports to amend announce addresses - to add certificate hashes\n * or other metadata that cannot be known before runtime\n */\n updateAnnounceAddrs(addrs: Multiaddr[]): void\n}\n\nexport const transportSymbol = Symbol.for('@libp2p/transport')\n\n/**\n * A filter that acts on a list of multiaddrs\n */\nexport interface MultiaddrFilter {\n (multiaddrs: Multiaddr[]): Multiaddr[]\n}\n\nexport interface CreateListenerOptions {\n /**\n * The upgrader turns a MultiaddrConnection into a Connection and notifies\n * other libp2p components about a new incoming connection.\n */\n upgrader: Upgrader\n}\n\nexport interface DialTransportOptions<DialEvents extends ProgressEvent = ProgressEvent> extends Required<AbortOptions>, ProgressOptions<DialEvents> {\n /**\n * The upgrader turns a MultiaddrConnection into a Connection which should be\n * returned by the transport's dial method\n */\n upgrader: Upgrader\n}\n\n/**\n * A libp2p transport offers dial and listen methods to establish connections.\n */\nexport interface Transport<DialEvents extends ProgressEvent = ProgressEvent> {\n /**\n * Used to identify the transport\n */\n [Symbol.toStringTag]: string\n\n /**\n * Used by the isTransport function\n */\n [transportSymbol]: true\n\n /**\n * Dial a given multiaddr.\n */\n dial(ma: Multiaddr, options: DialTransportOptions<DialEvents>): Promise<Connection>\n\n /**\n * Create transport listeners.\n */\n createListener(options: CreateListenerOptions): Listener\n\n /**\n * Takes a list of `Multiaddr`s and returns only addresses that are valid for\n * the transport to listen on\n */\n listenFilter: MultiaddrFilter\n\n /**\n * Takes a list of `Multiaddr`s and returns only addresses that are valid for\n * the transport to dial\n */\n dialFilter: MultiaddrFilter\n}\n\n/**\n * Used to disambiguate transport implementations\n */\nexport function isTransport (other?: any): other is Transport {\n return other != null && Boolean(other[transportSymbol])\n}\n\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport enum FaultTolerance {\n /**\n * should be used for failing in any listen circumstance\n */\n FATAL_ALL = 0,\n\n /**\n * should be used for not failing when not listening\n */\n NO_FATAL\n}\n\n/**\n * Options accepted by the upgrader during connection establishment\n */\nexport interface UpgraderOptions<ConnectionUpgradeEvents extends ProgressEvent = ProgressEvent> extends ProgressOptions<ConnectionUpgradeEvents>, Required<AbortOptions> {\n /**\n * If true the invoking transport is expected to implement it's own encryption\n * and an encryption protocol will not attempted to be negotiated via\n * multi-stream select\n *\n * @default false\n */\n skipEncryption?: boolean\n\n /**\n * If true no connection protection will be performed on the connection.\n */\n skipProtection?: boolean\n\n /**\n * By default a stream muxer protocol will be negotiated via multi-stream\n * select after an encryption protocol has been agreed on.\n *\n * If a transport provides it's own stream muxing facility pass a muxer\n * factory instance here to skip muxer negotiation.\n */\n muxerFactory?: StreamMuxerFactory\n\n /**\n * If the connection is to have limits applied to it, pass them here\n */\n limits?: ConnectionLimits\n\n /**\n * Multi-stream select is a initiator/responder protocol. By default a\n * connection returned from `upgrader.upgradeOutbound` will be the initiator\n * and one returned from `upgrader.upgradeInbound` will be the responder.\n *\n * Pass a value here to override the default.\n */\n initiator?: boolean\n}\n\nexport type InboundConnectionUpgradeEvents =\nProgressEvent<'upgrader:encrypt-inbound-connection'> |\nProgressEvent<'upgrader:multiplex-inbound-connection'>\n\nexport type OutboundConnectionUpgradeEvents =\nProgressEvent<'upgrader:encrypt-outbound-connection'> |\nProgressEvent<'upgrader:multiplex-outbound-connection'>\n\nexport interface Upgrader {\n /**\n * Upgrades an outbound connection created by the `dial` method of a transport\n */\n upgradeOutbound(maConn: MultiaddrConnection, opts?: UpgraderOptions<OutboundConnectionUpgradeEvents>): Promise<Connection>\n\n /**\n * Upgrades an inbound connection received by a transport listener and\n * notifies other libp2p components about the new connection\n */\n upgradeInbound(maConn: MultiaddrConnection, opts?: UpgraderOptions<InboundConnectionUpgradeEvents>): Promise<void>\n\n /**\n * Used by transports that perform part of the upgrade process themselves and\n * do some async work. This allows configuring inbound upgrade timeouts from a\n * single location.\n *\n * Regular transports should just pass the signal from their shutdown\n * controller to `upgradeInbound`.\n */\n createInboundAbortSignal (signal: AbortSignal): ClearableSignal\n\n /**\n * Returns configured stream muxers\n */\n getStreamMuxers (): Map<string, StreamMuxerFactory>\n\n /**\n * Returns configured connection encrypters\n */\n getConnectionEncrypters (): Map<string, ConnectionEncrypter>\n}\n", "/**\n * 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", "/**\n * Implemented by components that have a life cycle\n */\nexport interface Startable {\n /**\n * If implemented, this method will be invoked before the start method.\n *\n * It should not assume any other components have been started.\n */\n beforeStart?(): void | Promise<void>\n\n /**\n * This method will be invoked to start the component.\n *\n * It should not assume that any other components have been started.\n */\n start(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the start method.\n *\n * All other components will have had their start method invoked before this method is called.\n */\n afterStart?(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked before the stop method.\n *\n * Any other components will still be running when this method is called.\n */\n beforeStop?(): void | Promise<void>\n\n /**\n * This method will be invoked to stop the component.\n *\n * It should not assume any other components are running when it is called.\n */\n stop(): void | Promise<void>\n\n /**\n * If implemented, this method will be invoked after the stop method.\n *\n * All other components will have had their stop method invoked before this method is called.\n */\n afterStop?(): void | Promise<void>\n}\n\n/**\n * Returns `true` if the object has type overlap with `Startable`\n */\nexport function isStartable (obj?: any): obj is Startable {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function'\n}\n\n/**\n * A function that can be used to start and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { start } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await start(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function start (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStart != null) {\n await s.beforeStart()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.start()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStart != null) {\n await s.afterStart()\n }\n })\n )\n}\n\n/**\n * A function that can be used to stop and objects passed to it. This checks\n * that an object is startable before invoking its lifecycle methods so it is\n * safe to pass non-`Startable`s in.\n *\n * @example\n *\n * ```TypeScript\n * import { stop } from '@libp2p/interface'\n * import type { Startable } from '@libp2p/interface'\n *\n * const startable: Startable = {\n * start: () => {},\n * stop: () => {}\n * }\n *\n * const notStartable = 5\n *\n * await stop(\n * startable,\n * notStartable\n * )\n * ```\n */\nexport async function stop (...objs: any[]): Promise<void> {\n const startables: Startable[] = []\n\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj)\n }\n }\n\n await Promise.all(\n startables.map(async s => {\n if (s.beforeStop != null) {\n await s.beforeStop()\n }\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n await s.stop()\n })\n )\n\n await Promise.all(\n startables.map(async s => {\n if (s.afterStop != null) {\n await s.afterStop()\n }\n })\n )\n}\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions, Stream } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { TypedEventTarget } from './event-target.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions } from './stream-handler.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n 'start': CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n 'stop': CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './content-routing.js'\nexport * from './keys.js'\nexport * from './metrics.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './pubsub.js'\nexport * from './record.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './topology.js'\nexport * from './transport.js'\nexport * from './errors.js'\nexport * from './event-target.js'\nexport * from './events.js'\nexport * from './startable.js'\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 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\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, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\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 = codes[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\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 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, alphabet, 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 { type Digest } from 'multiformats/hashes/digest'\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 { 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", "/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\nimport type { Codec } from './codec.js'\n\nexport interface FieldDef {\n name: string\n codec: Codec<any>\n optional?: true\n repeats?: true\n packed?: true\n}\n\nexport {\n decodeMessage\n} from './decode.js'\n\nexport {\n encodeMessage\n} from './encode.js'\n\nexport { enumeration } from './codecs/enum.js'\nexport { message } from './codecs/message.js'\nexport { createReader as reader } from './utils/reader.js'\nexport { createWriter as writer } from './utils/writer.js'\nexport type { Codec, EncodeOptions, DecodeOptions } from './codec.js'\n\nexport interface Writer {\n /**\n * Current length\n */\n len: number\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value: number): this\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value: number): this\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value: string): this\n\n /**\n * Writes a boolish value as a varint\n */\n bool(value: boolean): this\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value: number): this\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value: bigint): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value: number): this\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value: string): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value: bigint): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value: number): this\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value: string): this\n\n /**\n * Writes a float (32 bit)\n */\n float(value: number): this\n\n /**\n * Writes a double (64 bit float)\n */\n double(value: number): this\n\n /**\n * Writes a sequence of bytes\n */\n bytes(value: Uint8Array): this\n\n /**\n * Writes a string\n */\n string(value: string): this\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork(): this\n\n /**\n * Resets this instance to the last state.\n */\n reset(): this\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim(): this\n\n /**\n * Finishes the write operation\n */\n finish(): Uint8Array\n}\n\nexport interface Reader {\n /**\n * Read buffer\n */\n buf: Uint8Array\n\n /**\n * Read buffer position\n */\n pos: number\n\n /**\n * Read buffer length\n */\n len: number\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32(): number\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32(): number\n\n /**\n * Reads a varint as a boolean\n */\n bool(): boolean\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32(): number\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32(): number\n\n /**\n * Reads a float (32 bit) as a number\n */\n float(): number\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double(): number\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes(): Uint8Array\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string(): string\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varints`\n */\n skip(length?: number): void\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType: number): void\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64(): bigint\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64Number(): number\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64String(): string\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64(): bigint\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64Number(): number\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64String(): string\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64(): bigint\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64Number(): number\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64String(): string\n\n /**\n * Reads fixed 64 bits\n */\n fixed64(): bigint\n\n /**\n * Reads fixed 64 bits\n */\n fixed64Number(): number\n\n /**\n * Reads fixed 64 bits\n */\n fixed64String(): string\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64(): bigint\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64Number(): number\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64String(): string\n}\n\n/**\n * This will be removed in a future release\n *\n * @deprecated\n */\nexport class CodeError extends Error {\n public code: string\n\n constructor (message: string, code: string) {\n super(message)\n\n this.code = code\n }\n}\n\n/**\n * Thrown when a repeated field has too many elements\n */\nexport class MaxLengthError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_MAX_LENGTH'\n public name = 'MaxLengthError'\n}\n\n/**\n * Thrown when a map has too many elements\n */\nexport class MaxSizeError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_MAX_SIZE'\n public name = 'MaxSizeError'\n}\n\nexport class ParseError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_PARSE_ERROR'\n public name = 'ParseError'\n}\n\nexport class NoMessagesFoundError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n public code = 'ERR_NO_MESSAGES_FOUND'\n public name = 'NoMessagesFoundError'\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, enumeration, message } 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 { type Digest } from 'multiformats/hashes/digest'\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 { 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) throw new Error('byte array longer than desired length')\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, type MultibaseDecoder } 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 { 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", "/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent<T extends string = any, D = unknown> {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent<D = unknown, T extends string = any> extends Event implements ProgressEvent<T, D> {\n public type: T\n public detail: D\n\n constructor (type: T, detail?: D) {\n super(type)\n\n this.type = type\n // @ts-expect-error detail may be undefined\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions<MyOperationProgressEvents> {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions<Event extends ProgressEvent = any> {\n onProgress?: (evt: Event) => void\n}\n", "import 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", "import { RecordType } from '../index.js'\n\nexport function getTypes (types?: RecordType | RecordType[]): RecordType[] {\n const DEFAULT_TYPES = [\n RecordType.A\n ]\n\n if (types == null) {\n return DEFAULT_TYPES\n }\n\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES\n }\n\n return types\n }\n\n return [\n types\n ]\n}\n", "import { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RecordType, type DNSResponse } from '../index.js'\n\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60\n\nexport function toDNSResponse (obj: any): DNSResponse {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question: any) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n }\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer: any) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n }\n })\n }\n}\n", "/* eslint-env browser */\n\nimport PQueue from 'p-queue'\nimport { CustomProgressEvent } from 'progress-events'\nimport { RecordType, type DNSResponse } from '../index.js'\nimport { getTypes } from '../utils/get-types.js'\nimport { toDNSResponse } from '../utils/to-dns-response.js'\nimport type { DNSResolver } from './index.js'\n\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4\n\nexport interface DNSJSONOverHTTPSOptions {\n queryConcurrency?: number\n}\n\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps (url: string, init: DNSJSONOverHTTPSOptions = {}): DNSResolver {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n })\n\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams()\n searchParams.set('name', fqdn)\n\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type])\n })\n\n options.onProgress?.(new CustomProgressEvent<string>('dns:query', { detail: fqdn }))\n\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n })\n\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`)\n }\n\n const response = toDNSResponse(await res.json())\n\n options.onProgress?.(new CustomProgressEvent<DNSResponse>('dns:response', { detail: response }))\n\n return response\n }, {\n signal: options.signal\n })\n\n if (response == null) {\n throw new Error('No DNS response received')\n }\n\n return response\n }\n}\n", "import { dnsJsonOverHttps } from './dns-json-over-https.js'\nimport type { DNSResolver } from './index.js'\n\nexport function defaultResolver (): DNSResolver[] {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ]\n}\n", "import hashlru from 'hashlru'\nimport { RecordType } from '../index.js'\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js'\nimport type { Answer, DNSResponse } from '../index.js'\n\ninterface CachedAnswer {\n expires: number\n value: Answer\n}\n\nexport interface AnswerCache {\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined\n add (domain: string, answer: Answer): void\n remove (domain: string, type: ResponseType): void\n clear (): void\n}\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n private readonly lru: ReturnType<typeof hashlru>\n\n constructor (maxSize: number) {\n this.lru = hashlru(maxSize)\n }\n\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined {\n let foundAllAnswers = true\n const answers: Answer[] = []\n\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type)\n\n if (cached.length === 0) {\n foundAllAnswers = false\n break\n }\n\n answers.push(...cached)\n }\n\n if (foundAllAnswers) {\n return toDNSResponse({ answers })\n }\n }\n\n private getAnswers (domain: string, type: RecordType): Answer[] {\n const key = `${domain.toLowerCase()}-${type}`\n const answers: CachedAnswer[] = this.lru.get(key)\n\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now()\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }))\n\n if (cachedAnswers.length === 0) {\n this.lru.remove(key)\n }\n\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers\n }\n\n return []\n }\n\n add (domain: string, answer: Answer): void {\n const key = `${domain.toLowerCase()}-${answer.type}`\n\n const answers: CachedAnswer[] = this.lru.get(key) ?? []\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n })\n\n this.lru.set(key, answers)\n }\n\n remove (domain: string, type: ResponseType): void {\n const key = `${domain.toLowerCase()}-${type}`\n\n this.lru.remove(key)\n }\n\n clear (): void {\n this.lru.clear()\n }\n}\n\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache (size: number): AnswerCache {\n return new CachedAnswers(size)\n}\n", "import { CustomProgressEvent } from 'progress-events'\nimport { defaultResolver } from './resolvers/default.js'\nimport { cache } from './utils/cache.js'\nimport { getTypes } from './utils/get-types.js'\nimport type { DNS as DNSInterface, DNSInit, DNSResponse, QueryOptions } from './index.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { AnswerCache } from './utils/cache.js'\n\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000\n\nexport class DNS implements DNSInterface {\n private readonly resolvers: Record<string, DNSResolver[]>\n private readonly cache: AnswerCache\n\n constructor (init: DNSInit) {\n this.resolvers = {}\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE)\n\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver]\n }\n\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`\n }\n\n this.resolvers[tld] = resolver\n })\n\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver()\n }\n }\n\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query (domain: string, options: QueryOptions = {}): Promise<DNSResponse> {\n const types = getTypes(options.types)\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined\n\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent<string>('dns:cache', { detail: cached }))\n\n return cached\n }\n\n const tld = `${domain.split('.').pop()}.`\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1\n })\n\n const errors: Error[] = []\n\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break\n }\n\n try {\n const result = await resolver(domain, {\n ...options,\n types\n })\n\n for (const answer of result.Answer) {\n this.cache.add(domain, answer)\n }\n\n return result\n } catch (err: any) {\n errors.push(err)\n options.onProgress?.(new CustomProgressEvent<Error>('dns:error', { detail: err }))\n }\n }\n\n if (errors.length === 1) {\n throw errors[0]\n }\n\n throw new AggregateError(errors, `DNS lookup of ${domain} ${types} failed`)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\n\nimport { DNS as DNSClass } from './dns.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport enum RecordType {\n A = 1,\n CNAME = 5,\n TXT = 16,\n AAAA = 28\n}\n\nexport interface Question {\n /**\n * The record name requested.\n */\n name: string\n\n /**\n * The type of DNS record requested.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\n type: RecordType\n}\n\nexport interface Answer {\n /**\n * The record owner.\n */\n name: string\n\n /**\n * The type of DNS record.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4\n */\n type: RecordType\n\n /**\n * The number of seconds the answer can be stored in cache before it is\n * considered stale.\n */\n TTL: number\n\n /**\n * The value of the DNS record for the given name and type. The data will be\n * in text for standardized record types and in hex for unknown types.\n */\n data: string\n}\n\nexport interface DNSResponse {\n /**\n * The Response Code of the DNS Query.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n */\n Status: number\n\n /**\n * If true, it means the truncated bit was set. This happens when the DNS\n * answer is larger than a single UDP or TCP packet.\n */\n TC: boolean\n\n /**\n * If true, it means the Recursive Desired bit was set.\n */\n RD: boolean\n\n /**\n * If true, it means the Recursion Available bit was set.\n */\n RA: boolean\n\n /**\n * If true, it means that every record in the answer was verified with DNSSEC.\n */\n AD: boolean\n\n /**\n * If true, the client asked to disable DNSSEC validation.\n */\n CD: boolean\n\n /**\n * The records that were requested.\n */\n Question: Question[]\n\n /**\n * Values for the records that were requested.\n */\n Answer: Answer[]\n}\n\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32\n\nexport interface QueryOptions extends ProgressOptions<ResolveDnsProgressEvents> {\n signal?: AbortSignal\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n cached?: boolean\n\n /**\n * The type or types of DNS records to resolve\n *\n * @default [RecordType.A, RecordType.AAAA]\n */\n types?: RecordType | RecordType[]\n}\n\nexport interface DNS {\n query(fqdn: string, options?: QueryOptions): Promise<DNSResponse>\n}\n\nexport type ResolveDnsProgressEvents =\n ProgressEvent<'dns:cache', string> |\n ProgressEvent<'dns:query', string> |\n ProgressEvent<'dns:response', DNSResponse> |\n ProgressEvent<'dns:error', Error>\n\nexport type DNSResolvers = Record<string, DNSResolver | DNSResolver[]>\n\nexport interface DNSInit {\n /**\n * A set of resolvers used to answer DNS queries\n *\n * String keys control which resolvers are used for which TLDs.\n *\n * @example\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns'\n *\n * const resolver = dns({\n * resolvers: {\n * // only used for .com domains\n * 'com.': dnsOverHttps('https://example-1.com'),\n *\n * // only used for .net domains, can be an array\n * 'net.': [\n * dnsOverHttps('https://example-2.com'),\n * dnsOverHttps('https://example-3.com'),\n * ],\n *\n * // used for everything else (can be an array)\n * '.': dnsOverHttps('https://example-4.com')\n * }\n * })\n * ```\n */\n resolvers?: DNSResolvers\n\n /**\n * To avoid repeating DNS lookups, successful answers are cached according to\n * their TTL. To avoid exhausting memory, this option controls how many\n * answers to cache.\n *\n * @default 1000\n */\n cacheSize?: number\n}\n\nexport function dns (init: DNSInit = {}): DNS {\n return new DNSClass(init)\n}\n", "/* eslint-disable @typescript-eslint/no-unsafe-return */\n\n// Heavily inspired by https://doc.rust-lang.org/src/std/net/parser.rs.html\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn = (...foo: any) => any;\n\nexport class Parser {\n private index = 0;\n private input = \"\";\n\n new(input: string): this {\n this.index = 0;\n this.input = input;\n return this;\n }\n\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically<T extends Fn>(fn: T): ReturnType<T> {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith<T extends Fn>(fn: T): ReturnType<T> | undefined {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n\n /** Peek the next character from the input */\n peekChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n\n /** Read the next character from the input */\n readChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target: string): string | undefined {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator<T extends Fn>(sep: string, index: number, inner: T): ReturnType<T> {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(\n radix: number,\n maxDigits: number | undefined,\n allowZeroPrefix: boolean,\n maxBytes: number\n ): number | undefined {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n\n if (digitCount === 0) {\n return undefined;\n } else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n } else {\n return result;\n }\n });\n }\n\n /** Read an IPv4 address. */\n readIPv4Addr(): Uint8Array | undefined {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n\n return out;\n });\n }\n\n /** Read an IPv6 Address. */\n readIPv6Addr(): Uint8Array | undefined {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups: Uint8Array): [number, boolean] => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n\n return [ix + 4, true];\n }\n }\n\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n\n if (headSize === 16) {\n return head;\n }\n\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n\n return head;\n });\n }\n\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr(): Uint8Array | undefined {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n", "import { Parser } from \"./parser.js\";\n\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\n\nconst parser = new Parser();\n\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n\n/** Parse IPv4 `input` into IPv6 with IPv4-mapped bytes, eg ::ffff:1.2.3.4 */\nexport function parseIPv4Mapped(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n\n const ipv4 = parser.new(input).parseWith(() => parser.readIPv4Addr());\n if (ipv4 === undefined) {\n return undefined;\n }\n\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, ipv4[0], ipv4[1], ipv4[2], ipv4[3]]);\n}\n\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input: string): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input: string, mapIPv4ToIPv6 = false): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n\n const addr = parser.new(input).parseWith(() => parser.readIPAddr());\n if (!addr) {\n return undefined;\n }\n\n if (mapIPv4ToIPv6 && addr.length === 4) {\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);\n }\n\n return addr;\n}\n", "import { IPv4Len, IPv6Len } from \"./ip.js\";\n\nexport function allFF(\n a: number[] | Uint8Array,\n from: number,\n to: number\n): boolean {\n let i = 0;\n for (const e of a) {\n if (i < from) continue;\n if (i > to) break;\n if (e !== 0xff) return false;\n i++;\n }\n return true;\n}\n\nexport function deepEqual(\n a: Uint8Array | number[],\n b: Uint8Array,\n from: number,\n to: number\n): boolean {\n let i = 0;\n for (const e of a) {\n if (i < from) continue;\n if (i > to) break;\n if (e !== b[i]) return false;\n i++;\n }\n return true;\n}\n\n/***\n * Returns long ip format\n */\nexport function ipToString(ip: Uint8Array | number[]): string {\n switch (ip.length) {\n case IPv4Len: {\n return ip.join(\".\");\n }\n case IPv6Len: {\n const result = [] as string[];\n for (let i = 0; i < ip.length; i++) {\n if (i % 2 === 0) {\n result.push(\n ip[i].toString(16).padStart(2, \"0\") +\n ip[i + 1].toString(16).padStart(2, \"0\")\n );\n }\n }\n return result.join(\":\");\n }\n default: {\n throw new Error(\"Invalid ip length\");\n }\n }\n}\n\n/**\n * If mask is a sequence of 1 bits followed by 0 bits, return number of 1 bits else -1\n */\nexport function simpleMaskLength(mask: Uint8Array): number {\n let ones = 0;\n // eslint-disable-next-line prefer-const\n for (let [index, byte] of mask.entries()) {\n if (byte === 0xff) {\n ones += 8;\n continue;\n }\n while ((byte & 0x80) != 0) {\n ones++;\n byte = byte << 1;\n }\n if ((byte & 0x80) != 0) {\n return -1;\n }\n for (let i = index + 1; i < mask.length; i++) {\n if (mask[i] != 0) {\n return -1;\n }\n }\n break;\n }\n return ones;\n}\n\nexport function maskToHex(mask: Uint8Array): string {\n let hex = \"0x\";\n for (const byte of mask) {\n hex += (byte >> 4).toString(16) + (byte & 0x0f).toString(16);\n }\n return hex;\n}\n", "import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\n\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\n\nexport const maxIPv6Octet = parseInt(\"0xFFFF\", 16);\nexport const ipv4Prefix = new Uint8Array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255,\n]);\n\nexport interface IpNetRaw {\n network: Uint8Array;\n mask: Uint8Array;\n}\n\nexport function maskIp(ip: Uint8Array, mask: Uint8Array): Uint8Array {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (\n mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)\n ) {\n ip = ip.slice(12);\n }\n const n = ip.length;\n if (n != mask.length) {\n throw new Error(\"Failed to mask ip\");\n }\n const out = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n out[i] = ip[i] & mask[i];\n }\n return out;\n}\n\nexport function containsIp(\n net: IpNetRaw,\n ip: Uint8Array | number[] | string\n): boolean {\n if (typeof ip === \"string\") {\n ip = parseIP(ip)!;\n }\n if (ip == null) throw new Error(\"Invalid ip\");\n if (ip.length !== net.network.length) {\n return false;\n }\n for (let i = 0; i < ip.length; i++) {\n if ((net.network[i] & net.mask[i]) !== (ip[i] & net.mask[i])) {\n return false;\n }\n }\n return true;\n}\n\nexport function iPv4FromIPv6(ip: Uint8Array): Uint8Array {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\n\nexport function isIPv4mappedIPv6(ip: Uint8Array | number[]): boolean {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n", "import { parseIPv4, parseIPv6 } from \"@chainsafe/is-ip/parse\";\nimport { IPv4Len, IPv6Len, maskIp } from \"./ip.js\";\n\nexport function parseCidr(s: string): {\n network: Uint8Array;\n mask: Uint8Array;\n} {\n const [address, maskString] = s.split(\"/\");\n if (!address || !maskString)\n throw new Error(\"Failed to parse given CIDR: \" + s);\n let ipLength = IPv4Len;\n let ip = parseIPv4(address);\n if (ip == null) {\n ipLength = IPv6Len;\n ip = parseIPv6(address);\n if (ip == null) throw new Error(\"Failed to parse given CIDR: \" + s);\n }\n const m = parseInt(maskString, 10);\n if (\n Number.isNaN(m) ||\n String(m).length !== maskString.length ||\n m < 0 ||\n m > ipLength * 8\n ) {\n throw new Error(\"Failed to parse given CIDR: \" + s);\n }\n const mask = cidrMask(m, 8 * ipLength);\n return {\n network: maskIp(ip, mask),\n mask,\n };\n}\n\nexport function cidrMask(ones: number, bits: number): Uint8Array {\n if (bits !== 8 * IPv4Len && bits !== 8 * IPv6Len)\n throw new Error(\"Invalid CIDR mask\");\n if (ones < 0 || ones > bits) throw new Error(\"Invalid CIDR mask\");\n const l = bits / 8;\n const m = new Uint8Array(l);\n for (let i = 0; i < l; i++) {\n if (ones >= 8) {\n m[i] = 0xff;\n ones -= 8;\n continue;\n }\n m[i] = 255 - (0xff >> ones);\n ones = 0;\n }\n return m;\n}\n", "import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { cidrMask, parseCidr } from \"./cidr.js\";\nimport { containsIp, maskIp } from \"./ip.js\";\nimport { ipToString, maskToHex, simpleMaskLength } from \"./util.js\";\n\nexport class IpNet {\n public readonly network: Uint8Array;\n public readonly mask: Uint8Array;\n\n /**\n *\n * @param ipOrCidr either network ip or full cidr address\n * @param mask in case ipOrCidr is network this can be either mask in decimal format or as ip address\n */\n constructor(ipOrCidr: string, mask?: string | number) {\n if (mask == null) {\n ({ network: this.network, mask: this.mask } = parseCidr(ipOrCidr));\n } else {\n const ipResult = parseIP(ipOrCidr);\n if (ipResult == null) {\n throw new Error(\"Failed to parse network\");\n }\n mask = String(mask);\n const m = parseInt(mask, 10);\n if (\n Number.isNaN(m) ||\n String(m).length !== mask.length ||\n m < 0 ||\n m > ipResult.length * 8\n ) {\n const maskResult = parseIP(mask);\n if (maskResult == null) {\n throw new Error(\"Failed to parse mask\");\n }\n this.mask = maskResult;\n } else {\n this.mask = cidrMask(m, 8 * ipResult.length);\n }\n this.network = maskIp(ipResult, this.mask);\n }\n }\n\n /**\n * Checks if netmask contains ip address\n * @param ip\n * @returns\n */\n contains(ip: Uint8Array | number[] | string): boolean {\n return containsIp({ network: this.network, mask: this.mask }, ip);\n }\n\n /**Serializes back to string format */\n toString(): string {\n const l = simpleMaskLength(this.mask);\n const mask = l !== -1 ? String(l) : maskToHex(this.mask);\n return ipToString(this.network) + \"/\" + mask;\n }\n}\n", "import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n\n/** Check if `input` is IPv4. */\nexport function isIPv4(input: string): boolean {\n return Boolean(parseIPv4(input));\n}\n\n/** Check if `input` is IPv6. */\nexport function isIPv6(input: string): boolean {\n return Boolean(parseIPv6(input));\n}\n\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input: string): boolean {\n return Boolean(parseIP(input));\n}\n\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input: string): 4 | 6 | undefined {\n if (isIPv4(input)) {\n return 4;\n } else if (isIPv6(input)) {\n return 6;\n } else {\n return undefined;\n }\n}\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nexport { isIP } from '@chainsafe/is-ip'\nexport const isV4 = isIPv4\nexport const isV6 = isIPv6\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4)\n\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff\n })\n\n return bytes\n }\n\n if (isV6(ip)) {\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = toBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) sections.unshift('0')\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) sections.push('0')\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++);\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16)\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n }\n\n throw new Error('invalid ip address')\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf: Uint8Array, offset: number = 0, length?: number): string {\n offset = ~~offset\n length = length ?? (buf.length - offset)\n\n const view = new DataView(buf.buffer)\n\n if (length === 4) {\n const result = []\n\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i])\n }\n\n return result.join('.')\n }\n\n if (length === 16) {\n const result = []\n\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16))\n }\n\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n\n return ''\n}\n", "import type { Protocol } from './index.js'\n\nconst V = -1\nexport const names: Record<string, Protocol> = {}\nexport const codes: Record<number, Protocol> = {}\n\nexport const table: Array<[number, number, string, boolean?, boolean?]> = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [481, V, 'http-path'],\n [777, V, 'memory']\n]\n\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row)\n codes[proto.code] = proto\n names[proto.name] = proto\n})\n\nexport function createProtocol (code: number, size: number, name: string, resolvable?: any, path?: any): Protocol {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n }\n}\n\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol (proto: number | string): Protocol {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto]\n }\n\n throw new Error(`no protocol with code: ${proto}`)\n } else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto]\n }\n\n throw new Error(`no protocol with name: ${proto}`)\n }\n\n throw new Error(`invalid protocol id type: ${typeof proto}`)\n}\n", "import { IpNet } from '@chainsafe/netmask'\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { bases } from 'multiformats/basics'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as ip from './ip.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Multiaddr } from './index.js'\n\nconst ip4Protocol = getProtocol('ip4')\nconst ip6Protocol = getProtocol('ip6')\nconst ipcidrProtocol = getProtocol('ipcidr')\n\n/**\n * converts (serializes) addresses\n */\nexport function convert (proto: string, a: string): Uint8Array\nexport function convert (proto: string, a: Uint8Array): string\nexport function convert (proto: string, a: string | Uint8Array): Uint8Array | string {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a)\n } else {\n return convertToBytes(proto, a)\n }\n}\n\n/**\n * Convert [code,Uint8Array] to string\n */\n// eslint-disable-next-line complexity\nexport function convertToString (proto: number | string, buf: Uint8Array): string {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf)\n case 42: // ipv6zone\n return bytes2str(buf)\n case 43: // ipcidr\n return uint8ArrayToString(buf, 'base10')\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString()\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf)\n\n case 421: // ipfs\n return bytes2mh(buf)\n case 444: // onion\n return bytes2onion(buf)\n case 445: // onion3\n return bytes2onion(buf)\n case 466: // certhash\n return bytes2mb(buf)\n case 481: // http-path\n return globalThis.encodeURIComponent(bytes2str(buf))\n default:\n return uint8ArrayToString(buf, 'base16') // no clue. convert to hex\n }\n}\n\n// eslint-disable-next-line complexity\nexport function convertToBytes (proto: string | number, str: string): Uint8Array {\n const protocol = getProtocol(proto)\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str)\n case 41: // ipv6\n return ip2bytes(str)\n case 42: // ipv6zone\n return str2bytes(str)\n case 43: // ipcidr\n return uint8ArrayFromString(str, 'base10')\n\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10))\n\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str)\n\n case 421: // ipfs\n return mh2bytes(str)\n case 444: // onion\n return onion2bytes(str)\n case 445: // onion3\n return onion32bytes(str)\n case 466: // certhash\n return mb2bytes(str)\n case 481: // http-path\n return str2bytes(globalThis.decodeURIComponent(str))\n default:\n return uint8ArrayFromString(str, 'base16') // no clue. convert from hex\n }\n}\n\nexport function convertToIpNet (multiaddr: Multiaddr): IpNet {\n let mask: string | undefined\n let addr: string | undefined\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value\n }\n if (code === ipcidrProtocol.code) {\n mask = value\n }\n })\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr')\n }\n return new IpNet(addr, mask)\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nfunction ip2bytes (ipString: string): Uint8Array {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ip.toBytes(ipString)\n}\n\nfunction bytes2ip (ipBuff: Uint8Array): string {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length)\n if (ipString == null) {\n throw new Error('ipBuff is required')\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address')\n }\n return ipString\n}\n\nfunction port2bytes (port: number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, port)\n\n return new Uint8Array(buf)\n}\n\nfunction bytes2port (buf: Uint8Array): number {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset)\n}\n\nfunction str2bytes (str: string): Uint8Array {\n const buf = uint8ArrayFromString(str)\n const size = Uint8Array.from(varint.encode(buf.length))\n return uint8ArrayConcat([size, buf], size.length + buf.length)\n}\n\nfunction bytes2str (buf: Uint8Array): string {\n const size = varint.decode(buf)\n buf = buf.slice(varint.encodingLength(size))\n\n if (buf.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(buf)\n}\n\nfunction mh2bytes (hash: string): Uint8Array {\n let mh\n\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes\n } else {\n mh = CID.parse(hash).multihash.bytes\n }\n\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length))\n return uint8ArrayConcat([size, mh], size.length + mh.length)\n}\n\nfunction mb2bytes (mbstr: string): Uint8Array {\n const mb = anybaseDecoder.decode(mbstr)\n const size = Uint8Array.from(varint.encode(mb.length))\n return uint8ArrayConcat([size, mb], size.length + mb.length)\n}\nfunction bytes2mb (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const hash = buf.slice(varint.encodingLength(size))\n\n if (hash.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return 'u' + uint8ArrayToString(hash, 'base64url')\n}\n\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh (buf: Uint8Array): string {\n const size = varint.decode(buf)\n const address = buf.slice(varint.encodingLength(size))\n\n if (address.length !== size) {\n throw new Error('inconsistent lengths')\n }\n\n return uint8ArrayToString(address, 'base58btc')\n}\n\nfunction onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0])\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n const portBuf = port2bytes(port)\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nfunction bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.slice(0, buf.length - 2)\n const portBytes = buf.slice(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n", "import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { convertToBytes, convertToString } from './convert.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { StringTuple, Tuple, Protocol } from './index.js'\n\nexport interface MultiaddrParts {\n bytes: Uint8Array\n string: string\n tuples: Tuple[]\n stringTuples: StringTuple[]\n path: string | null\n}\n\nexport function stringToMultiaddrParts (str: string): MultiaddrParts {\n str = cleanPath(str)\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n const parts = str.split('/').slice(1)\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n }\n }\n\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p]\n const proto = getProtocol(part)\n\n if (proto.size === 0) {\n tuples.push([proto.code])\n stringTuples.push([proto.code])\n // eslint-disable-next-line no-continue\n continue\n }\n\n p++ // advance addr part\n if (p >= parts.length) {\n throw new ParseError('invalid address: ' + str)\n }\n\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'))\n tuples.push([proto.code, convertToBytes(proto.code, path)])\n stringTuples.push([proto.code, path])\n break\n }\n\n const bytes = convertToBytes(proto.code, parts[p])\n tuples.push([proto.code, bytes])\n stringTuples.push([proto.code, convertToString(proto.code, bytes)])\n }\n\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n }\n}\n\nexport function bytesToMultiaddrParts (bytes: Uint8Array): MultiaddrParts {\n const tuples: Tuple[] = []\n const stringTuples: StringTuple[] = []\n let path: string | null = null\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, bytes.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n stringTuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = bytes.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw new ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n const stringAddr = convertToString(code, addr)\n stringTuples.push([code, stringAddr])\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr\n break\n }\n }\n\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n }\n}\n\n/**\n * [[num code, str value?]... ] -> Tuple[]\n */\nexport function stringTuplesToTuples (stringTuples: StringTuple[]): Tuple[] {\n const tuples: Tuple[] = []\n\n stringTuples.forEach(([code, value]) => {\n const tuple: Tuple = [code]\n\n if (value != null) {\n tuple[1] = convertToBytes(code, value)\n }\n\n tuples.push(tuple)\n })\n\n return tuples\n}\n\n/**\n * [[num code, str value?]... ] -> string\n */\nfunction stringTuplesToString (tuples: StringTuple[]): string {\n const parts: string[] = []\n tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n parts.push(proto.name)\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1])\n }\n return null\n })\n\n return cleanPath(parts.join('/'))\n}\n\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes (tuples: Tuple[]): Uint8Array {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0])\n let buf = Uint8Array.from(varint.encode(proto.code))\n\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer\n }\n\n return buf\n }))\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (p: Protocol, addr: Uint8Array | number[]): number {\n if (p.size > 0) {\n return p.size / 8\n } else if (p.size === 0) {\n return 0\n } else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr))\n return size + varint.encodingLength(size)\n }\n}\n\nexport function bytesToTuples (buf: Uint8Array): Tuple[] {\n const tuples: Array<[number, Uint8Array?]> = []\n let i = 0\n while (i < buf.length) {\n const code = varint.decode(buf, i)\n const n = varint.encodingLength(code)\n\n const p = getProtocol(code)\n\n const size = sizeForAddr(p, buf.slice(i + n))\n\n if (size === 0) {\n tuples.push([code])\n i += n\n // eslint-disable-next-line no-continue\n continue\n }\n\n const addr = buf.slice(i + n, i + n + size)\n\n i += (size + n)\n\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw new ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'))\n }\n\n // ok, tuple seems good.\n tuples.push([code, addr])\n }\n\n return tuples\n}\n\nexport function cleanPath (str: string): string {\n return '/' + str.trim().split('/').filter((a) => a).join('/')\n}\n\nexport class ParseError extends Error {\n static name = 'ParseError'\n name = 'ParseError'\n\n constructor (str: string) {\n super(`Error parsing address: ${str}`)\n }\n}\n", "/* eslint-disable complexity */\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, type MultiaddrParts, tuplesToBytes } from './codec.js'\nimport { getProtocol, names } from './protocols-table.js'\nimport { isMultiaddr, multiaddr, resolvers } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, MultiaddrObject, Protocol, StringTuple, Tuple, NodeAddress, ResolveOptions } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr')\n\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n]\n\nclass NoAvailableResolverError extends Error {\n constructor (message = 'No available resolver') {\n super(message)\n this.name = 'NoAvailableResolverError'\n }\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n public bytes: Uint8Array\n readonly #string: string\n readonly #tuples: Tuple[]\n readonly #stringTuples: StringTuple[]\n readonly #path: string | null\n\n [symbol]: boolean = true\n\n constructor (addr?: MultiaddrInput) {\n // default\n if (addr == null) {\n addr = ''\n }\n\n let parts: MultiaddrParts\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr)\n } else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`)\n }\n parts = stringToMultiaddrParts(addr)\n } else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes)\n } else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr')\n }\n\n this.bytes = parts.bytes\n this.#string = parts.string\n this.#tuples = parts.tuples\n this.#stringTuples = parts.stringTuples\n this.#path = parts.path\n }\n\n toString (): string {\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n toOptions (): MultiaddrObject {\n let family: 4 | 6 | undefined\n let transport: 'tcp' | 'udp' | undefined\n let host: string | undefined\n let port: number | undefined\n let zone = ''\n\n const tcp = getProtocol('tcp')\n const udp = getProtocol('udp')\n const ip4 = getProtocol('ip4')\n const ip6 = getProtocol('ip6')\n const dns6 = getProtocol('dns6')\n const ip6zone = getProtocol('ip6zone')\n\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`\n }\n\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name === 'tcp' ? 'tcp' : 'udp'\n port = 443\n host = `${value ?? ''}${zone}`\n family = code === dns6.code ? 6 : 4\n }\n\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name === 'tcp' ? 'tcp' : 'udp'\n port = parseInt(value ?? '')\n }\n\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name === 'tcp' ? 'tcp' : 'udp'\n host = `${value ?? ''}${zone}`\n family = code === ip6.code ? 6 : 4\n }\n }\n\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".')\n }\n\n const opts: MultiaddrObject = {\n family,\n host,\n transport,\n port\n }\n\n return opts\n }\n\n protos (): Protocol[] {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)))\n }\n\n protoCodes (): number[] {\n return this.#tuples.map(([code]) => code)\n }\n\n protoNames (): string[] {\n return this.#tuples.map(([code]) => getProtocol(code).name)\n }\n\n tuples (): Array<[number, Uint8Array?]> {\n return this.#tuples.map(([code, value]) => {\n if (value == null) {\n return [code]\n }\n\n return [code, value]\n })\n }\n\n stringTuples (): Array<[number, string?]> {\n return this.#stringTuples.map(([code, value]) => {\n if (value == null) {\n return [code]\n }\n\n return [code, value]\n })\n }\n\n encapsulate (addr: MultiaddrInput): Multiaddr {\n addr = new Multiaddr(addr)\n return new Multiaddr(this.toString() + addr.toString())\n }\n\n decapsulate (addr: Multiaddr | string): Multiaddr {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`)\n }\n return new Multiaddr(s.slice(0, i))\n }\n\n decapsulateCode (code: number): Multiaddr {\n const tuples = this.tuples()\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)))\n }\n }\n return this\n }\n\n getPeerId (): string | null {\n try {\n let tuples: Array<[number, string | undefined]> = []\n\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name])\n }\n\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = []\n }\n })\n\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop()\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1]\n\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc')\n }\n\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc')\n }\n\n return null\n } catch (e) {\n return null\n }\n }\n\n getPath (): string | null {\n return this.#path\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n async resolve (options?: ResolveOptions): Promise<MultiaddrInterface[]> {\n const resolvableProto = this.protos().find((p) => p.resolvable)\n\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this]\n }\n\n const resolver = resolvers.get(resolvableProto.name)\n if (resolver == null) {\n throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`)\n }\n\n const result = await resolver(this, options)\n\n return result.map(str => multiaddr(str))\n }\n\n nodeAddress (): NodeAddress {\n const options = this.toOptions()\n\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`)\n }\n\n return {\n family: options.family,\n address: options.host,\n port: options.port\n }\n }\n\n isThinWaistAddress (addr?: Multiaddr): boolean {\n const protos = (addr ?? this).protos()\n\n if (protos.length !== 2) {\n return false\n }\n\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false\n }\n return true\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.#string})`\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // <Uint8Array 04 7f 00 00 01 11 04 d2>\n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddrResolver)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * }\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\nimport { stringTuplesToTuples, tuplesToBytes } from './codec.js'\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { getProtocol } from './protocols-table.js'\nimport type { Resolver } from './resolvers/index.js'\nimport type { DNS } from '@multiformats/dns'\n\n/**\n * Protocols are present in the protocol table\n */\nexport interface Protocol {\n code: number\n size: number\n name: string\n resolvable?: boolean | undefined\n path?: boolean | undefined\n}\n\n/**\n * A plain JavaScript object representation of a {@link Multiaddr}\n */\nexport interface MultiaddrObject {\n family: 4 | 6\n host: string\n transport: 'tcp' | 'udp'\n port: number\n}\n\n/**\n * A NodeAddress is an IPv4/IPv6 address/TCP port combination\n */\nexport interface NodeAddress {\n family: 4 | 6\n address: string\n port: number\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null\n\n/**\n * A code/value pair\n */\nexport type Tuple = [number, Uint8Array?]\n\n/**\n * A code/value pair with the value as a string\n */\nexport type StringTuple = [number, string?]\n\n/**\n * Allows aborting long-lived operations\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map<string, Resolver>()\n\nexport type { Resolver }\n\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js'\n\nexport interface ResolveOptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns Multiaddr as a convinient options object to be used with net.createConnection\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions()\n * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 }\n * ```\n */\n toOptions(): MultiaddrObject\n\n /**\n * Returns the protocols the Multiaddr is defined with, as an array of objects, in\n * left-to-right order. Each object contains the protocol code, protocol name,\n * and the size of its address space in bits.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protos()\n * // [ { code: 4, size: 32, name: 'ip4' },\n * // { code: 6, size: 16, name: 'tcp' } ]\n * ```\n */\n protos(): Protocol[]\n\n /**\n * Returns the codes of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes()\n * // [ 4, 6 ]\n * ```\n */\n protoCodes(): number[]\n\n /**\n * Returns the names of the protocols in left-to-right order.\n * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv)\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames()\n * // [ 'ip4', 'tcp' ]\n * ```\n */\n protoNames(): string[]\n\n /**\n * Returns a tuple of parts\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').tuples()\n * // [ [ 4, <Buffer 7f 00 00 01> ], [ 6, <Buffer 0f a1> ] ]\n * ```\n */\n tuples(): Tuple[]\n\n /**\n * Returns a tuple of string/number parts\n * - tuples[][0] = code of protocol\n * - tuples[][1] = contents of address\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').stringTuples()\n * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ]\n * ```\n */\n stringTuples(): StringTuple[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a\n * specific code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Extract the peerId if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string)\n *\n * // should return QmValidBase58string or null if the id is missing or invalid\n * const peerId = mh1.getPeerId()\n * ```\n */\n getPeerId(): string | null\n\n /**\n * Extract the path if the multiaddr contains one\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock)\n *\n * // should return utf8 string or null if the id is missing or invalid\n * const path = mh1.getPath()\n * ```\n */\n getPath(): string | null\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n\n /**\n * Resolve multiaddr if containing resolvable hostname.\n *\n * @example\n * ```js\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n *\n * resolvers.set('dnsaddr', resolverFunction)\n * const mh1 = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')\n * const resolvedMultiaddrs = await mh1.resolve()\n * // [\n * // Multiaddr(/ip4/147.75.83.83/tcp/4001/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/tcp/443/wss/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb),\n * // Multiaddr(/ip4/147.75.83.83/udp/4001/quic/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb)\n * // ]\n * ```\n */\n resolve(options?: ResolveOptions): Promise<Multiaddr[]>\n\n /**\n * Gets a Multiaddrs node-friendly address object. Note that protocol information\n * is left out: in Node (and most network systems) the protocol is unknowable\n * given only the address.\n *\n * Has to be a ThinWaist Address, otherwise throws error\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress()\n * // {family: 4, address: '127.0.0.1', port: 4001}\n * ```\n */\n nodeAddress(): NodeAddress\n\n /**\n * Returns if a Multiaddr is a Thin Waist address or not.\n *\n * Thin Waist is if a Multiaddr adheres to the standard combination of:\n *\n * `{IPv4, IPv6}/{TCP, UDP}`\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * const mh2 = multiaddr('/ip4/192.168.2.1/tcp/5001')\n * // Multiaddr(/ip4/192.168.2.1/tcp/5001)\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001)\n * const mh4 = multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a')\n * // Multiaddr(/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a)\n * mh1.isThinWaistAddress()\n * // true\n * mh2.isThinWaistAddress()\n * // true\n * mh3.isThinWaistAddress()\n * // false\n * mh4.isThinWaistAddress()\n * // false\n * ```\n */\n isThinWaistAddress(addr?: Multiaddr): boolean\n}\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress (addr: NodeAddress, transport: string): Multiaddr {\n if (addr == null) {\n throw new Error('requires node address object')\n }\n if (transport == null) {\n throw new Error('requires transport protocol')\n }\n let ip: string | undefined\n let host = addr.address\n switch (addr.family) {\n case 4:\n ip = 'ip4'\n break\n case 6:\n ip = 'ip6'\n\n if (host.includes('%')) {\n const parts = host.split('%')\n\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr')\n }\n\n host = parts[0]\n const zone = parts[1]\n ip = `/ip6zone/${zone}/ip6`\n }\n break\n default:\n throw Error('Invalid addr family, should be 4 or 6.')\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'))\n}\n\n/**\n * Create a {@link Multiaddr} from an array of {@link Tuple}s\n *\n * @example\n *\n * ```ts\n * import { fromTuples, multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1')\n * const tuples = ma.tuples()\n *\n * const ma2 = fromTuples(tuples)\n *\n * console.info(ma2)\n * // '/ip4/127.0.0.1'\n * ```\n */\nexport function fromTuples (tuples: Tuple[]): Multiaddr {\n return multiaddr(tuplesToBytes(tuples))\n}\n\n/**\n * Create a {@link Multiaddr} from an array of {@link StringTuple}s\n *\n * @example\n *\n * ```ts\n * import { fromStringTuples, multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1')\n * const tuples = ma.stringTuples()\n *\n * const ma2 = fromStringTuples(tuples)\n *\n * console.info(ma2)\n * // '/ip4/127.0.0.1'\n * ```\n */\nexport function fromStringTuples (tuples: StringTuple[]): Multiaddr {\n return fromTuples(stringTuplesToTuples(tuples))\n}\n\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName (addr: Multiaddr): boolean {\n if (!isMultiaddr(addr)) {\n return false\n }\n\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable)\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\nexport { getProtocol as protocols }\n", "import { dns, RecordType } from '@multiformats/dns'\nimport { multiaddr } from '../index.js'\nimport { getProtocol } from '../protocols-table.js'\nimport type { Resolver } from './index.js'\nimport type { AbortOptions, Multiaddr } from '../index.js'\nimport type { DNS } from '@multiformats/dns'\n\nconst MAX_RECURSIVE_DEPTH = 32\nconst { code: dnsaddrCode } = getProtocol('dnsaddr')\n\nclass RecursionLimitError extends Error {\n constructor (message = 'Max recursive depth reached') {\n super(message)\n this.name = 'RecursionLimitError'\n }\n}\n\nexport interface DNSADDROptions extends AbortOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n\n /**\n * When resolving DNSADDR Multiaddrs that resolve to other DNSADDR Multiaddrs,\n * limit how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport const dnsaddrResolver: Resolver<DNSADDROptions> = async function dnsaddrResolver (ma: Multiaddr, options: DNSADDROptions = {}): Promise<string[]> {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH\n\n if (recursionLimit === 0) {\n throw new RecursionLimitError('Max recursive depth reached')\n }\n\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? []\n\n const resolver = options?.dns ?? dns()\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n RecordType.TXT\n ]\n })\n\n const peerId = ma.getPeerId()\n const output: string[] = []\n\n for (const answer of result.Answer) {\n const addr = answer.data\n .replace(/[\"']/g, '')\n .trim()\n .split('=')[1]\n\n if (addr == null) {\n continue\n }\n\n if (peerId != null && !addr.includes(peerId)) {\n continue\n }\n\n const ma = multiaddr(addr)\n\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n })\n\n output.push(...resolved.map(ma => ma.toString()))\n } else {\n output.push(ma.toString())\n }\n }\n\n return output\n}\n", "/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n", "import { FaultTolerance, InvalidParametersError } from '@libp2p/interface'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport mergeOptions from 'merge-options'\nimport type { Libp2pInit } from './index.js'\nimport type { ServiceMap } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst DefaultConfig: Libp2pInit = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs: Multiaddr[]) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n },\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n }\n}\n\nexport async function validateConfig <T extends ServiceMap = Record<string, unknown>> (opts: Libp2pInit<T>): Promise<Libp2pInit<T>> {\n const resultingOptions: Libp2pInit<T> = mergeOptions(DefaultConfig, opts)\n\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new InvalidParametersError('Private network is enforced, but no protector was provided')\n }\n\n return resultingOptions\n}\n", "// Helpers.\nconst s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nfunction ms(value, options) {\n try {\n if (typeof value === 'string' && value.length > 0) {\n return parse(value);\n }\n else if (typeof value === 'number' && isFinite(value)) {\n return options?.long ? fmtLong(value) : fmtShort(value);\n }\n throw new Error('Value is not a string or number.');\n }\n catch (error) {\n const message = isError(error)\n ? `${error.message}. value=${JSON.stringify(value)}`\n : 'An unknown error has occured.';\n throw new Error(message);\n }\n}\n/**\n * Parse the given `str` and return milliseconds.\n */\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n throw new Error('Value exceeds the maximum length of 100 characters.');\n }\n const match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return NaN;\n }\n const n = parseFloat(match[1]);\n const type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n // This should never occur.\n throw new Error(`The unit ${type} was matched, but no matching case exists.`);\n }\n}\nexport default ms;\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n/**\n * Pluralization helper.\n */\nfunction plural(ms, msAbs, n, name) {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`;\n}\n/**\n * A type guard for errors.\n */\nfunction isError(error) {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n", "/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms'\nimport type { Debug, Debugger } from './index.js'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms'\nimport setup from './common.js'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.js'\nimport type ms from 'ms'\n\nexport interface Debug {\n (namespace: string): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(...args: any[]): any\n selectColor(namespace: string): string | number\n humanize: typeof ms\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(...args: any[]): any\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n return v == null ? 'undefined' : notEmpty(v.stack) ?? notEmpty(v.message) ?? v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\nexport interface ComponentLogger {\n forComponent(name: string): Logger\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial<PeerLoggerOptions> = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`)\n }\n\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\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", "// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n", "import fnv1aHash from '@sindresorhus/fnv1a'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport interface Hash {\n hash(input: Uint8Array, seed: number): number\n hashV(input: Uint8Array, seed: number): Uint8Array\n}\n\nexport const fnv1a: Hash = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }))\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed))\n }\n}\n\nexport function numberToBuffer (num: bigint | number): Uint8Array {\n let hex = num.toString(16)\n\n if (hex.length % 2 === 1) {\n hex = `0${hex}`\n }\n\n return uint8ArrayFromString(hex, 'base16')\n}\n", "import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { Hash } from './hashes'\n\nexport const MAX_FINGERPRINT_SIZE = 64\n\nexport class Fingerprint {\n private readonly fp: Uint8Array\n private readonly h: Hash\n private readonly seed: number\n\n constructor (buf: Uint8Array, hash: Hash, seed: number, fingerprintSize: number = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size')\n }\n\n const fnv = hash.hashV(buf, seed)\n const fp = uint8ArrayAlloc(fingerprintSize)\n\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i]\n }\n\n if (fp.length === 0) {\n fp[0] = 7\n }\n\n this.fp = fp\n this.h = hash\n this.seed = seed\n }\n\n hash (): number {\n return this.h.hash(this.fp, this.seed)\n }\n\n equals (other?: any): boolean {\n if (!(other?.fp instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.fp, other.fp)\n }\n}\n", "export function getRandomInt (min: number, max: number): number {\n return Math.floor(Math.random() * (max - min)) + min\n}\n", "import { Fingerprint } from './fingerprint.js'\nimport { getRandomInt } from './utils.js'\n\nexport class Bucket {\n private readonly contents: Array<Fingerprint | null>\n\n constructor (size: number) {\n this.contents = new Array(size).fill(null)\n }\n\n has (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n return this.contents.some((fp) => {\n return fingerprint.equals(fp)\n })\n }\n\n add (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint\n return true\n }\n }\n\n return true\n }\n\n swap (fingerprint: Fingerprint): Fingerprint | null {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const i = getRandomInt(0, this.contents.length - 1)\n const current = this.contents[i]\n this.contents[i] = fingerprint\n\n return current\n }\n\n remove (fingerprint: Fingerprint): boolean {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint')\n }\n\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp)\n })\n\n if (found > -1) {\n this.contents[found] = null\n return true\n } else {\n return false\n }\n }\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { Bucket } from './bucket.js'\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.js'\nimport { fnv1a, type Hash } from './hashes.js'\nimport { getRandomInt } from './utils.js'\nimport type { Filter } from './index.js'\n\nconst maxCuckooCount = 500\n\nexport interface CuckooFilterInit {\n /**\n * How many items the filter is expected to contain\n */\n filterSize: number\n\n /**\n * How many items to put in each bucket\n */\n bucketSize?: number\n\n /**\n * How many bytes the fingerprint is expected to be\n */\n fingerprintSize?: number\n\n /**\n * A non-cryptographic hash implementation\n */\n hash?: Hash\n\n /**\n * A number used to seed the hash\n */\n seed?: number\n}\n\nexport class CuckooFilter implements Filter {\n private readonly bucketSize: number\n private readonly filterSize: number\n private readonly fingerprintSize: number\n private readonly buckets: Bucket[]\n public count: number\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: CuckooFilterInit) {\n this.filterSize = init.filterSize\n this.bucketSize = init.bucketSize ?? 4\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.count = 0\n this.buckets = []\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++\n return true\n }\n\n const rand = [j, k]\n let i = rand[getRandomInt(0, rand.length - 1)]\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint)\n\n if (swapped == null) {\n continue\n }\n\n i = (i ^ swapped.hash()) % this.filterSize\n\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize)\n }\n\n if (this.buckets[i].add(swapped)) {\n this.count++\n\n return true\n } else {\n continue\n }\n }\n\n return false\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.has(fingerprint) ?? false\n\n if (inJ) {\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n\n return this.buckets[k]?.has(fingerprint) ?? false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize)\n const j = this.hash.hash(item, this.seed) % this.filterSize\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false\n\n if (inJ) {\n this.count--\n return inJ\n }\n\n const k = (j ^ fingerprint.hash()) % this.filterSize\n const inK = this.buckets[k]?.remove(fingerprint) ?? false\n\n if (inK) {\n this.count--\n }\n\n return inK\n }\n\n get reliable (): boolean {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90\n }\n}\n\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n}\n\nfunction calculateBucketSize (errorRate: number = 0.001): 2 | 4 | 8 {\n if (errorRate > 0.002) {\n return 2\n }\n\n if (errorRate > 0.00001) {\n return 4\n }\n\n return 8\n}\n\nexport function optimize (maxItems: number, errorRate: number = 0.001): CuckooFilterInit {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate)\n const load = MAX_LOAD[bucketSize]\n\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load)\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), MAX_FINGERPRINT_SIZE)\n\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n }\n}\n\nexport function createCuckooFilter (maxItems: number, errorRate: number = 0.005): Filter {\n const opts = optimize(maxItems, errorRate)\n return new CuckooFilter(opts)\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { CuckooFilter, optimize, type CuckooFilterInit } from './cuckoo-filter.js'\nimport { fnv1a, type Hash } from './hashes.js'\nimport { getRandomInt } from './utils.js'\nimport type { Filter } from './index.js'\n\nexport interface ScalableCuckooFilterInit extends CuckooFilterInit {\n /**\n * A number to multiply maxItems by when adding new sub-filters\n */\n scale?: number\n}\n\nexport class ScalableCuckooFilter implements Filter {\n private readonly filterSize: number\n private readonly bucketSize: number\n private readonly fingerprintSize: number\n private readonly scale: number\n private readonly filterSeries: CuckooFilter[]\n private readonly hash: Hash\n private readonly seed: number\n\n constructor (init: ScalableCuckooFilterInit) {\n this.bucketSize = init.bucketSize ?? 4\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize\n this.fingerprintSize = init.fingerprintSize ?? 2\n this.scale = init.scale ?? 2\n this.hash = init.hash ?? fnv1a\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10))\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ]\n }\n\n add (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n if (this.has(item)) {\n return true\n }\n\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable\n })\n\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length)\n\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n\n this.filterSeries.push(current)\n }\n\n return current.add(item)\n }\n\n has (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true\n }\n }\n\n return false\n }\n\n remove (item: Uint8Array | string): boolean {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item)\n }\n\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true\n }\n }\n\n return false\n }\n\n get count (): number {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count\n }, 0)\n }\n}\n\nexport function createScalableCuckooFilter (maxItems: number, errorRate: number = 0.001, options?: Pick<ScalableCuckooFilterInit, 'hash' | 'seed' | 'scale'>): Filter {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n })\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Envelope {\n publicKey: Uint8Array\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport namespace Envelope {\n let _codec: Codec<Envelope>\n\n export const codec = (): Codec<Envelope> => {\n if (_codec == null) {\n _codec = message<Envelope>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.publicKey)\n }\n\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.payloadType)\n }\n\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26)\n w.bytes(obj.payload)\n }\n\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42)\n w.bytes(obj.signature)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n publicKey: uint8ArrayAlloc(0),\n payloadType: uint8ArrayAlloc(0),\n payload: uint8ArrayAlloc(0),\n signature: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.publicKey = reader.bytes()\n break\n }\n case 2: {\n obj.payloadType = reader.bytes()\n break\n }\n case 3: {\n obj.payload = reader.bytes()\n break\n }\n case 5: {\n obj.signature = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Envelope>): Uint8Array => {\n return encodeMessage(obj, Envelope.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Envelope>): Envelope => {\n return decodeMessage(buf, Envelope.codec(), opts)\n }\n}\n", "/**\n * The key in the record is not valid for the domain\n */\nexport class InvalidSignatureError extends Error {\n constructor (message = 'Invalid signature') {\n super(message)\n this.name = 'InvalidSignatureError'\n }\n}\n", "import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string'\nimport { Envelope as Protobuf } from './envelope.js'\nimport { InvalidSignatureError } from './errors.js'\nimport type { Record, Envelope, PrivateKey, PublicKey } from '@libp2p/interface'\n\nexport interface RecordEnvelopeInit {\n publicKey: PublicKey\n payloadType: Uint8Array\n payload: Uint8Array\n signature: Uint8Array\n}\n\nexport class RecordEnvelope implements Envelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data: Uint8Array | Uint8ArrayList): Promise<RecordEnvelope> => {\n const envelopeData = Protobuf.decode(data)\n const publicKey = publicKeyFromProtobuf(envelopeData.publicKey)\n\n return new RecordEnvelope({\n publicKey,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n })\n }\n\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record: Record, privateKey: PrivateKey): Promise<RecordEnvelope> => {\n if (privateKey == null) {\n throw new Error('Missing private key')\n }\n\n const domain = record.domain\n const payloadType = record.codec\n const payload = record.marshal()\n const signData = formatSignaturePayload(domain, payloadType, payload)\n const signature = await privateKey.sign(signData.subarray())\n\n return new RecordEnvelope({\n publicKey: privateKey.publicKey,\n payloadType,\n payload,\n signature\n })\n }\n\n /**\n * Open and certify a given marshaled envelope.\n * Data is unmarshaled and the signature validated for the given domain.\n */\n static openAndCertify = async (data: Uint8Array | Uint8ArrayList, domain: string): Promise<RecordEnvelope> => {\n const envelope = await RecordEnvelope.createFromProtobuf(data)\n const valid = await envelope.validate(domain)\n\n if (!valid) {\n throw new InvalidSignatureError('Envelope signature is not valid for the given domain')\n }\n\n return envelope\n }\n\n public publicKey: PublicKey\n public payloadType: Uint8Array\n public payload: Uint8Array\n public signature: Uint8Array\n public marshaled?: Uint8Array\n\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor (init: RecordEnvelopeInit) {\n const { publicKey, payloadType, payload, signature } = init\n\n this.publicKey = publicKey\n this.payloadType = payloadType\n this.payload = payload\n this.signature = signature\n }\n\n /**\n * Marshal the envelope content\n */\n marshal (): Uint8Array {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: publicKeyToProtobuf(this.publicKey),\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals (other?: Envelope): boolean {\n if (other == null) {\n return false\n }\n\n return uint8ArrayEquals(this.marshal(), other.marshal())\n }\n\n /**\n * Validate envelope data signature for the given domain\n */\n async validate (domain: string): Promise<boolean> {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload)\n\n return this.publicKey.verify(signData.subarray(), this.signature)\n }\n}\n\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain: string, payloadType: Uint8Array, payload: Uint8Array | Uint8ArrayList): Uint8ArrayList => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n\n const domainUint8Array = uint8arraysFromString(domain)\n const domainLength = varint.encode(domainUint8Array.byteLength)\n const payloadTypeLength = varint.encode(payloadType.length)\n const payloadLength = varint.encode(payload.length)\n\n return new Uint8ArrayList(\n domainLength,\n domainUint8Array,\n payloadTypeLength,\n payloadType,\n payloadLength,\n payload\n )\n}\n", "/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals (a: any[], b: any[]): boolean {\n const sort = (a: any, b: any): number => a.toString().localeCompare(b.toString())\n\n if (a.length !== b.length) {\n return false\n }\n\n b.sort(sort)\n\n return a.sort(sort).every((item, index) => b[index].equals(item))\n}\n", "// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'\n\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1])\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, MaxLengthError, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecord {\n peerId: Uint8Array\n seq: bigint\n addresses: PeerRecord.AddressInfo[]\n}\n\nexport namespace PeerRecord {\n export interface AddressInfo {\n multiaddr: Uint8Array\n }\n\n export namespace AddressInfo {\n let _codec: Codec<AddressInfo>\n\n export const codec = (): Codec<AddressInfo> => {\n if (_codec == null) {\n _codec = message<AddressInfo>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n multiaddr: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.multiaddr = 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<AddressInfo>): Uint8Array => {\n return encodeMessage(obj, AddressInfo.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<AddressInfo>): AddressInfo => {\n return decodeMessage(buf, AddressInfo.codec(), opts)\n }\n }\n\n let _codec: Codec<PeerRecord>\n\n export const codec = (): Codec<PeerRecord> => {\n if (_codec == null) {\n _codec = message<PeerRecord>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.peerId)\n }\n\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16)\n w.uint64(obj.seq)\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26)\n PeerRecord.AddressInfo.codec().encode(value, w)\n }\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n peerId: uint8ArrayAlloc(0),\n seq: 0n,\n addresses: []\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.peerId = reader.bytes()\n break\n }\n case 2: {\n obj.seq = reader.uint64()\n break\n }\n case 3: {\n if (opts.limits?.addresses != null && obj.addresses.length === opts.limits.addresses) {\n throw new MaxLengthError('Decode error - map field \"addresses\" had too many elements')\n }\n\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.addresses$\n }))\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PeerRecord>): Uint8Array => {\n return encodeMessage(obj, PeerRecord.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PeerRecord>): PeerRecord => {\n return decodeMessage(buf, PeerRecord.codec(), opts)\n }\n}\n", "import { peerIdFromMultihash } from '@libp2p/peer-id'\nimport { arrayEquals } from '@libp2p/utils/array-equals'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport * as Digest from 'multiformats/hashes/digest'\nimport {\n ENVELOPE_DOMAIN_PEER_RECORD,\n ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n} from './consts.js'\nimport { PeerRecord as Protobuf } from './peer-record.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface PeerRecordInit {\n peerId: PeerId\n\n /**\n * Addresses of the associated peer.\n */\n multiaddrs?: Multiaddr[]\n\n /**\n * Monotonically-increasing sequence counter that's used to order PeerRecords in time.\n */\n seqNumber?: bigint\n}\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf: Uint8Array | Uint8ArrayList): PeerRecord => {\n const peerRecord = Protobuf.decode(buf)\n const peerId = peerIdFromMultihash(Digest.decode(peerRecord.peerId))\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => multiaddr(a.multiaddr))\n const seqNumber = peerRecord.seq\n\n return new PeerRecord({ peerId, multiaddrs, seqNumber })\n }\n\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD\n\n public peerId: PeerId\n public multiaddrs: Multiaddr[]\n public seqNumber: bigint\n public domain = PeerRecord.DOMAIN\n public codec = PeerRecord.CODEC\n private marshaled?: Uint8Array\n\n constructor (init: PeerRecordInit) {\n const { peerId, multiaddrs, seqNumber } = init\n\n this.peerId = peerId\n this.multiaddrs = multiaddrs ?? []\n this.seqNumber = seqNumber ?? BigInt(Date.now())\n }\n\n /**\n * Marshal a record to be used in an envelope\n */\n marshal (): Uint8Array {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toMultihash().bytes,\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n })\n }\n\n return this.marshaled\n }\n\n /**\n * Returns true if `this` record equals the `other`\n */\n equals (other: unknown): boolean {\n if (!(other instanceof PeerRecord)) {\n return false\n }\n\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false\n }\n\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false\n }\n\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false\n }\n\n return true\n }\n}\n", "/**\n * @packageDocumentation\n *\n * For when you need a one-liner to collect iterable values.\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n *\n * // This can also be an iterator, etc\n * const values = function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = all(values)\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(values())\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Collects all values from an (async) iterable and returns them as an array\n */\nfunction all <T> (source: Iterable<T>): T[]\nfunction all <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T[]>\nfunction all <T> (source: Iterable<T> | AsyncIterable<T>): Promise<T[]> | T[] {\n if (isAsyncIterable(source)) {\n return (async () => {\n const arr = []\n\n for await (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n })()\n }\n\n const arr = []\n\n for (const entry of source) {\n arr.push(entry)\n }\n\n return arr\n}\n\nexport default all\n", "export interface WebworkerEventListener <T = any> {\n (worker: Worker, event: MessageEvent<T>): void\n}\n\nconst events: Record<string, WebworkerEventListener[]> = {}\n\nconst observable = (worker: Worker & { port?: any }) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event)\n })\n\n if (worker.port != null) {\n worker.port.addEventListener('message', (event: any) => {\n observable.dispatchEvent('message', worker, event)\n })\n }\n}\n\nobservable.addEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n events[type] = []\n }\n\n events[type].push(fn)\n}\n\nobservable.removeEventListener = (type: string, fn: WebworkerEventListener) => {\n if (events[type] == null) {\n return\n }\n\n events[type] = events[type]\n .filter(listener => listener === fn)\n}\n\nobservable.dispatchEvent = function (type: string, worker: Worker, event: MessageEvent<any>) {\n if (events[type] == null) {\n return\n }\n\n events[type].forEach(fn => fn(worker, event))\n}\n\nexport default observable\n", "export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read'\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read'\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read'\n\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write'\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write'\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write'\n", "export const nanoid = (size: number = 21): string => {\n return Math.random().toString().substring(2)\n}\n", "import observer from 'observable-webworkers'\nimport {\n WORKER_REQUEST_READ_LOCK,\n WORKER_RELEASE_READ_LOCK,\n MASTER_GRANT_READ_LOCK,\n WORKER_REQUEST_WRITE_LOCK,\n WORKER_RELEASE_WRITE_LOCK,\n MASTER_GRANT_WRITE_LOCK\n} from './constants.js'\nimport { nanoid } from './utils.js'\nimport type { MorticeImplementation, MorticeOptions, Release } from './index.js'\n\nconst handleWorkerLockRequest = (emitter: EventTarget, masterEvent: string, requestType: string, releaseType: string, grantType: string) => {\n return (worker: Worker, event: MessageEvent) => {\n if (event.data.type !== requestType) {\n return\n }\n\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async (): Promise<void> => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n })\n\n // wait for worker to finish\n await new Promise<void>((resolve) => {\n const releaseEventListener = (event: MessageEvent): void => {\n if (event?.data == null) {\n return\n }\n\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n }\n\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener)\n resolve()\n }\n }\n\n worker.addEventListener('message', releaseEventListener)\n })\n }\n }\n }))\n }\n}\n\nconst makeWorkerLockRequest = (name: string, requestType: string, grantType: string, releaseType: string) => {\n return async () => {\n const id = nanoid()\n\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n })\n\n return new Promise<Release>((resolve) => {\n const listener = (event: MessageEvent): void => {\n if (event?.data == null) {\n return\n }\n\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n }\n\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener)\n\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n })\n })\n }\n }\n\n globalThis.addEventListener('message', listener)\n })\n }\n}\n\nconst defaultOptions = {\n singleProcess: false\n}\n\nexport default (options: Required<MorticeOptions>): MorticeImplementation | EventTarget => {\n options = Object.assign({}, defaultOptions, options)\n const isPrimary = Boolean(globalThis.document) || options.singleProcess\n\n if (isPrimary) {\n const emitter = new EventTarget()\n\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK))\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK))\n\n return emitter\n }\n\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * <small pause>\n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\n\nimport PQueue from 'p-queue'\nimport pTimeout from 'p-timeout'\nimport impl from './node.js'\n\nexport interface MorticeOptions {\n name?: string\n timeout?: number\n concurrency?: number\n singleProcess?: boolean\n}\n\nexport interface Mortice {\n readLock(): Promise<Release>\n writeLock(): Promise<Release>\n}\n\nexport interface Release {\n (): void\n}\n\nexport interface MorticeImplementation {\n isWorker: boolean\n readLock(name: string, options: MorticeOptions): Mortice['readLock']\n writeLock(name: string, options: MorticeOptions): Mortice['writeLock']\n}\n\nconst mutexes: Record<string, Mortice> = {}\nlet implementation: any\n\nasync function createReleaseable (queue: PQueue, options: Required<MorticeOptions>): Promise<Release> {\n let res: (release: Release) => void\n\n const p = new Promise<Release>((resolve) => {\n res = resolve\n })\n\n void queue.add(async () => pTimeout((async () => {\n await new Promise<void>((resolve) => {\n res(() => {\n resolve()\n })\n })\n })(), {\n milliseconds: options.timeout\n }))\n\n return p\n}\n\nconst createMutex = (name: string, options: Required<MorticeOptions>): Mortice => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n }\n }\n\n const masterQueue = new PQueue({ concurrency: 1 })\n let readQueue: PQueue | null\n\n return {\n async readLock () {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options)\n }\n\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n })\n const localReadQueue = readQueue\n\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options)\n\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start()\n\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null\n }\n })\n })\n\n return readPromise\n },\n async writeLock () {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null\n\n return createReleaseable(masterQueue, options)\n }\n }\n}\n\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n}\n\ninterface EventData {\n name: string\n handler(): Promise<void>\n}\n\nexport default function createMortice (options?: MorticeOptions): Mortice {\n const opts: Required<MorticeOptions> = Object.assign({}, defaultOptions, options)\n\n if (implementation == null) {\n implementation = impl(opts)\n\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event: MessageEvent<EventData>) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].readLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n\n implementation.addEventListener('requestWriteLock', async (event: MessageEvent<EventData>) => {\n if (mutexes[event.data.name] == null) {\n return\n }\n\n void mutexes[event.data.name].writeLock()\n .then(async release => event.data.handler().finally(() => { release() }))\n })\n }\n }\n\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts)\n }\n\n return mutexes[opts.name]\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, MaxLengthError, MaxSizeError, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Peer {\n addresses: Address[]\n protocols: string[]\n publicKey?: Uint8Array\n peerRecordEnvelope?: Uint8Array\n metadata: Map<string, Uint8Array>\n tags: Map<string, Tag>\n updated?: number\n}\n\nexport namespace Peer {\n export interface Peer$metadataEntry {\n key: string\n value: Uint8Array\n }\n\n export namespace Peer$metadataEntry {\n let _codec: Codec<Peer$metadataEntry>\n\n export const codec = (): Codec<Peer$metadataEntry> => {\n if (_codec == null) {\n _codec = message<Peer$metadataEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10)\n w.string(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n key: '',\n value: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.string()\n break\n }\n case 2: {\n obj.value = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Peer$metadataEntry>): Uint8Array => {\n return encodeMessage(obj, Peer$metadataEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Peer$metadataEntry>): Peer$metadataEntry => {\n return decodeMessage(buf, Peer$metadataEntry.codec(), opts)\n }\n }\n\n export interface Peer$tagsEntry {\n key: string\n value?: Tag\n }\n\n export namespace Peer$tagsEntry {\n let _codec: Codec<Peer$tagsEntry>\n\n export const codec = (): Codec<Peer$tagsEntry> => {\n if (_codec == null) {\n _codec = message<Peer$tagsEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10)\n w.string(obj.key)\n }\n\n if (obj.value != null) {\n w.uint32(18)\n Tag.codec().encode(obj.value, w)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n key: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.string()\n break\n }\n case 2: {\n obj.value = Tag.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.value\n })\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Peer$tagsEntry>): Uint8Array => {\n return encodeMessage(obj, Peer$tagsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Peer$tagsEntry>): Peer$tagsEntry => {\n return decodeMessage(buf, Peer$tagsEntry.codec(), opts)\n }\n }\n\n let _codec: Codec<Peer>\n\n export const codec = (): Codec<Peer> => {\n if (_codec == null) {\n _codec = message<Peer>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10)\n Address.codec().encode(value, w)\n }\n }\n\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(18)\n w.string(value)\n }\n }\n\n if (obj.publicKey != null) {\n w.uint32(34)\n w.bytes(obj.publicKey)\n }\n\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42)\n w.bytes(obj.peerRecordEnvelope)\n }\n\n if (obj.metadata != null && obj.metadata.size !== 0) {\n for (const [key, value] of obj.metadata.entries()) {\n w.uint32(50)\n Peer.Peer$metadataEntry.codec().encode({ key, value }, w)\n }\n }\n\n if (obj.tags != null && obj.tags.size !== 0) {\n for (const [key, value] of obj.tags.entries()) {\n w.uint32(58)\n Peer.Peer$tagsEntry.codec().encode({ key, value }, w)\n }\n }\n\n if (obj.updated != null) {\n w.uint32(64)\n w.uint64Number(obj.updated)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n addresses: [],\n protocols: [],\n metadata: new Map<string, Uint8Array>(),\n tags: new Map<string, undefined>()\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.addresses != null && obj.addresses.length === opts.limits.addresses) {\n throw new MaxLengthError('Decode error - map field \"addresses\" had too many elements')\n }\n\n obj.addresses.push(Address.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.addresses$\n }))\n break\n }\n case 2: {\n if (opts.limits?.protocols != null && obj.protocols.length === opts.limits.protocols) {\n throw new MaxLengthError('Decode error - map field \"protocols\" had too many elements')\n }\n\n obj.protocols.push(reader.string())\n break\n }\n case 4: {\n obj.publicKey = reader.bytes()\n break\n }\n case 5: {\n obj.peerRecordEnvelope = reader.bytes()\n break\n }\n case 6: {\n if (opts.limits?.metadata != null && obj.metadata.size === opts.limits.metadata) {\n throw new MaxSizeError('Decode error - map field \"metadata\" had too many elements')\n }\n\n const entry = Peer.Peer$metadataEntry.codec().decode(reader, reader.uint32())\n obj.metadata.set(entry.key, entry.value)\n break\n }\n case 7: {\n if (opts.limits?.tags != null && obj.tags.size === opts.limits.tags) {\n throw new MaxSizeError('Decode error - map field \"tags\" had too many elements')\n }\n\n const entry = Peer.Peer$tagsEntry.codec().decode(reader, reader.uint32(), {\n limits: {\n value: opts.limits?.tags$value\n }\n })\n obj.tags.set(entry.key, entry.value)\n break\n }\n case 8: {\n obj.updated = reader.uint64Number()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Peer>): Uint8Array => {\n return encodeMessage(obj, Peer.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Peer>): Peer => {\n return decodeMessage(buf, Peer.codec(), opts)\n }\n}\n\nexport interface Address {\n multiaddr: Uint8Array\n isCertified?: boolean\n observed?: number\n}\n\nexport namespace Address {\n let _codec: Codec<Address>\n\n export const codec = (): Codec<Address> => {\n if (_codec == null) {\n _codec = message<Address>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.multiaddr)\n }\n\n if (obj.isCertified != null) {\n w.uint32(16)\n w.bool(obj.isCertified)\n }\n\n if (obj.observed != null) {\n w.uint32(24)\n w.uint64Number(obj.observed)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n multiaddr: uint8ArrayAlloc(0)\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.multiaddr = reader.bytes()\n break\n }\n case 2: {\n obj.isCertified = reader.bool()\n break\n }\n case 3: {\n obj.observed = reader.uint64Number()\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<Address>): Uint8Array => {\n return encodeMessage(obj, Address.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Address>): Address => {\n return decodeMessage(buf, Address.codec(), opts)\n }\n}\n\nexport interface Tag {\n value: number\n expiry?: bigint\n}\n\nexport namespace Tag {\n let _codec: Codec<Tag>\n\n export const codec = (): Codec<Tag> => {\n if (_codec == null) {\n _codec = message<Tag>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.value != null && obj.value !== 0)) {\n w.uint32(8)\n w.uint32(obj.value)\n }\n\n if (obj.expiry != null) {\n w.uint32(16)\n w.uint64(obj.expiry)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n value: 0\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.value = reader.uint32()\n break\n }\n case 2: {\n obj.expiry = reader.uint64()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Tag>): Uint8Array => {\n return encodeMessage(obj, Tag.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Tag>): Tag => {\n return decodeMessage(buf, Tag.codec(), opts)\n }\n}\n", "import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'\nimport { peerIdFromPublicKey } from '@libp2p/peer-id'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { base58btc } from 'multiformats/bases/base58'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { Peer as PeerPB } from '../pb/peer.js'\nimport type { PeerId, Peer, Tag } from '@libp2p/interface'\n\nfunction populatePublicKey (peerId: PeerId, protobuf: PeerPB): PeerId {\n if (peerId.publicKey != null || protobuf.publicKey == null) {\n return peerId\n }\n\n let digest: any\n\n if (peerId.type === 'RSA') {\n // avoid hashing public key\n const multihash = base58btc.decode(`z${peerId}`)\n digest = Digest.decode(multihash)\n }\n\n const publicKey = publicKeyFromProtobuf(protobuf.publicKey, digest)\n return peerIdFromPublicKey(publicKey)\n}\n\nexport function bytesToPeer (peerId: PeerId, buf: Uint8Array, maxAddressAge: number): Peer {\n const peer = PeerPB.decode(buf)\n\n return pbToPeer(peerId, peer, maxAddressAge)\n}\n\nexport function pbToPeer (peerId: PeerId, peer: PeerPB, maxAddressAge: number): Peer {\n const tags = new Map<string, Tag>()\n\n // remove any expired tags\n const now = BigInt(Date.now())\n\n for (const [key, tag] of peer.tags.entries()) {\n if (tag.expiry != null && tag.expiry < now) {\n continue\n }\n\n tags.set(key, tag)\n }\n\n return {\n ...peer,\n id: populatePublicKey(peerId, peer),\n addresses: peer.addresses\n // remove any expired multiaddrs\n .filter(({ observed }) => observed != null && observed > (Date.now() - maxAddressAge))\n .map(({ multiaddr: ma, isCertified }) => {\n return {\n multiaddr: multiaddr(ma),\n isCertified: isCertified ?? false\n }\n }),\n metadata: peer.metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined,\n tags\n }\n}\n", "import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport type { Peer, Address, Tag } from '../pb/peer.js'\n\nexport function peerEquals (peerA: Peer, peerB: Peer): boolean {\n return addressesEqual(peerA.addresses, peerB.addresses) &&\n protocolsEqual(peerA.protocols, peerB.protocols) &&\n publicKeyEqual(peerA.publicKey, peerB.publicKey) &&\n peerRecordEnvelope(peerA.peerRecordEnvelope, peerB.peerRecordEnvelope) &&\n metadataEqual(peerA.metadata, peerB.metadata) &&\n tagsEqual(peerA.tags, peerB.tags)\n}\n\nfunction addressesEqual (addressesA: Address[], addressesB: Address[]): boolean {\n return compareArrays(addressesA, addressesB, (a, b) => {\n if (a.isCertified !== b.isCertified) {\n return false\n }\n\n if (!uint8ArrayEquals(a.multiaddr, b.multiaddr)) {\n return false\n }\n\n return true\n })\n}\n\nfunction protocolsEqual (protocolsA: string[], protocolsB: string[]): boolean {\n return compareArrays(protocolsA, protocolsB, (a, b) => a === b)\n}\n\nfunction publicKeyEqual (publicKeyA?: Uint8Array, publicKeyB?: Uint8Array): boolean {\n return compareOptionalUint8Arrays(publicKeyA, publicKeyB)\n}\n\nfunction peerRecordEnvelope (envelopeA?: Uint8Array, envelopeB?: Uint8Array): boolean {\n return compareOptionalUint8Arrays(envelopeA, envelopeB)\n}\n\nfunction metadataEqual (metadataA: Map<string, Uint8Array>, metadataB: Map<string, Uint8Array>): boolean {\n return compareMaps(metadataA, metadataB, (a, b) => uint8ArrayEquals(a, b))\n}\n\nfunction tagsEqual (metadataA: Map<string, Tag>, metadataB: Map<string, Tag>): boolean {\n return compareMaps(metadataA, metadataB, (a, b) => a.value === b.value && a.expiry === b.expiry)\n}\n\nfunction compareOptionalUint8Arrays (arrA?: Uint8Array, arrB?: Uint8Array): boolean {\n if (arrA == null && arrB == null) {\n return true\n }\n\n if (arrA != null && arrB != null) {\n return uint8ArrayEquals(arrA, arrB)\n }\n\n return false\n}\n\nfunction compareArrays <T> (arrA: T[], arrB: T[], compare: (a: T, b: T) => boolean): boolean {\n if (arrA.length !== arrB.length) {\n return false\n }\n\n for (let i = 0; i < arrA.length; i++) {\n if (!compare(arrA[i], arrB[i])) {\n return false\n }\n }\n\n return true\n}\n\nfunction compareMaps <K, V> (mapA: Map<K, V>, mapB: Map<K, V>, compare: (a: V, b: V) => boolean): boolean {\n if (mapA.size !== mapB.size) {\n return false\n }\n\n for (const [key, value] of mapA.entries()) {\n const valueB = mapB.get(key)\n\n if (valueB == null) {\n return false\n }\n\n if (!compare(value, valueB)) {\n return false\n }\n }\n\n return true\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array<string>} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random (): Key {\n return new Key(Math.random().toString().substring(2))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array<string>}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array<string>}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array<Key>} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array<any>} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { isPeerId, type PeerId } from '@libp2p/interface'\nimport { Key } from 'interface-datastore/key'\n\nexport const NAMESPACE_COMMON = '/peers/'\n\nexport function peerIdToDatastoreKey (peerId: PeerId): Key {\n if (!isPeerId(peerId) || peerId.type == null) {\n throw new InvalidParametersError('Invalid PeerId')\n }\n\n const b32key = peerId.toCID().toString()\n return new Key(`${NAMESPACE_COMMON}${b32key}`)\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\nimport type { AddressFilter } from '../index.js'\nimport type { Address as AddressPB } from '../pb/peer.js'\nimport type { PeerId, Address } from '@libp2p/interface'\n\nexport async function dedupeFilterAndSortAddresses (peerId: PeerId, filter: AddressFilter, addresses: Array<Address | AddressPB | undefined>, existingAddresses?: AddressPB[]): Promise<AddressPB[]> {\n const addressMap = new Map<string, Address>()\n\n for (const addr of addresses) {\n if (addr == null) {\n continue\n }\n\n if (addr.multiaddr instanceof Uint8Array) {\n addr.multiaddr = multiaddr(addr.multiaddr)\n }\n\n if (!isMultiaddr(addr.multiaddr)) {\n throw new InvalidParametersError('Multiaddr was invalid')\n }\n\n if (!(await filter(peerId, addr.multiaddr))) {\n continue\n }\n\n const isCertified = addr.isCertified ?? false\n const maStr = addr.multiaddr.toString()\n const existingAddr = addressMap.get(maStr)\n\n if (existingAddr != null) {\n addr.isCertified = existingAddr.isCertified || isCertified\n } else {\n addressMap.set(maStr, {\n multiaddr: addr.multiaddr,\n isCertified\n })\n }\n }\n\n return [...addressMap.values()]\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString())\n })\n .map(({ isCertified, multiaddr: ma }) => {\n // strip the trailing peerId if it is present\n const addrPeer = ma.getPeerId()\n\n if (peerId.equals(addrPeer)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${peerId}`))\n }\n\n return {\n isCertified,\n multiaddr: ma.bytes\n }\n })\n}\n", "/* eslint-disable complexity */\nimport { publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { InvalidParametersError } from '@libp2p/interface'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { dedupeFilterAndSortAddresses } from './dedupe-addresses.js'\nimport type { AddressFilter } from '../index.js'\nimport type { Tag, Peer as PeerPB } from '../pb/peer.js'\nimport type { ExistingPeer } from '../store.js'\nimport type { PeerId, Address, PeerData, TagOptions } from '@libp2p/interface'\n\nexport interface ToPBPeerOptions {\n addressFilter?: AddressFilter\n existingPeer?: ExistingPeer\n}\n\nexport async function toPeerPB (peerId: PeerId, data: Partial<PeerData>, strategy: 'merge' | 'patch', options: ToPBPeerOptions): Promise<PeerPB> {\n if (data == null) {\n throw new InvalidParametersError('Invalid PeerData')\n }\n\n if (data.publicKey != null && peerId.publicKey != null && !data.publicKey.equals(peerId.publicKey)) {\n throw new InvalidParametersError('publicKey bytes do not match peer id publicKey bytes')\n }\n\n const existingPeer = options.existingPeer?.peer\n\n if (existingPeer != null && !peerId.equals(existingPeer.id)) {\n throw new InvalidParametersError('peer id did not match existing peer id')\n }\n\n let addresses: Address[] = existingPeer?.addresses ?? []\n let protocols = new Set<string>(existingPeer?.protocols ?? [])\n let metadata: Map<string, Uint8Array> = existingPeer?.metadata ?? new Map()\n let tags: Map<string, Tag> = existingPeer?.tags ?? new Map()\n let peerRecordEnvelope: Uint8Array | undefined = existingPeer?.peerRecordEnvelope\n\n // when patching, we replace the original fields with passed values\n if (strategy === 'patch') {\n if (data.multiaddrs != null || data.addresses != null) {\n addresses = []\n\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })))\n }\n\n if (data.addresses != null) {\n addresses.push(...data.addresses)\n }\n }\n\n if (data.protocols != null) {\n protocols = new Set(data.protocols)\n }\n\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata)\n\n metadata = createSortedMap(metadataEntries, {\n validate: validateMetadata\n })\n }\n\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags)\n\n tags = createSortedMap(tagsEntries, {\n validate: validateTag,\n map: mapTag\n })\n }\n\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope\n }\n }\n\n // when merging, we join the original fields with passed values\n if (strategy === 'merge') {\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })))\n }\n\n if (data.addresses != null) {\n addresses.push(...data.addresses)\n }\n\n if (data.protocols != null) {\n protocols = new Set([...protocols, ...data.protocols])\n }\n\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata)\n\n for (const [key, value] of metadataEntries) {\n if (value == null) {\n metadata.delete(key)\n } else {\n metadata.set(key, value)\n }\n }\n\n metadata = createSortedMap([...metadata.entries()], {\n validate: validateMetadata\n })\n }\n\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags)\n const mergedTags = new Map<string, Tag | TagOptions>(tags)\n\n for (const [key, value] of tagsEntries) {\n if (value == null) {\n mergedTags.delete(key)\n } else {\n mergedTags.set(key, value)\n }\n }\n\n tags = createSortedMap([...mergedTags.entries()], {\n validate: validateTag,\n map: mapTag\n })\n }\n\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope\n }\n }\n\n let publicKey: Uint8Array | undefined\n\n if (existingPeer?.id.publicKey != null) {\n publicKey = publicKeyToProtobuf(existingPeer.id.publicKey)\n } else if (data.publicKey != null) {\n publicKey = publicKeyToProtobuf(data.publicKey)\n } else if (peerId.publicKey != null) {\n publicKey = publicKeyToProtobuf(peerId.publicKey)\n }\n\n const output: PeerPB = {\n addresses: await dedupeFilterAndSortAddresses(\n peerId,\n options.addressFilter ?? (async () => true),\n addresses,\n options.existingPeer?.peerPB.addresses\n ),\n protocols: [...protocols.values()].sort((a, b) => {\n return a.localeCompare(b)\n }),\n metadata,\n tags,\n publicKey,\n peerRecordEnvelope\n }\n\n // add observed addresses to multiaddrs\n output.addresses.forEach(addr => {\n addr.observed = options.existingPeer?.peerPB.addresses?.find(addr => uint8ArrayEquals(addr.multiaddr, addr.multiaddr))?.observed ?? Date.now()\n })\n\n // Ed25519 and secp256k1 have their public key embedded in them so no need to duplicate it\n if (peerId.type !== 'RSA') {\n delete output.publicKey\n }\n\n return output\n}\n\ninterface CreateSortedMapOptions <V, R = V> {\n validate(key: string, value: V): void\n map?(key: string, value: V): R\n}\n\n/**\n * In JS maps are ordered by insertion order so create a new map with the\n * keys inserted in alphabetical order.\n */\nfunction createSortedMap <V, R = V> (entries: Array<[string, V | undefined]>, options: CreateSortedMapOptions<V, R>): Map<string, R> {\n const output = new Map()\n\n for (const [key, value] of entries) {\n if (value == null) {\n continue\n }\n\n options.validate(key, value)\n }\n\n for (const [key, value] of entries.sort(([a], [b]) => {\n return a.localeCompare(b)\n })) {\n if (value != null) {\n output.set(key, options.map?.(key, value) ?? value)\n }\n }\n\n return output\n}\n\nfunction validateMetadata (key: string, value: Uint8Array): void {\n if (typeof key !== 'string') {\n throw new InvalidParametersError('Metadata key must be a string')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new InvalidParametersError('Metadata value must be a Uint8Array')\n }\n}\n\nfunction validateTag (key: string, tag: TagOptions): void {\n if (typeof key !== 'string') {\n throw new InvalidParametersError('Tag name must be a string')\n }\n\n if (tag.value != null) {\n if (parseInt(`${tag.value}`, 10) !== tag.value) {\n throw new InvalidParametersError('Tag value must be an integer')\n }\n\n if (tag.value < 0 || tag.value > 100) {\n throw new InvalidParametersError('Tag value must be between 0-100')\n }\n }\n\n if (tag.ttl != null) {\n if (parseInt(`${tag.ttl}`, 10) !== tag.ttl) {\n throw new InvalidParametersError('Tag ttl must be an integer')\n }\n\n if (tag.ttl < 0) {\n throw new InvalidParametersError('Tag ttl must be between greater than 0')\n }\n }\n}\n\nfunction mapTag (key: string, tag: any): Tag {\n let expiry: bigint | undefined\n\n if (tag.expiry != null) {\n expiry = tag.expiry\n }\n\n if (tag.ttl != null) {\n expiry = BigInt(Date.now() + Number(tag.ttl))\n }\n\n return {\n value: tag.value ?? 0,\n expiry\n }\n}\n", "import { NotFoundError } from '@libp2p/interface'\nimport { peerIdFromCID } from '@libp2p/peer-id'\nimport mortice, { type Mortice } from 'mortice'\nimport { base32 } from 'multiformats/bases/base32'\nimport { CID } from 'multiformats/cid'\nimport { MAX_ADDRESS_AGE, MAX_PEER_AGE } from './constants.js'\nimport { Peer as PeerPB } from './pb/peer.js'\nimport { bytesToPeer, pbToPeer } from './utils/bytes-to-peer.js'\nimport { peerEquals } from './utils/peer-equals.js'\nimport { NAMESPACE_COMMON, peerIdToDatastoreKey } from './utils/peer-id-to-datastore-key.js'\nimport { toPeerPB } from './utils/to-peer-pb.js'\nimport type { AddressFilter, PersistentPeerStoreComponents, PersistentPeerStoreInit } from './index.js'\nimport type { PeerUpdate as PeerUpdateExternal, PeerId, Peer, PeerData, PeerQuery, Logger } from '@libp2p/interface'\nimport type { Datastore, Key, Query } from 'interface-datastore'\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate extends PeerUpdateExternal {\n updated: boolean\n}\n\nexport interface ExistingPeer {\n peerPB: PeerPB\n peer: Peer\n}\n\nfunction keyToPeerId (key: Key): PeerId {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2]\n const buf = CID.parse(base32Str, base32)\n\n return peerIdFromCID(buf)\n}\n\nfunction decodePeer (key: Key, value: Uint8Array, maxAddressAge: number): Peer {\n const peerId = keyToPeerId(key)\n\n return bytesToPeer(peerId, value, maxAddressAge)\n}\n\nfunction mapQuery (query: PeerQuery, maxAddressAge: number): Query {\n return {\n prefix: NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value, maxAddressAge))\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value, maxAddressAge), decodePeer(b.key, b.value, maxAddressAge))\n })\n }\n}\n\nexport class PersistentStore {\n private readonly peerId: PeerId\n private readonly datastore: Datastore\n public readonly lock: Mortice\n private readonly addressFilter?: AddressFilter\n private readonly log: Logger\n private readonly maxAddressAge: number\n private readonly maxPeerAge: number\n\n constructor (components: PersistentPeerStoreComponents, init: PersistentPeerStoreInit = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store')\n this.peerId = components.peerId\n this.datastore = components.datastore\n this.addressFilter = init.addressFilter\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n })\n this.maxAddressAge = init.maxAddressAge ?? MAX_ADDRESS_AGE\n this.maxPeerAge = init.maxPeerAge ?? MAX_PEER_AGE\n }\n\n async has (peerId: PeerId): Promise<boolean> {\n try {\n await this.load(peerId)\n\n return true\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n return false\n }\n\n async delete (peerId: PeerId): Promise<void> {\n if (this.peerId.equals(peerId)) {\n return\n }\n\n await this.datastore.delete(peerIdToDatastoreKey(peerId))\n }\n\n async load (peerId: PeerId): Promise<Peer> {\n const key = peerIdToDatastoreKey(peerId)\n const buf = await this.datastore.get(key)\n const peer = PeerPB.decode(buf)\n\n if (this.#peerIsExpired(peerId, peer)) {\n await this.datastore.delete(key)\n throw new NotFoundError()\n }\n\n return pbToPeer(peerId, peer, this.peerId.equals(peerId) ? Infinity : this.maxAddressAge)\n }\n\n async save (peerId: PeerId, data: PeerData): Promise<PeerUpdate> {\n const existingPeer = await this.#findExistingPeer(peerId)\n\n const peerPb: PeerPB = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n })\n\n return this.#saveIfDifferent(peerId, peerPb, existingPeer)\n }\n\n async patch (peerId: PeerId, data: Partial<PeerData>): Promise<PeerUpdate> {\n const existingPeer = await this.#findExistingPeer(peerId)\n\n const peerPb: PeerPB = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n })\n\n return this.#saveIfDifferent(peerId, peerPb, existingPeer)\n }\n\n async merge (peerId: PeerId, data: PeerData): Promise<PeerUpdate> {\n const existingPeer = await this.#findExistingPeer(peerId)\n\n const peerPb: PeerPB = await toPeerPB(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n })\n\n return this.#saveIfDifferent(peerId, peerPb, existingPeer)\n }\n\n async * all (query?: PeerQuery): AsyncGenerator<Peer, void, unknown> {\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, this.maxAddressAge))) {\n const peerId = keyToPeerId(key)\n\n // skip self peer if present\n if (peerId.equals(this.peerId)) {\n continue\n }\n\n const peer = PeerPB.decode(value)\n\n // remove expired peer\n if (this.#peerIsExpired(peerId, peer)) {\n await this.datastore.delete(key)\n continue\n }\n\n yield pbToPeer(peerId, peer, this.peerId.equals(peerId) ? Infinity : this.maxAddressAge)\n }\n }\n\n async #findExistingPeer (peerId: PeerId): Promise<ExistingPeer | undefined> {\n try {\n const key = peerIdToDatastoreKey(peerId)\n const buf = await this.datastore.get(key)\n const peerPB = PeerPB.decode(buf)\n\n // remove expired peer\n if (this.#peerIsExpired(peerId, peerPB)) {\n await this.datastore.delete(key)\n throw new NotFoundError()\n }\n\n return {\n peerPB,\n peer: bytesToPeer(peerId, buf, this.maxAddressAge)\n }\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n this.log.error('invalid peer data found in peer store - %e', err)\n }\n }\n }\n\n async #saveIfDifferent (peerId: PeerId, peer: PeerPB, existingPeer?: ExistingPeer): Promise<PeerUpdate> {\n // record last update\n peer.updated = Date.now()\n const buf = PeerPB.encode(peer)\n\n await this.datastore.put(peerIdToDatastoreKey(peerId), buf)\n\n return {\n peer: bytesToPeer(peerId, buf, this.maxAddressAge),\n previous: existingPeer?.peer,\n updated: existingPeer == null || !peerEquals(peer, existingPeer.peerPB)\n }\n }\n\n #peerIsExpired (peerId: PeerId, peer: PeerPB): boolean {\n if (peer.updated == null) {\n return true\n }\n\n if (this.peerId.equals(peerId)) {\n return false\n }\n\n const expired = peer.updated < (Date.now() - this.maxPeerAge)\n const minAddressObserved = Date.now() - this.maxAddressAge\n const addrs = peer.addresses.filter(addr => {\n return addr.observed != null && addr.observed > minAddressObserved\n })\n\n return expired && addrs.length === 0\n }\n}\n", "/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\n\nimport { peerIdFromCID } from '@libp2p/peer-id'\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'\nimport all from 'it-all'\nimport { PersistentStore, type PeerUpdate } from './store.js'\nimport type { ComponentLogger, Libp2pEvents, Logger, TypedEventTarget, PeerId, PeerStore, Peer, PeerData, PeerQuery, PeerInfo } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface PersistentPeerStoreComponents {\n peerId: PeerId\n datastore: Datastore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\n/**\n * Return true to allow storing the passed multiaddr for the passed peer\n */\nexport interface AddressFilter {\n (peerId: PeerId, multiaddr: Multiaddr): Promise<boolean> | boolean\n}\n\nexport interface PersistentPeerStoreInit {\n /**\n * Used to remove multiaddrs of peers before storing them. The default is to\n * store all addresses\n */\n addressFilter?: AddressFilter\n\n /**\n * The multiaddrs for a given peer will expire after this number of ms after\n * which they must be re-fetched using the peer routing.\n *\n * Defaults to one hour.\n *\n * @default 3_600_000\n */\n maxAddressAge?: number\n\n /**\n * Any peer without multiaddrs that has not been updated after this number of\n * ms will be evicted from the peer store.\n *\n * Defaults to six hours.\n *\n * @default 21_600_000\n */\n maxPeerAge?: number\n}\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nclass PersistentPeerStore implements PeerStore {\n private readonly store: PersistentStore\n private readonly events: TypedEventTarget<Libp2pEvents>\n private readonly peerId: PeerId\n private readonly log: Logger\n\n constructor (components: PersistentPeerStoreComponents, init: PersistentPeerStoreInit = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store')\n this.events = components.events\n this.peerId = components.peerId\n this.store = new PersistentStore(components, init)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/peer-store'\n\n async forEach (fn: (peer: Peer,) => void, query?: PeerQuery): Promise<void> {\n this.log.trace('forEach await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('forEach got read lock')\n\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer)\n }\n } finally {\n this.log.trace('forEach release read lock')\n release()\n }\n }\n\n async all (query?: PeerQuery): Promise<Peer[]> {\n this.log.trace('all await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('all got read lock')\n\n try {\n return await all(this.store.all(query))\n } finally {\n this.log.trace('all release read lock')\n release()\n }\n }\n\n async delete (peerId: PeerId): Promise<void> {\n this.log.trace('delete await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('delete got write lock')\n\n try {\n await this.store.delete(peerId)\n } finally {\n this.log.trace('delete release write lock')\n release()\n }\n }\n\n async has (peerId: PeerId): Promise<boolean> {\n this.log.trace('has await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('has got read lock')\n\n try {\n return await this.store.has(peerId)\n } finally {\n this.log.trace('has release read lock')\n release()\n }\n }\n\n async get (peerId: PeerId): Promise<Peer> {\n this.log.trace('get await read lock')\n const release = await this.store.lock.readLock()\n this.log.trace('get got read lock')\n\n try {\n return await this.store.load(peerId)\n } finally {\n this.log.trace('get release read lock')\n release()\n }\n }\n\n async getInfo (peerId: PeerId): Promise<PeerInfo> {\n const peer = await this.get(peerId)\n\n return {\n id: peer.id,\n multiaddrs: peer.addresses.map(({ multiaddr }) => multiaddr)\n }\n }\n\n async save (id: PeerId, data: PeerData): Promise<Peer> {\n this.log.trace('save await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('save got write lock')\n\n try {\n const result = await this.store.save(id, data)\n\n this.#emitIfUpdated(id, result)\n\n return result.peer\n } finally {\n this.log.trace('save release write lock')\n release()\n }\n }\n\n async patch (id: PeerId, data: PeerData): Promise<Peer> {\n this.log.trace('patch await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('patch got write lock')\n\n try {\n const result = await this.store.patch(id, data)\n\n this.#emitIfUpdated(id, result)\n\n return result.peer\n } finally {\n this.log.trace('patch release write lock')\n release()\n }\n }\n\n async merge (id: PeerId, data: PeerData): Promise<Peer> {\n this.log.trace('merge await write lock')\n const release = await this.store.lock.writeLock()\n this.log.trace('merge got write lock')\n\n try {\n const result = await this.store.merge(id, data)\n\n this.#emitIfUpdated(id, result)\n\n return result.peer\n } finally {\n this.log.trace('merge release write lock')\n release()\n }\n }\n\n async consumePeerRecord (buf: Uint8Array, expectedPeer?: PeerId): Promise<boolean> {\n const envelope = await RecordEnvelope.openAndCertify(buf, PeerRecord.DOMAIN)\n const peerId = peerIdFromCID(envelope.publicKey.toCID())\n\n if (expectedPeer?.equals(peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, peerId)\n return false\n }\n\n const peerRecord = PeerRecord.createFromProtobuf(envelope.payload)\n let peer: Peer | undefined\n\n try {\n peer = await this.get(peerId)\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope)\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload)\n\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber)\n return false\n }\n }\n\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n })\n\n return true\n }\n\n #emitIfUpdated (id: PeerId, result: PeerUpdate): void {\n if (!result.updated) {\n return\n }\n\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result })\n } else {\n this.events.safeDispatchEvent('peer:update', { detail: result })\n }\n }\n}\n\nexport function persistentPeerStore (components: PersistentPeerStoreComponents, init: PersistentPeerStoreInit = {}): PeerStore {\n return new PersistentPeerStore(components, init)\n}\n", "export class OpenFailedError extends Error {\n static name = 'OpenFailedError'\n static code = 'ERR_OPEN_FAILED'\n name = OpenFailedError.name\n code = OpenFailedError.code\n\n constructor (message = 'Open failed') {\n super(message)\n }\n}\n\nexport class CloseFailedError extends Error {\n static name = 'CloseFailedError'\n static code = 'ERR_CLOSE_FAILED'\n name = CloseFailedError.name\n code = CloseFailedError.code\n\n constructor (message = 'Close failed') {\n super(message)\n }\n}\n\nexport class PutFailedError extends Error {\n static name = 'PutFailedError'\n static code = 'ERR_PUT_FAILED'\n name = PutFailedError.name\n code = PutFailedError.code\n\n constructor (message = 'Put failed') {\n super(message)\n }\n}\n\nexport class GetFailedError extends Error {\n static name = 'GetFailedError'\n static code = 'ERR_GET_FAILED'\n name = GetFailedError.name\n code = GetFailedError.code\n\n constructor (message = 'Get failed') {\n super(message)\n }\n}\n\nexport class DeleteFailedError extends Error {\n static name = 'DeleteFailedError'\n static code = 'ERR_DELETE_FAILED'\n name = DeleteFailedError.name\n code = DeleteFailedError.code\n\n constructor (message = 'Delete failed') {\n super(message)\n }\n}\n\nexport class HasFailedError extends Error {\n static name = 'HasFailedError'\n static code = 'ERR_HAS_FAILED'\n name = HasFailedError.name\n code = HasFailedError.code\n\n constructor (message = 'Has failed') {\n super(message)\n }\n}\n\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n static code = 'ERR_NOT_FOUND'\n name = NotFoundError.name\n code = NotFoundError.code\n\n constructor (message = 'Not Found') {\n super(message)\n }\n}\n\nexport class AbortError extends Error {\n static name = 'AbortError'\n static code = 'ERR_ABORTED'\n name = AbortError.name\n code = AbortError.code\n\n constructor (message = 'Aborted') {\n super(message)\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Drains an (async) iterable discarding its' content and does not return\n * anything\n */\nfunction drain (source: Iterable<unknown>): void\nfunction drain (source: Iterable<unknown> | AsyncIterable<unknown>): Promise<void>\nfunction drain (source: Iterable<unknown> | AsyncIterable<unknown>): Promise<void> | void {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n })()\n } else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\n\nexport default drain\n", "/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\n\nexport interface Peek <T> {\n peek(): IteratorResult<T, undefined>\n}\n\nexport interface AsyncPeek <T> {\n peek(): Promise<IteratorResult<T, undefined>>\n}\n\nexport interface Push <T> {\n push(value: T): void\n}\n\nexport type Peekable <T> = Iterable<T> & Peek<T> & Push<T> & Iterator<T>\n\nexport type AsyncPeekable <T> = AsyncIterable<T> & AsyncPeek<T> & Push<T> & AsyncIterator<T>\n\nfunction peekable <T> (iterable: Iterable<T>): Peekable<T>\nfunction peekable <T> (iterable: AsyncIterable<T>): AsyncPeekable<T>\nfunction peekable <T> (iterable: Iterable<T> | AsyncIterable<T>): Peekable<T> | AsyncPeekable<T> {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator]\n\n const queue: any[] = []\n\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next()\n },\n push: (value: any) => {\n queue.push(value)\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n }\n }\n\n return iterator.next()\n },\n [symbol] () {\n return this\n }\n }\n}\n\nexport default peekable\n", "/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\n\nimport peek from 'it-peekable'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Filters the passed (async) iterable by using the filter function\n */\nfunction filter <T> (source: Iterable<T>, fn: (val: T, index: number) => Promise<boolean>): AsyncGenerator<T, void, undefined>\nfunction filter <T> (source: Iterable<T>, fn: (val: T, index: number) => boolean): Generator<T, void, undefined>\nfunction filter <T> (source: Iterable<T> | AsyncIterable<T>, fn: (val: T, index: number) => boolean | Promise<boolean>): AsyncGenerator<T, void, undefined>\nfunction filter <T> (source: Iterable<T> | AsyncIterable<T>, fn: (val: T, index: number) => boolean | Promise<boolean>): Generator<T, void, undefined> | AsyncGenerator<T, void, undefined> {\n let index = 0\n\n if (isAsyncIterable(source)) {\n return (async function * () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry\n }\n }\n })()\n }\n\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source)\n const { value, done } = peekable.next()\n\n if (done === true) {\n return (function * () {}())\n }\n\n const res = fn(value, index++)\n\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function * () {\n if (await res) {\n yield value\n }\n\n for await (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry\n }\n }\n })()\n }\n\n const func = fn as (val: T, index: number) => boolean\n\n return (function * () {\n if (res === true) {\n yield value\n }\n\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry\n }\n }\n })()\n}\n\nexport default filter\n", "/**\n * @packageDocumentation\n *\n * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\n\nimport all from 'it-all'\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\nexport interface CompareFunction<T> {\n (a: T, b: T): number\n}\n\n/**\n * Collects all values from an async iterator, sorts them\n * using the passed function and yields them\n */\nfunction sort <T> (source: Iterable<T>, sorter: CompareFunction<T>): Generator<T, void, undefined>\nfunction sort <T> (source: Iterable<T> | AsyncIterable<T>, sorter: CompareFunction<T>): AsyncGenerator<T, void, undefined>\nfunction sort <T> (source: Iterable<T> | AsyncIterable<T>, sorter: CompareFunction<T>): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n if (isAsyncIterable(source)) {\n return (async function * () {\n const arr = await all(source)\n\n yield * arr.sort(sorter)\n })()\n }\n\n return (function * () {\n const arr = all(source)\n\n yield * arr.sort(sorter)\n })()\n}\n\nexport default sort\n", "/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\n\nfunction isAsyncIterable <T> (thing: any): thing is AsyncIterable<T> {\n return thing[Symbol.asyncIterator] != null\n}\n\n/**\n * Stop iteration after n items have been received\n */\nfunction take <T> (source: Iterable<T>, limit: number): Generator<T, void, undefined>\nfunction take <T> (source: Iterable<T> | AsyncIterable<T>, limit: number): AsyncGenerator<T, void, undefined>\nfunction take <T> (source: Iterable<T> | AsyncIterable<T>, limit: number): AsyncGenerator<T, void, undefined> | Generator<T, void, undefined> {\n if (isAsyncIterable(source)) {\n return (async function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for await (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n }\n\n return (function * () {\n let items = 0\n\n if (limit < 1) {\n return\n }\n\n for (const entry of source) {\n yield entry\n\n items++\n\n if (items === limit) {\n return\n }\n }\n })()\n}\n\nexport default take\n", "import drain from 'it-drain'\nimport filter from 'it-filter'\nimport sort from 'it-sort'\nimport take from 'it-take'\nimport type { Batch, Datastore, Key, KeyQuery, Pair, Query } from 'interface-datastore'\nimport type { AbortOptions, Await, AwaitIterable } from 'interface-store'\n\nexport class BaseDatastore implements Datastore {\n put (key: Key, val: Uint8Array, options?: AbortOptions): Await<Key> {\n return Promise.reject(new Error('.put is not implemented'))\n }\n\n get (key: Key, options?: AbortOptions): Await<Uint8Array> {\n return Promise.reject(new Error('.get is not implemented'))\n }\n\n has (key: Key, options?: AbortOptions): Await<boolean> {\n return Promise.reject(new Error('.has is not implemented'))\n }\n\n delete (key: Key, options?: AbortOptions): Await<void> {\n return Promise.reject(new Error('.delete is not implemented'))\n }\n\n async * putMany (source: AwaitIterable<Pair>, options: AbortOptions = {}): AwaitIterable<Key> {\n for await (const { key, value } of source) {\n await this.put(key, value, options)\n yield key\n }\n }\n\n async * getMany (source: AwaitIterable<Key>, options: AbortOptions = {}): AwaitIterable<Pair> {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n }\n }\n }\n\n async * deleteMany (source: AwaitIterable<Key>, options: AbortOptions = {}): AwaitIterable<Key> {\n for await (const key of source) {\n await this.delete(key, options)\n yield key\n }\n }\n\n batch (): Batch {\n let puts: Pair[] = []\n let dels: Key[] = []\n\n return {\n put (key, value) {\n puts.push({ key, value })\n },\n\n delete (key) {\n dels.push(key)\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options))\n puts = []\n await drain(this.deleteMany(dels, options))\n dels = []\n }\n }\n }\n\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _all (q: Query, options?: AbortOptions): AwaitIterable<Pair> {\n throw new Error('._all is not implemented')\n }\n\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async * _allKeys (q: KeyQuery, options?: AbortOptions): AwaitIterable<Key> {\n throw new Error('._allKeys is not implemented')\n }\n\n query (q: Query, options?: AbortOptions): AwaitIterable<Pair> {\n let it = this._all(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (e) => e.key.toString().startsWith(prefix))\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n let i = 0\n const offset = q.offset\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n\n queryKeys (q: KeyQuery, options?: AbortOptions): AwaitIterable<Key> {\n let it = this._allKeys(q, options)\n\n if (q.prefix != null) {\n const prefix = q.prefix\n it = filter(it, (key) =>\n key.toString().startsWith(prefix)\n )\n }\n\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it)\n }\n\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it)\n }\n\n if (q.offset != null) {\n const offset = q.offset\n let i = 0\n it = filter(it, () => i++ >= offset)\n }\n\n if (q.limit != null) {\n it = take(it, q.limit)\n }\n\n return it\n }\n}\n", "import { Key } from 'interface-datastore/key'\nimport { NotFoundError } from 'interface-store'\nimport { BaseDatastore } from './base.js'\nimport type { Pair } from 'interface-datastore'\nimport type { Await, AwaitIterable } from 'interface-store'\n\nexport class MemoryDatastore extends BaseDatastore {\n private readonly data: Map<string, Uint8Array>\n\n constructor () {\n super()\n\n this.data = new Map()\n }\n\n put (key: Key, val: Uint8Array): Await<Key> { // eslint-disable-line require-await\n this.data.set(key.toString(), val)\n\n return key\n }\n\n get (key: Key): Await<Uint8Array> {\n const result = this.data.get(key.toString())\n\n if (result == null) {\n throw new NotFoundError()\n }\n\n return result\n }\n\n has (key: Key): Await<boolean> { // eslint-disable-line require-await\n return this.data.has(key.toString())\n }\n\n delete (key: Key): Await<void> { // eslint-disable-line require-await\n this.data.delete(key.toString())\n }\n\n * _all (): AwaitIterable<Pair> {\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value }\n }\n }\n\n * _allKeys (): AwaitIterable<Key> {\n for (const key of this.data.keys()) {\n yield new Key(key)\n }\n }\n}\n", "import type { Startable } from '@libp2p/interface'\n\nexport interface DebouncedFunction extends Startable {\n (): void\n}\n\n/**\n * Returns a function wrapper that will only call the passed function once\n *\n * Important - the passed function should not throw or reject\n */\nexport function debounce (func: () => void | Promise<void>, wait: number): DebouncedFunction {\n let timeout: ReturnType<typeof setTimeout> | undefined\n\n const output = function (): void {\n const later = function (): void {\n timeout = undefined\n void func()\n }\n\n clearTimeout(timeout)\n timeout = setTimeout(later, wait)\n }\n output.start = () => {}\n output.stop = () => {\n clearTimeout(timeout)\n }\n\n return output\n}\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { Netmask } from 'netmask'\n\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n]\n\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new Netmask(ipRange))\n\nfunction ipv4Check (ipAddr: string): boolean {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr)) return true\n }\n\n return false\n}\n\nfunction isIpv4MappedIpv6 (ipAddr: string): boolean {\n return /^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(ipAddr)\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2\n */\nfunction ipv4MappedIpv6Check (ipAddr: string): boolean {\n const parts = ipAddr.split(':')\n\n if (parts.length < 2) {\n return false\n }\n\n const octet34 = parts[parts.length - 1].padStart(4, '0')\n const octet12 = parts[parts.length - 2].padStart(4, '0')\n\n const ip4 = `${parseInt(octet12.substring(0, 2), 16)}.${parseInt(octet12.substring(2), 16)}.${parseInt(octet34.substring(0, 2), 16)}.${parseInt(octet34.substring(2), 16)}`\n\n return ipv4Check(ip4)\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.2 example 3\n */\nfunction isIpv4EmbeddedIpv6 (ipAddr: string): boolean {\n return /^::ffff:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr)\n}\n\nfunction ipv4EmbeddedIpv6Check (ipAddr: string): boolean {\n const parts = ipAddr.split(':')\n const ip4 = parts[parts.length - 1]\n\n return ipv4Check(ip4)\n}\n\nfunction ipv6Check (ipAddr: string): boolean {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr)\n}\n\nexport function isPrivateIp (ip: string): boolean | undefined {\n if (isIPv4(ip)) return ipv4Check(ip)\n else if (isIpv4MappedIpv6(ip)) return ipv4MappedIpv6Check(ip)\n else if (isIpv4EmbeddedIpv6(ip)) return ipv4EmbeddedIpv6Check(ip)\n else if (isIPv6(ip)) return ipv6Check(ip)\n else return undefined\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { base64url } from 'multiformats/bases/base64'\nimport type { Matcher, MultiaddrMatcher } from './index.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma: Multiaddr): string[] => {\n return ma.toString().split('/').slice(1)\n}\n\nexport const func = (fn: (val: string) => boolean): Matcher => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false\n }\n\n if (fn(vals[0])) {\n return vals.slice(1)\n }\n\n return false\n },\n pattern: 'fn'\n }\n}\n\nexport const literal = (str: string): Matcher => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n }\n}\n\nexport const string = (): Matcher => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n }\n}\n\nexport const number = (): Matcher => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n }\n}\n\nexport const peerId = (): Matcher => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false\n }\n\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false\n }\n\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n base58btc.decode(`z${vals[1]}`)\n } catch (err) {\n return false\n }\n } else {\n return false\n }\n\n return vals.slice(2)\n },\n pattern: '/p2p/{peerid}'\n }\n}\n\nexport const certhash = (): Matcher => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false\n }\n\n if (vals[0] !== 'certhash') {\n return false\n }\n\n try {\n base64url.decode(vals[1])\n } catch {\n return false\n }\n\n return vals.slice(2)\n },\n pattern: '/certhash/{certhash}'\n }\n}\n\nexport const optional = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return result\n },\n pattern: `optional(${matcher.pattern})`\n }\n}\n\nexport const or = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n let matches: string[] | undefined\n\n for (const matcher of matchers) {\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n continue\n }\n\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result\n }\n }\n\n if (matches == null) {\n return false\n }\n\n return matches\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n }\n}\n\nexport const and = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n return false\n }\n\n vals = result\n }\n\n return vals\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n }\n}\n\nexport function fmt (...matchers: Matcher[]): MultiaddrMatcher {\n function match (ma: Multiaddr): string[] | false {\n let parts = toParts(ma)\n\n for (const matcher of matchers) {\n const result = matcher.match(parts)\n\n if (result === false) {\n return false\n }\n\n parts = result\n }\n\n return parts\n }\n\n function matches (ma: Multiaddr): boolean {\n const result = match(ma)\n\n return result !== false\n }\n\n function exactMatch (ma: Multiaddr): boolean {\n const result = match(ma)\n\n if (result === false) {\n return false\n }\n\n return result.length === 0\n }\n\n return {\n matchers,\n matches,\n exactMatch\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\nimport { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { and, or, literal, string, peerId, optional, fmt, func, number, certhash } from './utils.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * A matcher accepts multiaddr components and either fails to match and returns\n * false or returns a sublist of unmatched components\n */\nexport interface Matcher {\n match(parts: string[]): string[] | false\n pattern: string\n}\n\n/**\n * A MultiaddrMatcher allows interpreting a multiaddr as a certain type of\n * multiaddr\n */\nexport interface MultiaddrMatcher {\n /**\n * The matchers that make up this MultiaddrMatcher - useful if you want to\n * make your own custom matchers\n */\n matchers: Matcher[]\n\n /**\n * Returns true if the passed multiaddr can be treated as this type of\n * multiaddr\n */\n matches(ma: Multiaddr): boolean\n\n /**\n * Returns true if the passed multiaddr terminates as this type of\n * multiaddr\n */\n exactMatch(ma: Multiaddr): boolean\n}\n\n/**\n * Matches PeerId addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { PEER_ID } from '@multiformats/multiaddr-matcher'\n *\n * PEER_ID.matches(multiaddr('/p2p/Qmfoo')) // true\n * PEER_ID.matches(multiaddr('/ipfs/Qmfoo')) // true\n * ```\n */\nconst _PEER_ID = peerId()\n\nexport const PEER_ID = fmt(_PEER_ID)\n\n/**\n * DNS matchers\n */\nconst _DNS4 = and(literal('dns4'), string())\nconst _DNS6 = and(literal('dns6'), string())\nconst _DNSADDR = and(literal('dnsaddr'), string())\nconst _DNS = and(literal('dns'), string())\n\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4, optional(peerId()))\n\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6, optional(peerId()))\n\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR, optional(peerId()))\n\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(peerId()))\n\nconst _IP4 = and(literal('ip4'), func(isIPv4))\nconst _IP6 = and(literal('ip6'), func(isIPv6))\nconst _IP = or(_IP4, _IP6)\n\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR)\n\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(peerId()))))\n\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4)\n\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6)\n\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP)\n\nconst _TCP = and(_IP_OR_DOMAIN, literal('tcp'), number())\nconst _UDP = and(_IP_OR_DOMAIN, literal('udp'), number())\n\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(and(_TCP, optional(peerId())))\n\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP)\n\nconst _QUIC = and(_UDP, literal('quic'), optional(peerId()))\nconst _QUICV1 = and(_UDP, literal('quic-v1'), optional(peerId()))\n\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUICV1)\n\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC)\n\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUICV1 = fmt(_QUICV1)\n\nconst _WEB = or(\n _IP_OR_DOMAIN,\n _TCP,\n _UDP,\n _QUIC,\n _QUICV1\n)\n\nconst _WebSockets = or(\n and(_WEB, literal('ws'), optional(peerId()))\n)\n\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets)\n\nconst _WebSocketsSecure = or(\n and(_WEB, literal('wss'), optional(peerId())),\n and(_WEB, literal('tls'), optional(and(literal('sni'), string())), literal('ws'), optional(peerId()))\n)\n\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure)\n\nconst _WebRTCDirect = and(_UDP, literal('webrtc-direct'), optional(certhash()), optional(certhash()), optional(peerId()))\n\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect)\n\nconst _WebTransport = and(_QUICV1, literal('webtransport'), optional(certhash()), optional(certhash()), optional(peerId()))\n\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport)\n\nconst _P2P = or(\n _WebSockets,\n _WebSocketsSecure,\n and(_TCP, optional(peerId())),\n and(QUIC_V0_OR_V1, optional(peerId())),\n and(_IP_OR_DOMAIN, optional(peerId())),\n _WebRTCDirect,\n _WebTransport,\n peerId()\n)\n\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P)\n\nconst _Circuit = and(_P2P, literal('p2p-circuit'), peerId())\n\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit)\n\nconst _WebRTC = or(\n and(_P2P, literal('p2p-circuit'), literal('webrtc'), optional(peerId())),\n and(_P2P, literal('webrtc'), optional(peerId())),\n and(literal('webrtc'), optional(peerId()))\n)\n\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC)\n\nconst _HTTP = or(\n and(_IP_OR_DOMAIN, literal('tcp'), number(), literal('http'), optional(peerId())),\n and(_IP_OR_DOMAIN, literal('http'), optional(peerId()))\n)\n\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP)\n\nconst _HTTPS = or(\n and(_IP_OR_DOMAIN, literal('tcp'), or(\n and(literal('443'), literal('http')),\n and(number(), literal('https')),\n and(number(), literal('tls'), literal('http'))\n ), optional(peerId())),\n and(_IP_OR_DOMAIN, literal('tls'), literal('http'), optional(peerId())),\n and(_IP_OR_DOMAIN, literal('https'), optional(peerId()))\n)\n\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS)\n\nconst _Memory = or(\n and(literal('memory'), string(), optional(peerId()))\n)\n\n/**\n * Matches Memory addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Memory } from '@multiformats/multiaddr-matcher'\n *\n * Memory.matches(multiaddr('/memory/0xDEADBEEF')) // true\n * ```\n */\nexport const Memory = fmt(_Memory)\n", "import { isPrivateIp } from '@libp2p/utils/private-ip'\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport type { AddressManagerComponents, AddressManagerInit } from './index.js'\nimport type { Logger } from '@libp2p/interface'\nimport type { NodeAddress } from '@libp2p/interface-internal'\nimport type { Multiaddr, StringTuple } from '@multiformats/multiaddr'\n\nconst MAX_DATE = 8_640_000_000_000_000\n\nexport const defaultValues = {\n maxObservedAddresses: 10\n}\n\ninterface DNSMapping {\n domain: string\n verified: boolean\n expires: number\n lastVerified?: number\n}\n\nconst CODEC_TLS = 0x01c0\nconst CODEC_SNI = 0x01c1\nconst CODEC_DNS = 0x35\nconst CODEC_DNS4 = 0x36\nconst CODEC_DNS6 = 0x37\nconst CODEC_DNSADDR = 0x38\n\nexport class DNSMappings {\n private readonly log: Logger\n private readonly mappings: Map<string, DNSMapping>\n\n constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {\n this.log = components.logger.forComponent('libp2p:address-manager:dns-mappings')\n this.mappings = new Map()\n }\n\n has (ma: Multiaddr): boolean {\n const host = this.findHost(ma)\n\n for (const mapping of this.mappings.values()) {\n if (mapping.domain === host) {\n return true\n }\n }\n\n return false\n }\n\n add (domain: string, addresses: string[]): void {\n addresses.forEach(ip => {\n this.log('add DNS mapping %s to %s', ip, domain)\n // we are only confident if this is an local domain mapping, otherwise\n // we will require external validation\n const verified = isPrivateIp(ip) === true\n\n this.mappings.set(ip, {\n domain,\n verified,\n expires: verified ? MAX_DATE - Date.now() : 0,\n lastVerified: verified ? MAX_DATE - Date.now() : undefined\n })\n })\n }\n\n remove (ma: Multiaddr): boolean {\n const host = this.findHost(ma)\n let wasConfident = false\n\n for (const [ip, mapping] of this.mappings.entries()) {\n if (mapping.domain === host) {\n this.log('removing %s to %s DNS mapping %e', ip, mapping.domain, new Error('where'))\n this.mappings.delete(ip)\n wasConfident = wasConfident || mapping.verified\n }\n }\n\n return wasConfident\n }\n\n getAll (addresses: NodeAddress[]): NodeAddress[] {\n const dnsMappedAddresses: NodeAddress[] = []\n\n for (let i = 0; i < addresses.length; i++) {\n const address = addresses[i]\n const tuples = address.multiaddr.stringTuples()\n const host = tuples[0][1]\n\n if (host == null) {\n continue\n }\n\n for (const [ip, mapping] of this.mappings.entries()) {\n if (host !== ip) {\n continue\n }\n\n // insert SNI tuple after TLS tuple, if one is present\n const mappedIp = this.maybeAddSNITuple(tuples, mapping.domain)\n\n if (mappedIp) {\n // remove the address and replace it with the version that includes\n // the SNI tuple\n addresses.splice(i, 1)\n i--\n\n dnsMappedAddresses.push({\n multiaddr: multiaddr(`/${\n tuples.map(tuple => {\n return [\n protocols(tuple[0]).name,\n tuple[1]\n ].join('/')\n }).join('/')\n }`),\n verified: mapping.verified,\n type: 'dns-mapping',\n expires: mapping.expires,\n lastVerified: mapping.lastVerified\n })\n }\n }\n }\n\n return dnsMappedAddresses\n }\n\n private maybeAddSNITuple (tuples: StringTuple[], domain: string): boolean {\n for (let j = 0; j < tuples.length; j++) {\n if (tuples[j][0] === CODEC_TLS && tuples[j + 1]?.[0] !== CODEC_SNI) {\n tuples.splice(j + 1, 0, [CODEC_SNI, domain])\n return true\n }\n }\n\n return false\n }\n\n confirm (ma: Multiaddr, ttl: number): boolean {\n const host = this.findHost(ma)\n let startingConfidence = false\n\n for (const [ip, mapping] of this.mappings.entries()) {\n if (mapping.domain === host) {\n this.log('marking %s to %s DNS mapping as verified', ip, mapping.domain)\n startingConfidence = mapping.verified\n mapping.verified = true\n mapping.expires = Date.now() + ttl\n mapping.lastVerified = Date.now()\n }\n }\n\n return startingConfidence\n }\n\n unconfirm (ma: Multiaddr, ttl: number): boolean {\n const host = this.findHost(ma)\n let wasConfident = false\n\n for (const [ip, mapping] of this.mappings.entries()) {\n if (mapping.domain === host) {\n this.log('removing verification of %s to %s DNS mapping', ip, mapping.domain)\n wasConfident = wasConfident || mapping.verified\n mapping.verified = false\n mapping.expires = Date.now() + ttl\n }\n }\n\n return wasConfident\n }\n\n private findHost (ma: Multiaddr): string | undefined {\n for (const tuple of ma.stringTuples()) {\n if (tuple[0] === CODEC_SNI) {\n return tuple[1]\n }\n\n if (tuple[0] === CODEC_DNS || tuple[0] === CODEC_DNS4 || tuple[0] === CODEC_DNS6 || tuple[0] === CODEC_DNSADDR) {\n return tuple[1]\n }\n }\n }\n}\n", "import { isIPv4 } from '@chainsafe/is-ip'\nimport { multiaddr, protocols } from '@multiformats/multiaddr'\nimport type { AddressManagerComponents, AddressManagerInit } from './index.js'\nimport type { Logger } from '@libp2p/interface'\nimport type { NodeAddress } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport const defaultValues = {\n maxObservedAddresses: 10\n}\n\ninterface PublicAddressMapping {\n internalIp: string\n internalPort: number\n externalIp: string\n externalPort: number\n externalFamily: 4 | 6\n protocol: 'tcp' | 'udp'\n verified: boolean\n expires: number\n lastVerified?: number\n}\n\nconst CODEC_IP4 = 0x04\nconst CODEC_IP6 = 0x29\nconst CODEC_TCP = 0x06\nconst CODEC_UDP = 0x0111\n\nexport class IPMappings {\n private readonly log: Logger\n private readonly mappings: Map<string, PublicAddressMapping[]>\n\n constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {\n this.log = components.logger.forComponent('libp2p:address-manager:ip-mappings')\n this.mappings = new Map()\n }\n\n has (ma: Multiaddr): boolean {\n const tuples = ma.stringTuples()\n\n for (const mappings of this.mappings.values()) {\n for (const mapping of mappings) {\n if (mapping.externalIp === tuples[0][1]) {\n return true\n }\n }\n }\n\n return false\n }\n\n add (internalIp: string, internalPort: number, externalIp: string, externalPort: number = internalPort, protocol: 'tcp' | 'udp' = 'tcp'): void {\n const key = `${internalIp}-${internalPort}-${protocol}`\n const mappings = this.mappings.get(key) ?? []\n const mapping: PublicAddressMapping = {\n internalIp,\n internalPort,\n externalIp,\n externalPort,\n externalFamily: isIPv4(externalIp) ? 4 : 6,\n protocol,\n verified: false,\n expires: 0\n }\n mappings.push(mapping)\n\n this.mappings.set(key, mappings)\n }\n\n remove (ma: Multiaddr): boolean {\n const tuples = ma.stringTuples()\n const host = tuples[0][1] ?? ''\n const protocol = tuples[1][0] === CODEC_TCP ? 'tcp' : 'udp'\n const port = parseInt(tuples[1][1] ?? '0')\n let wasConfident = false\n\n for (const [key, mappings] of this.mappings.entries()) {\n for (let i = 0; i < mappings.length; i++) {\n const mapping = mappings[i]\n\n if (mapping.externalIp === host && mapping.externalPort === port && mapping.protocol === protocol) {\n this.log('removing %s:%s to %s:%s %s IP mapping', mapping.externalIp, mapping.externalPort, host, port, protocol)\n\n wasConfident = wasConfident || mapping.verified\n mappings.splice(i, 1)\n i--\n }\n }\n\n if (mappings.length === 0) {\n this.mappings.delete(key)\n }\n }\n\n return wasConfident\n }\n\n getAll (addresses: NodeAddress[]): NodeAddress[] {\n const ipMappedAddresses: NodeAddress[] = []\n\n for (const { multiaddr: ma } of addresses) {\n const tuples = ma.stringTuples()\n let tuple: string | undefined\n\n // see if the internal host/port/protocol tuple has been mapped externally\n if ((tuples[0][0] === CODEC_IP4 || tuples[0][0] === CODEC_IP6) && tuples[1][0] === CODEC_TCP) {\n tuple = `${tuples[0][1]}-${tuples[1][1]}-tcp`\n } else if ((tuples[0][0] === CODEC_IP4 || tuples[0][0] === CODEC_IP6) && tuples[1][0] === CODEC_UDP) {\n tuple = `${tuples[0][1]}-${tuples[1][1]}-udp`\n }\n\n if (tuple == null) {\n continue\n }\n\n const mappings = this.mappings.get(tuple)\n\n if (mappings == null) {\n continue\n }\n\n for (const mapping of mappings) {\n tuples[0][0] = mapping.externalFamily === 4 ? CODEC_IP4 : CODEC_IP6\n tuples[0][1] = mapping.externalIp\n tuples[1][1] = `${mapping.externalPort}`\n\n ipMappedAddresses.push({\n multiaddr: multiaddr(`/${\n tuples.map(tuple => {\n return [\n protocols(tuple[0]).name,\n tuple[1]\n ].join('/')\n }).join('/')\n }`),\n verified: mapping.verified,\n type: 'ip-mapping',\n expires: mapping.expires,\n lastVerified: mapping.lastVerified\n })\n }\n }\n\n return ipMappedAddresses\n }\n\n confirm (ma: Multiaddr, ttl: number): boolean {\n const tuples = ma.stringTuples()\n const host = tuples[0][1]\n let startingConfidence = false\n\n for (const mappings of this.mappings.values()) {\n for (const mapping of mappings) {\n // eslint-disable-next-line max-depth\n if (mapping.externalIp === host) {\n this.log('marking %s to %s IP mapping as verified', mapping.internalIp, mapping.externalIp)\n startingConfidence = mapping.verified\n mapping.verified = true\n mapping.expires = Date.now() + ttl\n mapping.lastVerified = Date.now()\n }\n }\n }\n\n return startingConfidence\n }\n\n unconfirm (ma: Multiaddr, ttl: number): boolean {\n const tuples = ma.stringTuples()\n const host = tuples[0][1] ?? ''\n const protocol = tuples[1][0] === CODEC_TCP ? 'tcp' : 'udp'\n const port = parseInt(tuples[1][1] ?? '0')\n let wasConfident = false\n\n for (const mappings of this.mappings.values()) {\n for (let i = 0; i < mappings.length; i++) {\n const mapping = mappings[i]\n\n if (mapping.externalIp === host && mapping.externalPort === port && mapping.protocol === protocol) {\n this.log('removing verification of %s:%s to %s:%s %s IP mapping', mapping.externalIp, mapping.externalPort, host, port, protocol)\n\n wasConfident = wasConfident || mapping.verified\n mapping.verified = false\n mapping.expires = Date.now() + ttl\n }\n }\n }\n\n return wasConfident\n }\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\n\nconst CODEC_IP4 = 0x04\nconst CODEC_IP6 = 0x29\n\n/**\n * Check if a given multiaddr is a link-local address\n */\nexport function isLinkLocal (ma: Multiaddr): boolean {\n try {\n const [[codec, value]] = ma.stringTuples()\n\n if (value == null) {\n return false\n }\n\n if (codec === CODEC_IP4) {\n return value.startsWith('169.254.')\n }\n\n if (codec === CODEC_IP6) {\n return value.toLowerCase().startsWith('fe80')\n }\n } catch {\n\n }\n\n return false\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\n\nconst CODEC_IP4 = 0x04\nconst CODEC_IP6 = 0x29\n\n/**\n * Check if a given multiaddr is IP-based\n */\nexport function isIpBased (ma: Multiaddr): boolean {\n try {\n const [[codec]] = ma.stringTuples()\n\n return codec === CODEC_IP4 || codec === CODEC_IP6\n } catch {\n\n }\n\n return false\n}\n", "import { isPrivateIp } from '../private-ip.js'\nimport { isIpBased } from './is-ip-based.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr starts with a private address\n */\nexport function isPrivate (ma: Multiaddr): boolean {\n try {\n if (!isIpBased(ma)) {\n // not an IP based multiaddr, cannot be private\n return false\n }\n\n const [[, value]] = ma.stringTuples()\n\n if (value == null) {\n return false\n }\n\n return isPrivateIp(value) ?? false\n } catch {\n\n }\n\n return true\n}\n", "import { isLinkLocal } from '@libp2p/utils/multiaddr/is-link-local'\nimport { isPrivate } from '@libp2p/utils/multiaddr/is-private'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport type { AddressManagerComponents, AddressManagerInit } from './index.js'\nimport type { Logger } from '@libp2p/interface'\nimport type { NodeAddress } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport const defaultValues = {\n maxObservedAddresses: 10\n}\n\ninterface ObservedAddressMetadata {\n verified: boolean\n expires: number\n lastVerified?: number\n}\n\nexport class ObservedAddresses {\n private readonly log: Logger\n private readonly addresses: Map<string, ObservedAddressMetadata>\n private readonly maxObservedAddresses: number\n\n constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {\n this.log = components.logger.forComponent('libp2p:address-manager:observed-addresses')\n this.addresses = new Map()\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses\n }\n\n has (ma: Multiaddr): boolean {\n return this.addresses.has(ma.toString())\n }\n\n removePrefixed (prefix: string): void {\n for (const key of this.addresses.keys()) {\n if (key.toString().startsWith(prefix)) {\n this.addresses.delete(key)\n }\n }\n }\n\n add (ma: Multiaddr): void {\n if (this.addresses.size === this.maxObservedAddresses) {\n return\n }\n\n if (isPrivate(ma) || isLinkLocal(ma)) {\n return\n }\n\n this.log('adding observed address %a', ma)\n this.addresses.set(ma.toString(), {\n verified: false,\n expires: 0\n })\n }\n\n getAll (): NodeAddress[] {\n return Array.from(this.addresses)\n .map(([ma, metadata]) => ({\n multiaddr: multiaddr(ma),\n verified: metadata.verified,\n type: 'observed',\n expires: metadata.expires,\n lastVerified: metadata.lastVerified\n }))\n }\n\n remove (ma: Multiaddr): boolean {\n const startingConfidence = this.addresses.get(ma.toString())?.verified ?? false\n\n this.log('removing observed address %a', ma)\n this.addresses.delete(ma.toString())\n\n return startingConfidence\n }\n\n confirm (ma: Multiaddr, ttl: number): boolean {\n const addrString = ma.toString()\n const metadata = this.addresses.get(addrString) ?? {\n verified: false,\n expires: Date.now() + ttl,\n lastVerified: Date.now()\n }\n const startingConfidence = metadata.verified\n metadata.verified = true\n metadata.expires = Date.now() + ttl\n metadata.lastVerified = Date.now()\n\n this.log('marking observed address %a as verified', addrString)\n this.addresses.set(addrString, metadata)\n\n return startingConfidence\n }\n}\n", "import type { Multiaddr } from '@multiformats/multiaddr'\n\nconst CODEC_IP4 = 0x04\nconst CODEC_IP6 = 0x29\nconst CODEC_DNS = 0x35\nconst CODEC_DNS4 = 0x36\nconst CODEC_DNS6 = 0x37\nconst CODEC_DNSADDR = 0x38\n\nconst NETWORK_CODECS = [\n CODEC_IP4,\n CODEC_IP6,\n CODEC_DNS,\n CODEC_DNS4,\n CODEC_DNS6,\n CODEC_DNSADDR\n]\n\n/**\n * Check if a given multiaddr is a network address\n */\nexport function isNetworkAddress (ma: Multiaddr): boolean {\n try {\n const [[codec]] = ma.stringTuples()\n\n return NETWORK_CODECS.includes(codec)\n } catch {\n\n }\n\n return false\n}\n", "import { isNetworkAddress } from '@libp2p/utils/multiaddr/is-network-address'\nimport { isPrivate } from '@libp2p/utils/multiaddr/is-private'\nimport type { AddressManagerComponents, AddressManagerInit } from './index.js'\nimport type { Logger } from '@libp2p/interface'\nimport type { NodeAddress } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport const defaultValues = {\n maxObservedAddresses: 10\n}\n\ninterface TransportAddressMetadata {\n verified: boolean\n expires: number\n lastVerified?: number\n}\n\nexport class TransportAddresses {\n private readonly log: Logger\n private readonly addresses: Map<string, TransportAddressMetadata>\n private readonly maxObservedAddresses: number\n\n constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {\n this.log = components.logger.forComponent('libp2p:address-manager:observed-addresses')\n this.addresses = new Map()\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses\n }\n\n get (multiaddr: Multiaddr, ttl: number): NodeAddress {\n if (isPrivate(multiaddr)) {\n return {\n multiaddr,\n verified: true,\n type: 'transport',\n expires: Date.now() + ttl,\n lastVerified: Date.now()\n }\n }\n\n const key = this.toKey(multiaddr)\n let metadata = this.addresses.get(key)\n\n if (metadata == null) {\n metadata = {\n verified: !isNetworkAddress(multiaddr),\n expires: 0\n }\n\n this.addresses.set(key, metadata)\n }\n\n return {\n multiaddr,\n verified: metadata.verified,\n type: 'transport',\n expires: metadata.expires,\n lastVerified: metadata.lastVerified\n }\n }\n\n has (ma: Multiaddr): boolean {\n const key = this.toKey(ma)\n return this.addresses.has(key)\n }\n\n remove (ma: Multiaddr): boolean {\n const key = this.toKey(ma)\n const startingConfidence = this.addresses.get(key)?.verified ?? false\n\n this.log('removing observed address %a', ma)\n this.addresses.delete(key)\n\n return startingConfidence\n }\n\n confirm (ma: Multiaddr, ttl: number): boolean {\n const key = this.toKey(ma)\n const metadata = this.addresses.get(key) ?? {\n verified: false,\n expires: 0,\n lastVerified: 0\n }\n\n const startingConfidence = metadata.verified\n\n metadata.verified = true\n metadata.expires = Date.now() + ttl\n metadata.lastVerified = Date.now()\n\n this.addresses.set(key, metadata)\n\n return startingConfidence\n }\n\n unconfirm (ma: Multiaddr, ttl: number): boolean {\n const key = this.toKey(ma)\n const metadata = this.addresses.get(key) ?? {\n verified: false,\n expires: 0\n }\n\n const startingConfidence = metadata.verified\n\n metadata.verified = false\n metadata.expires = Date.now() + ttl\n\n this.addresses.set(key, metadata)\n\n return startingConfidence\n }\n\n private toKey (ma: Multiaddr): string {\n if (isNetworkAddress(ma)) {\n // only works for dns/ip based addresses\n const options = ma.toOptions()\n\n return `${options.host}-${options.port}-${options.transport}`\n }\n\n return ma.toString()\n }\n}\n", "/* eslint-disable complexity */\nimport { isIPv4 } from '@chainsafe/is-ip'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { debounce } from '@libp2p/utils/debounce'\nimport { createScalableCuckooFilter } from '@libp2p/utils/filters'\nimport { isPrivateIp } from '@libp2p/utils/private-ip'\nimport { multiaddr } from '@multiformats/multiaddr'\nimport { QUICV1, TCP, WebSockets, WebSocketsSecure } from '@multiformats/multiaddr-matcher'\nimport { DNSMappings } from './dns-mappings.js'\nimport { IPMappings } from './ip-mappings.js'\nimport { ObservedAddresses } from './observed-addresses.js'\nimport { TransportAddresses } from './transport-addresses.js'\nimport type { ComponentLogger, Libp2pEvents, Logger, TypedEventTarget, PeerId, PeerStore } from '@libp2p/interface'\nimport type { AddressManager as AddressManagerInterface, TransportManager, NodeAddress, ConfirmAddressOptions } from '@libp2p/interface-internal'\nimport type { Filter } from '@libp2p/utils/filters'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst ONE_MINUTE = 60_000\n\nexport const defaultValues = {\n maxObservedAddresses: 10,\n addressVerificationTTL: ONE_MINUTE * 10,\n addressVerificationRetry: ONE_MINUTE * 5\n}\n\nexport interface AddressManagerInit {\n /**\n * Pass an function in this field to override the list of addresses\n * that are announced to the network\n */\n announceFilter?: AddressFilter\n\n /**\n * A list of string multiaddrs to listen on\n */\n listen?: string[]\n\n /**\n * A list of string multiaddrs to use instead of those reported by transports\n */\n announce?: string[]\n\n /**\n * A list of string multiaddrs string to never announce\n */\n noAnnounce?: string[]\n\n /**\n * A list of string multiaddrs to add to the list of announced addresses\n */\n appendAnnounce?: string[]\n\n /**\n * Limits the number of observed addresses we will store\n */\n maxObservedAddresses?: number\n\n /**\n * How long before each public address should be reverified in ms.\n *\n * Requires `@libp2p/autonat` or some other verification method to be\n * configured.\n *\n * @default 600_000\n */\n addressVerificationTTL?: number\n\n /**\n * After a transport or mapped address has failed to verify, how long to wait\n * before retrying it in ms\n *\n * Requires `@libp2p/autonat` or some other verification method to be\n * configured.\n *\n * @default 300_000\n */\n addressVerificationRetry?: number\n}\n\nexport interface AddressManagerComponents {\n peerId: PeerId\n transportManager: TransportManager\n peerStore: PeerStore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\n/**\n * A function that takes a list of multiaddrs and returns a list\n * to announce\n */\nexport interface AddressFilter {\n (addrs: Multiaddr[]): Multiaddr[]\n}\n\nconst defaultAddressFilter = (addrs: Multiaddr[]): Multiaddr[] => addrs\n\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId (ma: Multiaddr, peerId: PeerId): Multiaddr {\n const observedPeerIdStr = ma.getPeerId()\n\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = peerIdFromString(observedPeerIdStr)\n\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${peerId.toString()}`))\n }\n }\n\n return ma\n}\n\nexport class AddressManager implements AddressManagerInterface {\n private readonly log: Logger\n private readonly components: AddressManagerComponents\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n private readonly listen: string[]\n private readonly announce: Set<string>\n private readonly appendAnnounce: Set<string>\n private readonly announceFilter: AddressFilter\n private readonly observed: ObservedAddresses\n private readonly dnsMappings: DNSMappings\n private readonly ipMappings: IPMappings\n private readonly transportAddresses: TransportAddresses\n private readonly observedAddressFilter: Filter\n private readonly addressVerificationTTL: number\n private readonly addressVerificationRetry: number\n\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor (components: AddressManagerComponents, init: AddressManagerInit = {}) {\n const { listen = [], announce = [], appendAnnounce = [] } = init\n\n this.components = components\n this.log = components.logger.forComponent('libp2p:address-manager')\n this.listen = listen.map(ma => ma.toString())\n this.announce = new Set(announce.map(ma => ma.toString()))\n this.appendAnnounce = new Set(appendAnnounce.map(ma => ma.toString()))\n this.observed = new ObservedAddresses(components, init)\n this.dnsMappings = new DNSMappings(components, init)\n this.ipMappings = new IPMappings(components, init)\n this.transportAddresses = new TransportAddresses(components, init)\n this.announceFilter = init.announceFilter ?? defaultAddressFilter\n this.observedAddressFilter = createScalableCuckooFilter(1024)\n this.addressVerificationTTL = init.addressVerificationTTL ?? defaultValues.addressVerificationTTL\n this.addressVerificationRetry = init.addressVerificationRetry ?? defaultValues.addressVerificationRetry\n\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = debounce(this._updatePeerStoreAddresses.bind(this), 1000)\n\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses()\n })\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses()\n })\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/address-manager'\n\n _updatePeerStoreAddresses (): void {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAddresses()\n .map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`)\n }\n\n return ma\n })\n\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => {\n this.log.error('error updating addresses', err)\n })\n }\n\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs (): Multiaddr[] {\n return Array.from(this.listen).map((a) => multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.announce).map((a) => multiaddr(a))\n }\n\n /**\n * Get peer announcing multiaddrs\n */\n getAppendAnnounceAddrs (): Multiaddr[] {\n return Array.from(this.appendAnnounce).map((a) => multiaddr(a))\n }\n\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs (): Multiaddr[] {\n return this.observed.getAll().map(addr => addr.multiaddr)\n }\n\n /**\n * Add peer observed addresses\n */\n addObservedAddr (addr: Multiaddr): void {\n const tuples = addr.stringTuples()\n const socketAddress = `${tuples[0][1]}:${tuples[1][1]}`\n\n // ignore if this address if it's been observed before\n if (this.observedAddressFilter.has(socketAddress)) {\n return\n }\n\n this.observedAddressFilter.add(socketAddress)\n\n addr = stripPeerId(addr, this.components.peerId)\n\n // ignore observed address if it is an IP mapping\n if (this.ipMappings.has(addr)) {\n return\n }\n\n // ignore observed address if it is a DNS mapping\n if (this.dnsMappings.has(addr)) {\n return\n }\n\n this.observed.add(addr)\n }\n\n confirmObservedAddr (addr: Multiaddr, options?: ConfirmAddressOptions): void {\n addr = stripPeerId(addr, this.components.peerId)\n let startingConfidence = true\n\n if (options?.type === 'transport' || this.transportAddresses.has(addr)) {\n const transportStartingConfidence = this.transportAddresses.confirm(addr, options?.ttl ?? this.addressVerificationTTL)\n\n if (!transportStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n if (options?.type === 'dns-mapping' || this.dnsMappings.has(addr)) {\n const dnsMappingStartingConfidence = this.dnsMappings.confirm(addr, options?.ttl ?? this.addressVerificationTTL)\n\n if (!dnsMappingStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n if (options?.type === 'ip-mapping' || this.ipMappings.has(addr)) {\n const ipMappingStartingConfidence = this.ipMappings.confirm(addr, options?.ttl ?? this.addressVerificationTTL)\n\n if (!ipMappingStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n if (options?.type === 'observed' || this.observed.has(addr)) {\n // try to match up observed address with local transport listener\n if (this.maybeUpgradeToIPMapping(addr)) {\n this.ipMappings.confirm(addr, options?.ttl ?? this.addressVerificationTTL)\n startingConfidence = false\n } else {\n const observedStartingConfidence = this.observed.confirm(addr, options?.ttl ?? this.addressVerificationTTL)\n\n if (!observedStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n }\n\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses()\n }\n }\n\n removeObservedAddr (addr: Multiaddr, options?: ConfirmAddressOptions): void {\n addr = stripPeerId(addr, this.components.peerId)\n\n let startingConfidence = false\n\n if (this.observed.has(addr)) {\n const observedStartingConfidence = this.observed.remove(addr)\n\n if (!observedStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n if (this.transportAddresses.has(addr)) {\n const transportStartingConfidence = this.transportAddresses.unconfirm(addr, options?.ttl ?? this.addressVerificationRetry)\n\n if (!transportStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n if (this.dnsMappings.has(addr)) {\n const dnsMappingStartingConfidence = this.dnsMappings.unconfirm(addr, options?.ttl ?? this.addressVerificationRetry)\n\n if (!dnsMappingStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n if (this.ipMappings.has(addr)) {\n const ipMappingStartingConfidence = this.ipMappings.unconfirm(addr, options?.ttl ?? this.addressVerificationRetry)\n\n if (!ipMappingStartingConfidence && startingConfidence) {\n startingConfidence = false\n }\n }\n\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (startingConfidence) {\n this._updatePeerStoreAddresses()\n }\n }\n\n getAddresses (): Multiaddr[] {\n const addresses = new Set<string>()\n\n const multiaddrs = this.getAddressesWithMetadata()\n .filter(addr => {\n if (!addr.verified) {\n return false\n }\n\n const maStr = addr.multiaddr.toString()\n\n if (addresses.has(maStr)) {\n return false\n }\n\n addresses.add(maStr)\n\n return true\n })\n .map(address => address.multiaddr)\n\n // filter addressees before returning\n return this.announceFilter(\n multiaddrs.map(str => {\n const ma = multiaddr(str)\n\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma\n }\n\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma\n }\n\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`)\n })\n )\n }\n\n getAddressesWithMetadata (): NodeAddress[] {\n const announceMultiaddrs = this.getAnnounceAddrs()\n\n if (announceMultiaddrs.length > 0) {\n // allow transports to add certhashes and other runtime information\n this.components.transportManager.getListeners().forEach(listener => {\n listener.updateAnnounceAddrs(announceMultiaddrs)\n })\n\n return announceMultiaddrs.map(multiaddr => ({\n multiaddr,\n verified: true,\n type: 'announce',\n expires: Date.now() + this.addressVerificationTTL,\n lastVerified: Date.now()\n }))\n }\n\n let addresses: NodeAddress[] = []\n\n // add transport addresses\n addresses = addresses.concat(\n this.components.transportManager.getAddrs()\n .map(multiaddr => this.transportAddresses.get(multiaddr, this.addressVerificationTTL))\n )\n\n const appendAnnounceMultiaddrs = this.getAppendAnnounceAddrs()\n\n // add append announce addresses\n if (appendAnnounceMultiaddrs.length > 0) {\n // allow transports to add certhashes and other runtime information\n this.components.transportManager.getListeners().forEach(listener => {\n listener.updateAnnounceAddrs(appendAnnounceMultiaddrs)\n })\n\n addresses = addresses.concat(\n appendAnnounceMultiaddrs.map(multiaddr => ({\n multiaddr,\n verified: true,\n type: 'announce',\n expires: Date.now() + this.addressVerificationTTL,\n lastVerified: Date.now()\n }))\n )\n }\n\n // add observed addresses\n addresses = addresses.concat(\n this.observed.getAll()\n )\n\n // add ip mapped addresses\n addresses = addresses.concat(\n this.ipMappings.getAll(addresses)\n )\n\n // add ip->domain mappings, must be done after IP mappings\n addresses = addresses.concat(\n this.dnsMappings.getAll(addresses)\n )\n\n return addresses\n }\n\n addDNSMapping (domain: string, addresses: string[]): void {\n this.dnsMappings.add(domain, addresses)\n }\n\n removeDNSMapping (domain: string): void {\n if (this.dnsMappings.remove(multiaddr(`/dns/${domain}`))) {\n this._updatePeerStoreAddresses()\n }\n }\n\n addPublicAddressMapping (internalIp: string, internalPort: number, externalIp: string, externalPort: number = internalPort, protocol: 'tcp' | 'udp' = 'tcp'): void {\n this.ipMappings.add(internalIp, internalPort, externalIp, externalPort, protocol)\n\n // remove duplicate observed addresses\n this.observed.removePrefixed(`/ip${isIPv4(externalIp) ? 4 : 6}/${externalIp}/${protocol}/${externalPort}`)\n }\n\n removePublicAddressMapping (internalIp: string, internalPort: number, externalIp: string, externalPort: number = internalPort, protocol: 'tcp' | 'udp' = 'tcp'): void {\n if (this.ipMappings.remove(multiaddr(`/ip${isIPv4(externalIp) ? 4 : 6}/${externalIp}/${protocol}/${externalPort}`))) {\n this._updatePeerStoreAddresses()\n }\n }\n\n /**\n * Where an external service (router, gateway, etc) is forwarding traffic to\n * us, attempt to add an IP mapping for the external address - this will\n * include the observed mapping in the address list where we also have a DNS\n * mapping for the external IP.\n *\n * Returns true if we added a new mapping\n */\n private maybeUpgradeToIPMapping (ma: Multiaddr): boolean {\n // this address is already mapped\n if (this.ipMappings.has(ma)) {\n return false\n }\n\n const maOptions = ma.toOptions()\n\n // only public IPv4 addresses\n if (maOptions.family === 6 || maOptions.host === '127.0.0.1' || isPrivateIp(maOptions.host) === true) {\n return false\n }\n\n const listeners = this.components.transportManager.getListeners()\n\n const transportMatchers: Array<(ma: Multiaddr) => boolean> = [\n (ma: Multiaddr) => WebSockets.exactMatch(ma) || WebSocketsSecure.exactMatch(ma),\n (ma: Multiaddr) => TCP.exactMatch(ma),\n (ma: Multiaddr) => QUICV1.exactMatch(ma)\n ]\n\n for (const matcher of transportMatchers) {\n // is the incoming address the same type as the matcher\n if (!matcher(ma)) {\n continue\n }\n\n // get the listeners for this transport\n const transportListeners = listeners.filter(listener => {\n return listener.getAddrs().filter(ma => {\n // only IPv4 addresses of the matcher type\n return ma.toOptions().family === 4 && matcher(ma)\n }).length > 0\n })\n\n // because the NAT mapping could be forwarding different external ports to\n // internal ones, we can only be sure enough to add a mapping if there is\n // a single listener\n if (transportListeners.length !== 1) {\n continue\n }\n\n // we have one listener which listens on one port so whatever the external\n // NAT port mapping is, it should be for this listener\n const linkLocalAddr = transportListeners[0].getAddrs().filter(ma => {\n return ma.toOptions().host !== '127.0.0.1'\n }).pop()\n\n if (linkLocalAddr == null) {\n continue\n }\n\n const linkLocalOptions = linkLocalAddr.toOptions()\n\n // upgrade observed address to IP mapping\n this.observed.remove(ma)\n this.ipMappings.add(\n linkLocalOptions.host,\n linkLocalOptions.port,\n maOptions.host,\n maOptions.port,\n maOptions.transport\n )\n\n return true\n }\n\n return false\n }\n}\n", "export enum messages {\n NOT_STARTED_YET = 'The libp2p node is not started yet',\n NOT_FOUND = 'Not found'\n}\n\nexport class MissingServiceError extends Error {\n constructor (message = 'Missing service') {\n super(message)\n this.name = 'MissingServiceError'\n }\n}\n\nexport class UnmetServiceDependenciesError extends Error {\n constructor (message = 'Unmet service dependencies') {\n super(message)\n this.name = 'UnmetServiceDependenciesError'\n }\n}\n\nexport class NoContentRoutersError extends Error {\n constructor (message = 'No content routers available') {\n super(message)\n this.name = 'NoContentRoutersError'\n }\n}\n\nexport class NoPeerRoutersError extends Error {\n constructor (message = 'No peer routers available') {\n super(message)\n this.name = 'NoPeerRoutersError'\n }\n}\n\nexport class QueriedForSelfError extends Error {\n constructor (message = 'Should not try to find self') {\n super(message)\n this.name = 'QueriedForSelfError'\n }\n}\n\nexport class UnhandledProtocolError extends Error {\n constructor (message = 'Unhandled protocol error') {\n super(message)\n this.name = 'UnhandledProtocolError'\n }\n}\n\nexport class DuplicateProtocolHandlerError extends Error {\n constructor (message = 'Duplicate protocol handler error') {\n super(message)\n this.name = 'DuplicateProtocolHandlerError'\n }\n}\n\nexport class DialDeniedError extends Error {\n constructor (message = 'Dial denied error') {\n super(message)\n this.name = 'DialDeniedError'\n }\n}\n\nexport class UnsupportedListenAddressError extends Error {\n constructor (message = 'No transport was configured to listen on this address') {\n super(message)\n this.name = 'UnsupportedListenAddressError'\n }\n}\n\nexport class UnsupportedListenAddressesError extends Error {\n constructor (message = 'Configured listen addresses could not be listened on') {\n super(message)\n this.name = 'UnsupportedListenAddressesError'\n }\n}\n\nexport class NoValidAddressesError extends Error {\n constructor (message = 'No valid addresses') {\n super(message)\n this.name = 'NoValidAddressesError'\n }\n}\n\nexport class ConnectionInterceptedError extends Error {\n constructor (message = 'Connection intercepted') {\n super(message)\n this.name = 'ConnectionInterceptedError'\n }\n}\n\nexport class ConnectionDeniedError extends Error {\n constructor (message = 'Connection denied') {\n super(message)\n this.name = 'ConnectionDeniedError'\n }\n}\n\nexport class MuxerUnavailableError extends Error {\n constructor (message = 'Stream is not multiplexed') {\n super(message)\n this.name = 'MuxerUnavailableError'\n }\n}\n\nexport class EncryptionFailedError extends Error {\n constructor (message = 'Encryption failed') {\n super(message)\n this.name = 'EncryptionFailedError'\n }\n}\n\nexport class TransportUnavailableError extends Error {\n constructor (message = 'Transport unavailable') {\n super(message)\n this.name = 'TransportUnavailableError'\n }\n}\n", "import { serviceCapabilities, serviceDependencies } from '@libp2p/interface'\nimport { isStartable, type Startable, type Libp2pEvents, type ComponentLogger, type NodeInfo, type ConnectionProtector, type ConnectionGater, type ContentRouting, type TypedEventTarget, type Metrics, type PeerId, type PeerRouting, type PeerStore, type PrivateKey, type Upgrader } from '@libp2p/interface'\nimport { defaultLogger } from '@libp2p/logger'\nimport { MissingServiceError, UnmetServiceDependenciesError } from './errors.js'\nimport type { AddressManager, ConnectionManager, RandomWalk, Registrar, TransportManager } from '@libp2p/interface-internal'\nimport type { DNS } from '@multiformats/dns'\nimport type { Datastore } from 'interface-datastore'\n\nexport interface Components extends Record<string, any>, Startable {\n peerId: PeerId\n privateKey: PrivateKey\n nodeInfo: NodeInfo\n logger: ComponentLogger\n events: TypedEventTarget<Libp2pEvents>\n addressManager: AddressManager\n peerStore: PeerStore\n upgrader: Upgrader\n randomWalk: RandomWalk\n registrar: Registrar\n connectionManager: ConnectionManager\n transportManager: TransportManager\n connectionGater: ConnectionGater\n contentRouting: ContentRouting\n peerRouting: PeerRouting\n datastore: Datastore\n connectionProtector?: ConnectionProtector\n metrics?: Metrics\n dns?: DNS\n}\n\nexport interface ComponentsInit {\n peerId?: PeerId\n privateKey?: PrivateKey\n nodeInfo?: NodeInfo\n logger?: ComponentLogger\n events?: TypedEventTarget<Libp2pEvents>\n addressManager?: AddressManager\n peerStore?: PeerStore\n upgrader?: Upgrader\n randomWalk?: RandomWalk\n metrics?: Metrics\n registrar?: Registrar\n connectionManager?: ConnectionManager\n transportManager?: TransportManager\n connectionGater?: ConnectionGater\n contentRouting?: ContentRouting\n peerRouting?: PeerRouting\n datastore?: Datastore\n connectionProtector?: ConnectionProtector\n dns?: DNS\n}\n\nclass DefaultComponents implements Startable {\n public components: Record<string, any> = {}\n private _started = false\n\n constructor (init: ComponentsInit = {}) {\n this.components = {}\n\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value\n }\n\n if (this.components.logger == null) {\n this.components.logger = defaultLogger()\n }\n }\n\n isStarted (): boolean {\n return this._started\n }\n\n private async _invokeStartableMethod (methodName: 'beforeStart' | 'start' | 'afterStart' | 'beforeStop' | 'stop' | 'afterStop'): Promise<void> {\n await Promise.all(\n Object.values(this.components)\n .filter(obj => isStartable(obj))\n .map(async (startable: Startable) => {\n await startable[methodName]?.()\n })\n )\n }\n\n async beforeStart (): Promise<void> {\n await this._invokeStartableMethod('beforeStart')\n }\n\n async start (): Promise<void> {\n await this._invokeStartableMethod('start')\n this._started = true\n }\n\n async afterStart (): Promise<void> {\n await this._invokeStartableMethod('afterStart')\n }\n\n async beforeStop (): Promise<void> {\n await this._invokeStartableMethod('beforeStop')\n }\n\n async stop (): Promise<void> {\n await this._invokeStartableMethod('stop')\n this._started = false\n }\n\n async afterStop (): Promise<void> {\n await this._invokeStartableMethod('afterStop')\n }\n}\n\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n]\n\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n]\n\nexport function defaultComponents (init: ComponentsInit = {}): Components {\n const components = new DefaultComponents(init)\n\n const proxy = new Proxy(components, {\n get (target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop]\n\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new MissingServiceError(`${prop} not set`)\n }\n\n return service\n }\n\n return Reflect.get(target, prop, receiver)\n },\n\n set (target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value\n } else {\n Reflect.set(target, prop, value)\n }\n\n return true\n }\n })\n\n // @ts-expect-error component keys are proxied\n return proxy\n}\n\nexport function checkServiceDependencies (components: Components): void {\n const serviceCapabilities: Record<string, ConstrainBoolean> = {}\n\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceCapabilities(service)) {\n serviceCapabilities[capability] = true\n }\n }\n\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceDependencies(service)) {\n if (serviceCapabilities[capability] !== true) {\n throw new UnmetServiceDependenciesError(`Service \"${getServiceName(service)}\" required capability \"${capability}\" but it was not provided by any component, you may need to add additional configuration when creating your node.`)\n }\n }\n }\n}\n\nfunction getServiceCapabilities (service: any): string[] {\n if (Array.isArray(service?.[serviceCapabilities])) {\n return service[serviceCapabilities]\n }\n\n return []\n}\n\nfunction getServiceDependencies (service: any): string[] {\n if (Array.isArray(service?.[serviceDependencies])) {\n return service[serviceDependencies]\n }\n\n return []\n}\n\nfunction getServiceName (service: any): string {\n return service?.[Symbol.toStringTag] ?? service?.toString() ?? 'unknown'\n}\n", "import { isPrivateIp } from '@libp2p/utils/private-ip'\nimport { WebSockets } from '@multiformats/multiaddr-matcher'\nimport type { ConnectionGater } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst CODEC_IP4 = 0x04\nconst CODEC_IP6 = 0x29\n\n/**\n * Returns a connection gater that disallows dialling private addresses or\n * insecure websockets by default.\n *\n * Browsers are severely limited in their resource usage so don't waste time\n * trying to dial undialable addresses, and they also print verbose error\n * messages when making connections over insecure transports which causes\n * confusion.\n */\nexport function connectionGater (gater: ConnectionGater = {}): ConnectionGater {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr: Multiaddr) => {\n // do not connect to insecure websockets by default\n if (WebSockets.matches(multiaddr)) {\n return false\n }\n\n const tuples = multiaddr.stringTuples()\n\n // do not connect to private addresses by default\n if (tuples[0][0] === CODEC_IP4 || tuples[0][0] === CODEC_IP6) {\n return Boolean(isPrivateIp(`${tuples[0][1]}`))\n }\n\n return false\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n }\n}\n", "// From https://github.com/sindresorhus/random-int/blob/c37741b56f76b9160b0b63dae4e9c64875128146/index.js#L13-L15\nconst randomInteger = (minimum, maximum) => Math.floor((Math.random() * (maximum - minimum + 1)) + minimum);\n\nconst createAbortError = () => {\n\tconst error = new Error('Delay aborted');\n\terror.name = 'AbortError';\n\treturn error;\n};\n\nconst clearMethods = new WeakMap();\n\nexport function createDelay({clearTimeout: defaultClear, setTimeout: defaultSet} = {}) {\n\t// We cannot use `async` here as we need the promise identity.\n\treturn (milliseconds, {value, signal} = {}) => {\n\t\t// TODO: Use `signal?.throwIfAborted()` when targeting Node.js 18.\n\t\tif (signal?.aborted) {\n\t\t\treturn Promise.reject(createAbortError());\n\t\t}\n\n\t\tlet timeoutId;\n\t\tlet settle;\n\t\tlet rejectFunction;\n\t\tconst clear = defaultClear ?? clearTimeout;\n\n\t\tconst signalListener = () => {\n\t\t\tclear(timeoutId);\n\t\t\trejectFunction(createAbortError());\n\t\t};\n\n\t\tconst cleanup = () => {\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t\t}\n\t\t};\n\n\t\tconst delayPromise = new Promise((resolve, reject) => {\n\t\t\tsettle = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t};\n\n\t\t\trejectFunction = reject;\n\t\t\ttimeoutId = (defaultSet ?? setTimeout)(settle, milliseconds);\n\t\t});\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t\t}\n\n\t\tclearMethods.set(delayPromise, () => {\n\t\t\tclear(timeoutId);\n\t\t\ttimeoutId = null;\n\t\t\tsettle();\n\t\t});\n\n\t\treturn delayPromise;\n\t};\n}\n\nconst delay = createDelay();\n\nexport default delay;\n\nexport async function rangeDelay(minimum, maximum, options = {}) {\n\treturn delay(randomInteger(minimum, maximum), options);\n}\n\nexport function clearDelay(promise) {\n\tclearMethods.get(promise)?.();\n}\n", "import type { RateLimiterResult } from './rate-limiter.js'\n\n/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n\n constructor (message = 'Rate limit exceeded', props: RateLimiterResult) {\n super(message)\n this.name = 'RateLimitError'\n this.remainingPoints = props.remainingPoints\n this.msBeforeNext = props.msBeforeNext\n this.consumedPoints = props.consumedPoints\n this.isFirstInDuration = props.isFirstInDuration\n }\n}\n\nexport class QueueFullError extends Error {\n static name = 'QueueFullError'\n\n constructor (message: string = 'The queue was full') {\n super(message)\n this.name = 'QueueFullError'\n }\n}\n", "import delay from 'delay'\nimport { RateLimitError } from './errors.js'\n\nexport interface RateLimiterInit {\n /**\n * Number of points\n *\n * @default 4\n */\n points?: number\n\n /**\n * Per seconds\n *\n * @default 1\n */\n duration?: number\n\n /**\n * Block if consumed more than points in current duration for blockDuration seconds\n *\n * @default 0\n */\n blockDuration?: number\n\n /**\n * Execute allowed actions evenly over duration\n *\n * @default false\n */\n execEvenly?: boolean\n\n /**\n * ms, works with execEvenly=true option\n *\n * @default duration * 1000 / points\n */\n execEvenlyMinDelayMs?: number\n\n /**\n * @default \"rlflx\"\n */\n keyPrefix?: string\n}\n\nexport interface GetKeySecDurationOptions {\n customDuration?: number\n}\n\nexport interface RateLimiterResult {\n remainingPoints: number\n msBeforeNext: number\n consumedPoints: number\n isFirstInDuration: boolean\n}\n\nexport interface RateRecord {\n value: number\n expiresAt?: Date\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nexport class RateLimiter {\n public readonly memoryStorage: MemoryStorage\n protected points: number\n protected duration: number\n protected blockDuration: number\n protected execEvenly: boolean\n protected execEvenlyMinDelayMs: number\n protected keyPrefix: string\n\n constructor (opts: RateLimiterInit = {}) {\n this.points = opts.points ?? 4\n this.duration = opts.duration ?? 1\n this.blockDuration = opts.blockDuration ?? 0\n this.execEvenly = opts.execEvenly ?? false\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points)\n this.keyPrefix = opts.keyPrefix ?? 'rlflx'\n this.memoryStorage = new MemoryStorage()\n }\n\n async consume (key: string, pointsToConsume: number = 1, options: GetKeySecDurationOptions = {}): Promise<RateLimiterResult> {\n const rlKey = this.getKey(key)\n const secDuration = this._getKeySecDuration(options)\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration)\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration)\n }\n\n throw new RateLimitError('Rate limit exceeded', res)\n } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2))\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs\n }\n\n await delay(delayMs)\n }\n\n return res\n }\n\n penalty (key: string, points: number = 1, options: GetKeySecDurationOptions = {}): RateLimiterResult {\n const rlKey = this.getKey(key)\n const secDuration = this._getKeySecDuration(options)\n const res = this.memoryStorage.incrby(rlKey, points, secDuration)\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n\n return res\n }\n\n reward (key: string, points: number = 1, options: GetKeySecDurationOptions = {}): RateLimiterResult {\n const rlKey = this.getKey(key)\n const secDuration = this._getKeySecDuration(options)\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration)\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n\n return res\n }\n\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block (key: string, secDuration: number): RateLimiterResult {\n const msDuration = secDuration * 1000\n const initPoints = this.points + 1\n\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration)\n\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n }\n }\n\n set (key: string, points: number, secDuration: number = 0): RateLimiterResult {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000\n\n this.memoryStorage.set(this.getKey(key), points, secDuration)\n\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n }\n }\n\n get (key: string): RateLimiterResult | undefined {\n const res = this.memoryStorage.get(this.getKey(key))\n\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0)\n }\n\n return res\n }\n\n delete (key: string): void {\n this.memoryStorage.delete(this.getKey(key))\n }\n\n private _getKeySecDuration (options?: GetKeySecDurationOptions): number {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration\n }\n\n return this.duration\n }\n\n getKey (key: string): string {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key\n }\n\n parseKey (rlKey: string): string {\n return rlKey.substring(this.keyPrefix.length)\n }\n}\n\nexport class MemoryStorage {\n public readonly storage: Map<string, RateRecord>\n\n constructor () {\n this.storage = new Map()\n }\n\n incrby (key: string, value: number, durationSec: number): RateLimiterResult {\n const existing = this.storage.get(key)\n\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1\n\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value\n\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n }\n }\n\n return this.set(key, value, durationSec)\n }\n\n return this.set(key, value, durationSec)\n }\n\n set (key: string, value: number, durationSec: number): RateLimiterResult {\n const durationMs = durationSec * 1000\n const existing = this.storage.get(key)\n\n if (existing != null) {\n clearTimeout(existing.timeoutId)\n }\n\n const record: RateRecord = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n }\n\n this.storage.set(key, record)\n\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key)\n }, durationMs)\n\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref()\n }\n }\n\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n }\n }\n\n get (key: string): RateLimiterResult | undefined {\n const existing = this.storage.get(key)\n\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n }\n }\n }\n\n delete (key: string): boolean {\n const record = this.storage.get(key)\n\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId)\n }\n\n this.storage.delete(key)\n\n return true\n }\n return false\n }\n}\n", "import { InvalidMultiaddrError, InvalidParametersError, isPeerId } from '@libp2p/interface'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { isMultiaddr } from '@multiformats/multiaddr'\nimport { PEER_ID } from '@multiformats/multiaddr-matcher'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface PeerAddress {\n peerId?: PeerId\n multiaddrs: Multiaddr[]\n}\n\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an\n * array of Multiaddrs\n */\nexport function getPeerAddress (peer: PeerId | Multiaddr | Multiaddr[]): PeerAddress {\n if (isPeerId(peer)) {\n return { peerId: peer, multiaddrs: [] }\n }\n\n let multiaddrs = Array.isArray(peer) ? peer : [peer]\n\n let peerId: PeerId | undefined\n\n if (multiaddrs.length > 0) {\n const peerIdStr = multiaddrs[0].getPeerId()\n peerId = peerIdStr == null ? undefined : peerIdFromString(peerIdStr)\n\n // ensure PeerId is either not set or is consistent\n multiaddrs.forEach(ma => {\n if (!isMultiaddr(ma)) {\n throw new InvalidMultiaddrError('Invalid multiaddr')\n }\n\n const maPeerIdStr = ma.getPeerId()\n\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new InvalidParametersError('Multiaddrs must all have the same peer id or have no peer id')\n }\n } else {\n const maPeerId = peerIdFromString(maPeerIdStr)\n\n if (peerId?.equals(maPeerId) !== true) {\n throw new InvalidParametersError('Multiaddrs must all have the same peer id or have no peer id')\n }\n }\n })\n }\n\n // ignore any `/p2p/Qmfoo`-style addresses as we will include the peer id in\n // the returned value of this function\n multiaddrs = multiaddrs.filter(ma => {\n return !PEER_ID.exactMatch(ma)\n })\n\n return {\n peerId,\n multiaddrs\n }\n}\n", "import type { Connection, Stream, AbortOptions } from '@libp2p/interface'\n\n/**\n * Close the passed stream, falling back to aborting the stream if closing\n * cleanly fails.\n */\nexport async function safelyCloseStream (stream?: Stream, options?: AbortOptions): Promise<void> {\n try {\n await stream?.close(options)\n } catch (err: any) {\n stream?.abort(err)\n }\n}\n\n/**\n * These are speculative protocols that are run automatically on connection open\n * so are usually not the reason the connection was opened.\n *\n * Consequently when requested it should be safe to close connections that only\n * have these protocol streams open.\n */\nconst DEFAULT_CLOSABLE_PROTOCOLS = [\n // identify\n '/ipfs/id/1.0.0',\n\n // identify-push\n '/ipfs/id/push/1.0.0',\n\n // autonat\n '/libp2p/autonat/1.0.0',\n\n // dcutr\n '/libp2p/dcutr'\n]\n\nexport interface SafelyCloseConnectionOptions extends AbortOptions {\n /**\n * Only close the stream if it either has no protocol streams open or only\n * ones in this list.\n *\n * @default ['/ipfs/id/1.0.0']\n */\n closableProtocols?: string[]\n}\n\n/**\n * Close the passed connection if it has no streams, or only closable protocol\n * streams, falling back to aborting the connection if closing it cleanly fails.\n */\nexport async function safelyCloseConnectionIfUnused (connection?: Connection, options?: SafelyCloseConnectionOptions): Promise<void> {\n const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? []\n const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS\n\n // if the connection has protocols not in the closable protocols list, do not\n // close the connection\n if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) {\n return\n }\n\n try {\n await connection?.close(options)\n } catch (err: any) {\n connection?.abort(err)\n }\n}\n", "/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#dialTimeout\n */\nexport const DIAL_TIMEOUT = 10_000\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundUpgradeTimeout\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 10_000\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#protocolNegotiationTimeout\n */\nexport const PROTOCOL_NEGOTIATION_TIMEOUT = 10_000\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxPeerAddrsToDial\n */\nexport const MAX_PEER_ADDRS_TO_DIAL = 25\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundConnectionThreshold\n */\nexport const INBOUND_CONNECTION_THRESHOLD = 5\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxIncomingPendingConnections\n */\nexport const MAX_INCOMING_PENDING_CONNECTIONS = 10\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelReconnects\n */\nexport const MAX_PARALLEL_RECONNECTS = 5\n\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempt failed with the timestamp\n * stored as a string.\n *\n * Used to insure we do not endlessly try to auto dial peers we have recently\n * failed to dial.\n */\nexport const LAST_DIAL_FAILURE_KEY = 'last-dial-failure'\n\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempt succeeded with the\n * timestamp stored as a string.\n */\nexport const LAST_DIAL_SUCCESS_KEY = 'last-dial-success'\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxDialQueueLength\n */\nexport const MAX_DIAL_QUEUE_LENGTH = 500\n", "export * from './constants.defaults.js'\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections\n */\nexport const MAX_CONNECTIONS = 100\n\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials\n */\nexport const MAX_PARALLEL_DIALS = 50\n", "import { multiaddr, resolvers, type Multiaddr, type ResolveOptions } from '@multiformats/multiaddr'\nimport { convertToIpNet } from '@multiformats/multiaddr/convert'\nimport type { IpNet } from '@chainsafe/netmask'\nimport type { LoggerOptions } from '@libp2p/interface'\n\n/**\n * Recursively resolve DNSADDR multiaddrs\n */\nexport async function resolveMultiaddrs (ma: Multiaddr, options: ResolveOptions & LoggerOptions): Promise<Multiaddr[]> {\n // check multiaddr resolvers\n let resolvable = false\n\n for (const key of resolvers.keys()) {\n resolvable = ma.protoNames().includes(key)\n\n if (resolvable) {\n break\n }\n }\n\n // return multiaddr if it is not resolvable\n if (!resolvable) {\n return [ma]\n }\n\n const output = await ma.resolve(options)\n\n options.log('resolved %s to', ma, output.map(ma => ma.toString()))\n\n return output\n}\n\n/**\n * Converts a multiaddr string or object to an IpNet object.\n * If the multiaddr doesn't include /ipcidr, it will encapsulate with the appropriate CIDR:\n * - /ipcidr/32 for IPv4\n * - /ipcidr/128 for IPv6\n *\n * @param {string | Multiaddr} ma - The multiaddr string or object to convert.\n * @returns {IpNet} The converted IpNet object.\n * @throws {Error} Throws an error if the multiaddr is not valid.\n */\nexport function multiaddrToIpNet (ma: string | Multiaddr): IpNet {\n try {\n let parsedMa: Multiaddr\n if (typeof ma === 'string') {\n parsedMa = multiaddr(ma)\n } else {\n parsedMa = ma\n }\n\n // Check if /ipcidr is already present\n if (!parsedMa.protoNames().includes('ipcidr')) {\n const isIPv6 = parsedMa.protoNames().includes('ip6')\n const cidr = isIPv6 ? '/ipcidr/128' : '/ipcidr/32'\n parsedMa = parsedMa.encapsulate(cidr)\n }\n\n return convertToIpNet(parsedMa)\n } catch (error) {\n throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${ma}`)\n }\n}\n", "import { PeerMap } from '@libp2p/peer-collections'\nimport { safelyCloseConnectionIfUnused } from '@libp2p/utils/close'\nimport { MAX_CONNECTIONS } from './constants.js'\nimport { multiaddrToIpNet } from './utils.js'\nimport type { IpNet } from '@chainsafe/netmask'\nimport type { Libp2pEvents, Logger, ComponentLogger, TypedEventTarget, PeerStore, Connection } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\ninterface ConnectionPrunerInit {\n maxConnections?: number\n allow?: Multiaddr[]\n}\n\ninterface ConnectionPrunerComponents {\n connectionManager: ConnectionManager\n peerStore: PeerStore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n allow: []\n}\n\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nexport class ConnectionPruner {\n private readonly maxConnections: number\n private readonly connectionManager: ConnectionManager\n private readonly peerStore: PeerStore\n private readonly allow: IpNet[]\n private readonly events: TypedEventTarget<Libp2pEvents>\n private readonly log: Logger\n\n constructor (components: ConnectionPrunerComponents, init: ConnectionPrunerInit = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections\n this.allow = (init.allow ?? []).map(ma => multiaddrToIpNet(ma))\n this.connectionManager = components.connectionManager\n this.peerStore = components.peerStore\n this.events = components.events\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner')\n this.maybePruneConnections = this.maybePruneConnections.bind(this)\n }\n\n start (): void {\n this.events.addEventListener('connection:open', this.maybePruneConnections)\n }\n\n stop (): void {\n this.events.removeEventListener('connection:open', this.maybePruneConnections)\n }\n\n maybePruneConnections (): void {\n this._maybePruneConnections()\n .catch(err => {\n this.log.error('error while pruning connections %e', err)\n })\n }\n\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n private async _maybePruneConnections (): Promise<void> {\n const connections = this.connectionManager.getConnections()\n const numConnections = connections.length\n\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections)\n\n if (numConnections <= this.maxConnections) {\n return\n }\n\n const peerValues = new PeerMap<number>()\n\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer\n\n if (peerValues.has(remotePeer)) {\n continue\n }\n\n peerValues.set(remotePeer, 0)\n\n try {\n const peer = await this.peerStore.get(remotePeer)\n\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value\n }, 0))\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n this.log.error('error loading peer tags', err)\n }\n }\n }\n\n const sortedConnections = this.sortConnections(connections, peerValues)\n\n // close some connections\n const toPrune = Math.max(numConnections - this.maxConnections, 0)\n const toClose = []\n\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer)\n // check allow list\n const connectionInAllowList = this.allow.some((ipNet) => {\n return ipNet.contains(connection.remoteAddr.nodeAddress().address)\n })\n\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection)\n }\n\n if (toClose.length === toPrune) {\n break\n }\n }\n\n // close connections\n await Promise.all(\n toClose.map(async connection => {\n await safelyCloseConnectionIfUnused(connection, {\n signal: AbortSignal.timeout(1000)\n })\n })\n )\n\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose })\n }\n\n sortConnections (connections: Connection[], peerValues: PeerMap<number>): Connection[] {\n return connections\n // sort by connection age, newest to oldest\n .sort((a, b) => {\n const connectionALifespan = a.timeline.open\n const connectionBLifespan = b.timeline.open\n\n if (connectionALifespan < connectionBLifespan) {\n return 1\n }\n\n if (connectionALifespan > connectionBLifespan) {\n return -1\n }\n\n return 0\n })\n // sort by direction, incoming first then outgoing\n .sort((a, b) => {\n if (a.direction === 'outbound' && b.direction === 'inbound') {\n return 1\n }\n\n if (a.direction === 'inbound' && b.direction === 'outbound') {\n return -1\n }\n\n return 0\n })\n // sort by number of streams, lowest to highest\n .sort((a, b) => {\n if (a.streams.length > b.streams.length) {\n return 1\n }\n\n if (a.streams.length < b.streams.length) {\n return -1\n }\n\n return 0\n })\n // sort by tag value, lowest to highest\n .sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0\n const peerBValue = peerValues.get(b.remotePeer) ?? 0\n\n if (peerAValue > peerBValue) {\n return 1\n }\n\n if (peerAValue < peerBValue) {\n return -1\n }\n\n return 0\n })\n }\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "// ported from https://www.npmjs.com/package/fast-fifo\n\nexport interface Next<T> {\n done?: boolean\n error?: Error\n value?: T\n}\n\nclass FixedFIFO<T> {\n public buffer: Array<Next<T> | undefined>\n private readonly mask: number\n private top: number\n private btm: number\n public next: FixedFIFO<T> | null\n\n constructor (hwm: number) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two')\n }\n\n this.buffer = new Array(hwm)\n this.mask = hwm - 1\n this.top = 0\n this.btm = 0\n this.next = null\n }\n\n push (data: Next<T>): boolean {\n if (this.buffer[this.top] !== undefined) {\n return false\n }\n\n this.buffer[this.top] = data\n this.top = (this.top + 1) & this.mask\n\n return true\n }\n\n shift (): Next<T> | undefined {\n const last = this.buffer[this.btm]\n\n if (last === undefined) {\n return undefined\n }\n\n this.buffer[this.btm] = undefined\n this.btm = (this.btm + 1) & this.mask\n return last\n }\n\n isEmpty (): boolean {\n return this.buffer[this.btm] === undefined\n }\n}\n\nexport interface FIFOOptions {\n /**\n * When the queue reaches this size, it will be split into head/tail parts\n */\n splitLimit?: number\n}\n\nexport class FIFO<T> {\n public size: number\n private readonly hwm: number\n private head: FixedFIFO<T>\n private tail: FixedFIFO<T>\n\n constructor (options: FIFOOptions = {}) {\n this.hwm = options.splitLimit ?? 16\n this.head = new FixedFIFO<T>(this.hwm)\n this.tail = this.head\n this.size = 0\n }\n\n calculateSize (obj: any): number {\n if (obj?.byteLength != null) {\n return obj.byteLength\n }\n\n return 1\n }\n\n push (val: Next<T>): void {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value)\n }\n\n if (!this.head.push(val)) {\n const prev = this.head\n this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)\n this.head.push(val)\n }\n }\n\n shift (): Next<T> | undefined {\n let val = this.tail.shift()\n\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next\n this.tail.next = null\n this.tail = next\n val = this.tail.shift()\n }\n\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value)\n }\n\n return val\n }\n\n isEmpty (): boolean {\n return this.head.isEmpty()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { FIFO, type Next } from './fifo.js'\n\nexport class AbortError extends Error {\n type: string\n code: string\n\n constructor (message?: string, code?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\ninterface BasePushable<T> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error): this\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T): this\n\n /**\n * Returns a promise that resolves when the underlying queue becomes empty (e.g.\n * this.readableLength === 0).\n *\n * If an AbortSignal is passed as an option and that signal aborts, it only\n * causes the returned promise to reject - it does not end the pushable.\n */\n onEmpty(options?: AbortOptions): Promise<void>\n\n /**\n * This property contains the number of bytes (or objects) in the queue ready to be read.\n *\n * If `objectMode` is true, this is the number of objects in the queue, if false it's the\n * total number of bytes in the queue.\n */\n readableLength: number\n}\n\n/**\n * An iterable that you can push values into.\n */\nexport interface Pushable<T, R = void, N = unknown> extends AsyncGenerator<T, R, N>, BasePushable<T> {}\n\n/**\n * Similar to `pushable`, except it yields multiple buffered chunks at a time. All values yielded from the iterable will be arrays.\n */\nexport interface PushableV<T, R = void, N = unknown> extends AsyncGenerator<T[], R, N>, BasePushable<T> {}\n\nexport interface Options {\n /**\n * A boolean value that means non-`Uint8Array`s will be passed to `.push`, default: `false`\n */\n objectMode?: boolean\n\n /**\n * A function called after *all* values have been yielded from the iterator (including\n * buffered values). In the case when the iterator is ended with an error it will be\n * passed the error as a parameter.\n */\n onEnd?(err?: Error): void\n}\n\nexport interface DoneResult { done: true }\nexport interface ValueResult<T> { done: false, value: T }\nexport type NextResult<T> = ValueResult<T> | DoneResult\n\ninterface getNext<T, V = T> { (buffer: FIFO<T>): NextResult<V> }\n\nexport interface ObjectPushableOptions extends Options {\n objectMode: true\n}\n\nexport interface BytePushableOptions extends Options {\n objectMode?: false\n}\n\n/**\n * Create a new async iterable. The values yielded from calls to `.next()`\n * or when used in a `for await of`loop are \"pushed\" into the iterable.\n * Returns an async iterable object with additional methods.\n */\nexport function pushable<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): Pushable<T>\nexport function pushable<T> (options: ObjectPushableOptions): Pushable<T>\nexport function pushable<T> (options: Options = {}): Pushable<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T> => {\n const next: Next<T> | undefined = buffer.shift()\n\n if (next == null) {\n return { done: true }\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n }\n }\n\n return _pushable<T, T, Pushable<T>>(getNext, options)\n}\n\nexport function pushableV<T extends { byteLength: number } = Uint8Array> (options?: BytePushableOptions): PushableV<T>\nexport function pushableV<T> (options: ObjectPushableOptions): PushableV<T>\nexport function pushableV<T> (options: Options = {}): PushableV<T> {\n const getNext = (buffer: FIFO<T>): NextResult<T[]> => {\n let next: Next<T> | undefined\n const values: T[] = []\n\n while (!buffer.isEmpty()) {\n next = buffer.shift()\n\n if (next == null) {\n break\n }\n\n if (next.error != null) {\n throw next.error\n }\n\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value)\n }\n }\n\n if (next == null) {\n return { done: true }\n }\n\n return {\n done: next.done === true,\n value: values\n }\n }\n\n return _pushable<T, T[], PushableV<T>>(getNext, options)\n}\n\nfunction _pushable<PushType, ValueType, ReturnType> (getNext: getNext<PushType, ValueType>, options?: Options): ReturnType {\n options = options ?? {}\n let onEnd = options.onEnd\n let buffer = new FIFO<PushType>()\n let pushable: any\n let onNext: ((next: Next<PushType>) => ReturnType) | null\n let ended: boolean\n let drain = deferred()\n\n const waitNext = async (): Promise<NextResult<ValueType>> => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer)\n }\n\n if (ended) {\n return { done: true }\n }\n\n return await new Promise<NextResult<ValueType>>((resolve, reject) => {\n onNext = (next: Next<PushType>) => {\n onNext = null\n buffer.push(next)\n\n try {\n resolve(getNext(buffer))\n } catch (err) {\n reject(err)\n }\n\n return pushable\n }\n })\n } finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve()\n drain = deferred()\n })\n }\n }\n }\n\n const bufferNext = (next: Next<PushType>): ReturnType => {\n if (onNext != null) {\n return onNext(next)\n }\n\n buffer.push(next)\n return pushable\n }\n\n const bufferError = (err: Error): ReturnType => {\n buffer = new FIFO()\n\n if (onNext != null) {\n return onNext({ error: err })\n }\n\n buffer.push({ error: err })\n return pushable\n }\n\n const push = (value: PushType): ReturnType => {\n if (ended) {\n return pushable\n }\n\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value')\n }\n\n return bufferNext({ done: false, value })\n }\n const end = (err?: Error): ReturnType => {\n if (ended) return pushable\n ended = true\n\n return (err != null) ? bufferError(err) : bufferNext({ done: true })\n }\n const _return = (): DoneResult => {\n buffer = new FIFO()\n end()\n\n return { done: true }\n }\n const _throw = (err: Error): DoneResult => {\n end(err)\n\n return { done: true }\n }\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength (): number {\n return buffer.size\n },\n onEmpty: async (options?: AbortOptions) => {\n const signal = options?.signal\n signal?.throwIfAborted()\n\n if (buffer.isEmpty()) {\n return\n }\n\n let cancel: Promise<void> | undefined\n let listener: (() => void) | undefined\n\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError())\n }\n\n signal.addEventListener('abort', listener)\n })\n }\n\n try {\n await Promise.race([\n drain.promise,\n cancel\n ])\n } finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener)\n }\n }\n }\n }\n\n if (onEnd == null) {\n return pushable\n }\n\n const _pushable = pushable\n\n pushable = {\n [Symbol.asyncIterator] () { return this },\n next () {\n return _pushable.next()\n },\n throw (err: Error) {\n _pushable.throw(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return { done: true }\n },\n return () {\n _pushable.return()\n\n if (onEnd != null) {\n onEnd()\n onEnd = undefined\n }\n\n return { done: true }\n },\n push,\n end (err: Error) {\n _pushable.end(err)\n\n if (onEnd != null) {\n onEnd(err)\n onEnd = undefined\n }\n\n return pushable\n },\n get readableLength () {\n return _pushable.readableLength\n },\n onEmpty: (opts?: AbortOptions) => {\n return _pushable.onEmpty(opts)\n }\n }\n\n return pushable\n}\n", "/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\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) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RaceEventOptions<T> {\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 of an event emitted on the emitter that should cause the returned\n * promise to reject. The rejection reason will be the `.detail` field of the\n * event.\n */\n errorEvent?: string\n\n /**\n * When multiple events with the same name may be emitted, pass a filter\n * function here to allow ignoring ones that should not cause the returned\n * promise to resolve.\n */\n filter?(evt: T): boolean\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent <T> (emitter: EventTarget, eventName: string, signal?: AbortSignal, opts?: RaceEventOptions<T>): Promise<T> {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode)\n\n if (signal?.aborted === true) {\n return Promise.reject(error)\n }\n\n return new Promise((resolve, reject) => {\n function removeListeners (): void {\n signal?.removeEventListener('abort', abortListener)\n emitter.removeEventListener(eventName, eventListener)\n\n if (opts?.errorEvent != null) {\n emitter.removeEventListener(opts.errorEvent, errorEventListener)\n }\n }\n\n const eventListener = (evt: any): void => {\n try {\n if (opts?.filter?.(evt) === false) {\n return\n }\n } catch (err: any) {\n removeListeners()\n reject(err)\n return\n }\n\n removeListeners()\n resolve(evt)\n }\n\n const errorEventListener = (evt: any): void => {\n removeListeners()\n reject(evt.detail)\n }\n\n const abortListener = (): void => {\n removeListeners()\n reject(error)\n }\n\n signal?.addEventListener('abort', abortListener)\n emitter.addEventListener(eventName, eventListener)\n\n if (opts?.errorEvent != null) {\n emitter.addEventListener(opts.errorEvent, errorEventListener)\n }\n })\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", "import { AbortError } from '@libp2p/interface'\nimport pDefer from 'p-defer'\nimport type { DeferredPromise } from 'p-defer'\n\nexport class JobRecipient<JobReturnType> {\n public deferred: DeferredPromise<JobReturnType>\n public signal?: AbortSignal\n\n constructor (signal?: AbortSignal) {\n this.signal = signal\n this.deferred = pDefer()\n\n this.onAbort = this.onAbort.bind(this)\n this.signal?.addEventListener('abort', this.onAbort)\n }\n\n onAbort (): void {\n this.deferred.reject(this.signal?.reason ?? new AbortError())\n }\n\n cleanup (): void {\n this.signal?.removeEventListener('abort', this.onAbort)\n }\n}\n", "import { AbortError, setMaxListeners } from '@libp2p/interface'\nimport { raceSignal } from 'race-signal'\nimport { JobRecipient } from './recipient.js'\nimport type { JobStatus } from './index.js'\nimport type { AbortOptions } from '@libp2p/interface'\n\n/**\n * Returns a random string\n */\nfunction randomId (): string {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`\n}\n\nexport interface JobTimeline {\n created: number\n started?: number\n finished?: number\n}\n\nexport class Job <JobOptions extends AbortOptions = AbortOptions, JobReturnType = unknown> {\n public id: string\n public fn: (options: JobOptions) => Promise<JobReturnType>\n public options: JobOptions\n public recipients: Array<JobRecipient<JobReturnType>>\n public status: JobStatus\n public readonly timeline: JobTimeline\n private readonly controller: AbortController\n\n constructor (fn: (options: JobOptions) => Promise<JobReturnType>, options: any) {\n this.id = randomId()\n this.status = 'queued'\n this.fn = fn\n this.options = options\n this.recipients = []\n this.timeline = {\n created: Date.now()\n }\n\n this.controller = new AbortController()\n setMaxListeners(Infinity, this.controller.signal)\n\n this.onAbort = this.onAbort.bind(this)\n }\n\n abort (err: Error): void {\n this.controller.abort(err)\n }\n\n onAbort (): void {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true)\n }, true)\n\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError())\n this.cleanup()\n }\n }\n\n async join (options: AbortOptions = {}): Promise<JobReturnType> {\n const recipient = new JobRecipient<JobReturnType>(options.signal)\n this.recipients.push(recipient)\n\n options.signal?.addEventListener('abort', this.onAbort)\n\n return recipient.deferred.promise\n }\n\n async run (): Promise<void> {\n this.status = 'running'\n this.timeline.started = Date.now()\n\n try {\n this.controller.signal.throwIfAborted()\n\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal)\n\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result)\n })\n\n this.status = 'complete'\n } catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err)\n })\n\n this.status = 'errored'\n } finally {\n this.timeline.finished = Date.now()\n this.cleanup()\n }\n }\n\n cleanup (): void {\n this.recipients.forEach(recipient => {\n recipient.cleanup()\n recipient.signal?.removeEventListener('abort', this.onAbort)\n })\n }\n}\n", "import { AbortError, TypedEventEmitter } from '@libp2p/interface'\nimport { pushable } from 'it-pushable'\nimport { raceEvent } from 'race-event'\nimport { debounce } from '../debounce.js'\nimport { QueueFullError } from '../errors.js'\nimport { Job } from './job.js'\nimport type { AbortOptions, Metrics } from '@libp2p/interface'\n\nexport type { Job, JobTimeline } from './job.js'\nexport type { JobRecipient } from './recipient.js'\n\nexport interface Comparator<T> {\n (a: T, b: T): -1 | 0 | 1\n}\n\nexport interface QueueInit<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * Concurrency limit.\n *\n * Minimum: `1`.\n *\n * @default Infinity\n */\n concurrency?: number\n\n /**\n * If the queue size grows to larger than this number the promise returned\n * from the add function will reject\n *\n * @default Infinity\n */\n maxSize?: number\n\n /**\n * The name of the metric for the queue length\n */\n metricName?: string\n\n /**\n * An implementation of the libp2p Metrics interface\n */\n metrics?: Metrics\n\n /**\n * An optional function that will sort the queue after a job has been added\n */\n sort?: Comparator<Job<JobOptions, JobReturnType>>\n}\n\nexport type JobStatus = 'queued' | 'running' | 'errored' | 'complete'\n\nexport interface RunFunction<Options extends AbortOptions = AbortOptions, ReturnType = void> {\n (options: Options): Promise<ReturnType>\n}\n\nexport interface JobMatcher<JobOptions extends AbortOptions = AbortOptions> {\n (options?: Partial<JobOptions>): boolean\n}\n\nexport interface QueueJobSuccess<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n result: JobReturnType\n}\n\nexport interface QueueJobFailure<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n job: Job<JobOptions, JobReturnType>\n error: Error\n}\n\nexport interface QueueEvents<JobReturnType, JobOptions extends AbortOptions = AbortOptions> {\n /**\n * A job is about to start running\n */\n 'active': CustomEvent\n\n /**\n * All jobs have finished and the queue is empty\n */\n 'idle': CustomEvent\n\n /**\n * The queue is empty, jobs may be running\n */\n 'empty': CustomEvent\n\n /**\n * A job was added to the queue\n */\n 'add': CustomEvent\n\n /**\n * A job has finished or failed\n */\n 'next': CustomEvent\n\n /**\n * A job has finished successfully\n */\n 'completed': CustomEvent<JobReturnType>\n\n /**\n * A job has failed\n */\n 'error': CustomEvent<Error>\n\n /**\n * Emitted just after `\"completed\", a job has finished successfully - this\n * event gives access to the job and it's result\n */\n 'success': CustomEvent<QueueJobSuccess<JobReturnType, JobOptions>>\n\n /**\n * Emitted just after `\"error\", a job has failed - this event gives access to\n * the job and the thrown error\n */\n 'failure': CustomEvent<QueueJobFailure<JobReturnType, JobOptions>>\n}\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue<JobReturnType = unknown, JobOptions extends AbortOptions = AbortOptions> extends TypedEventEmitter<QueueEvents<JobReturnType, JobOptions>> {\n public concurrency: number\n public maxSize: number\n public queue: Array<Job<JobOptions, JobReturnType>>\n private pending: number\n private readonly sort?: Comparator<Job<JobOptions, JobReturnType>>\n\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super()\n\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY\n this.pending = 0\n\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n }\n }\n })\n }\n\n this.sort = init.sort\n this.queue = []\n\n this.emitEmpty = debounce(this.emitEmpty.bind(this), 1)\n this.emitIdle = debounce(this.emitIdle.bind(this), 1)\n }\n\n emitEmpty (): void {\n if (this.size !== 0) {\n return\n }\n\n this.safeDispatchEvent('empty')\n }\n\n emitIdle (): void {\n if (this.running !== 0) {\n return\n }\n\n this.safeDispatchEvent('idle')\n }\n\n private tryToStartAnother (): boolean {\n if (this.size === 0) {\n this.emitEmpty()\n\n if (this.running === 0) {\n this.emitIdle()\n }\n\n return false\n }\n\n if (this.pending < this.concurrency) {\n let job: Job<JobOptions, JobReturnType> | undefined\n\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j\n break\n }\n }\n\n if (job == null) {\n return false\n }\n\n this.safeDispatchEvent('active')\n\n this.pending++\n\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n\n this.pending--\n this.tryToStartAnother()\n this.safeDispatchEvent('next')\n })\n\n return true\n }\n\n return false\n }\n\n private enqueue (job: Job<JobOptions, JobReturnType>): void {\n this.queue.push(job)\n\n if (this.sort != null) {\n this.queue.sort(this.sort)\n }\n }\n\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add (fn: RunFunction<JobOptions, JobReturnType>, options?: JobOptions): Promise<JobReturnType> {\n options?.signal?.throwIfAborted()\n\n if (this.size === this.maxSize) {\n throw new QueueFullError()\n }\n\n const job = new Job<JobOptions, JobReturnType>(fn, options)\n this.enqueue(job)\n this.safeDispatchEvent('add')\n this.tryToStartAnother()\n\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result })\n this.safeDispatchEvent('success', { detail: { job, result } })\n\n return result\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1)\n break\n }\n }\n }\n\n this.safeDispatchEvent('error', { detail: err })\n this.safeDispatchEvent('failure', { detail: { job, error: err } })\n\n throw err\n })\n }\n\n /**\n * Clear the queue\n */\n clear (): void {\n this.queue.splice(0, this.queue.length)\n }\n\n /**\n * Abort all jobs in the queue and clear it\n */\n abort (): void {\n this.queue.forEach(job => {\n job.abort(new AbortError())\n })\n\n this.clear()\n }\n\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty (options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return\n }\n\n await raceEvent(this, 'empty', options?.signal)\n }\n\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan (limit: number, options?: AbortOptions): Promise<void> {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return\n }\n\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n })\n }\n\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle (options?: AbortOptions): Promise<void> {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return\n }\n\n await raceEvent(this, 'idle', options?.signal)\n }\n\n /**\n * Size of the queue including running items\n */\n get size (): number {\n return this.queue.length\n }\n\n /**\n * The number of queued items waiting to run.\n */\n get queued (): number {\n return this.queue.length - this.pending\n }\n\n /**\n * The number of items currently running.\n */\n get running (): number {\n return this.pending\n }\n\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async * toGenerator (options?: AbortOptions): AsyncGenerator<JobReturnType, void, unknown> {\n options?.signal?.throwIfAborted()\n\n const stream = pushable<JobReturnType>({\n objectMode: true\n })\n\n const cleanup = (err?: Error): void => {\n if (err != null) {\n this.abort()\n } else {\n this.clear()\n }\n\n stream.end(err)\n }\n\n const onQueueJobComplete = (evt: CustomEvent<JobReturnType>): void => {\n if (evt.detail != null) {\n stream.push(evt.detail)\n }\n }\n\n const onQueueError = (evt: CustomEvent<Error>): void => {\n cleanup(evt.detail)\n }\n\n const onQueueIdle = (): void => {\n cleanup()\n }\n\n // clear the queue and throw if the query is aborted\n const onSignalAbort = (): void => {\n cleanup(new AbortError('Queue aborted'))\n }\n\n // add listeners\n this.addEventListener('completed', onQueueJobComplete)\n this.addEventListener('error', onQueueError)\n this.addEventListener('idle', onQueueIdle)\n options?.signal?.addEventListener('abort', onSignalAbort)\n\n try {\n yield * stream\n } finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete)\n this.removeEventListener('error', onQueueError)\n this.removeEventListener('idle', onQueueIdle)\n options?.signal?.removeEventListener('abort', onSignalAbort)\n\n // empty the queue for when the user has broken out of a loop early\n cleanup()\n }\n }\n}\n", "import { Queue } from './queue/index.js'\nimport type { QueueInit } from './queue/index.js'\nimport type { AbortOptions } from '@libp2p/interface'\n\nexport interface PriorityQueueJobOptions extends AbortOptions {\n priority: number\n}\n\nexport class PriorityQueue <JobReturnType = void, JobOptions extends PriorityQueueJobOptions = PriorityQueueJobOptions> extends Queue<JobReturnType, JobOptions> {\n constructor (init: QueueInit<JobReturnType, JobOptions> = {}) {\n super({\n ...init,\n sort: (a, b) => {\n if (a.options.priority > b.options.priority) {\n return -1\n }\n\n if (a.options.priority < b.options.priority) {\n return 1\n }\n\n return 0\n }\n })\n }\n}\n", "\nexport interface ClearableSignal extends AbortSignal {\n clear: () => void\n}\n\n/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {\n const controller = new globalThis.AbortController()\n\n function onAbort (): void {\n controller.abort()\n\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort()\n break\n }\n\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort)\n }\n }\n\n function clear (): void {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort)\n }\n }\n }\n\n const signal = controller.signal as ClearableSignal\n signal.clear = clear\n\n return signal\n}\n", "/**\n * Check if a given ip address is a loopback address\n */\nexport function isLoopbackAddr (ip: string) {\n return /^127\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/i.test(ip) ||\n /^::1$/.test(ip)\n}\n", "import { isLoopbackAddr } from 'is-loopback-addr'\nimport { isIpBased } from './is-ip-based.js'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\n/**\n * Check if a given multiaddr is a loopback address.\n */\nexport function isLoopback (ma: Multiaddr): boolean {\n if (!isIpBased(ma)) {\n // not an IP based multiaddr, cannot be private\n return false\n }\n\n const { address } = ma.nodeAddress()\n\n return isLoopbackAddr(address)\n}\n", "import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'\nimport { isPrivate } from '@libp2p/utils/multiaddr/is-private'\nimport { Circuit, WebSockets, WebSocketsSecure, WebRTC, WebRTCDirect, WebTransport, TCP } from '@multiformats/multiaddr-matcher'\nimport type { Address } from '@libp2p/interface'\n\n/**\n * Sorts addresses by order of reliability, where they have presented the fewest\n * problems:\n *\n * TCP -> WebSockets/Secure -> WebRTC -> WebRTCDirect -> WebTransport\n */\n// eslint-disable-next-line complexity\nexport function reliableTransportsFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isATcp = TCP.exactMatch(a.multiaddr)\n const isBTcp = TCP.exactMatch(b.multiaddr)\n\n if (isATcp && !isBTcp) {\n return -1\n }\n\n if (!isATcp && isBTcp) {\n return 1\n }\n\n const isAWebSocketSecure = WebSocketsSecure.exactMatch(a.multiaddr)\n const isBWebSocketSecure = WebSocketsSecure.exactMatch(b.multiaddr)\n\n if (isAWebSocketSecure && !isBWebSocketSecure) {\n return -1\n }\n\n if (!isAWebSocketSecure && isBWebSocketSecure) {\n return 1\n }\n\n const isAWebSocket = WebSockets.exactMatch(a.multiaddr)\n const isBWebSocket = WebSockets.exactMatch(b.multiaddr)\n\n if (isAWebSocket && !isBWebSocket) {\n return -1\n }\n\n if (!isAWebSocket && isBWebSocket) {\n return 1\n }\n\n const isAWebRTC = WebRTC.exactMatch(a.multiaddr)\n const isBWebRTC = WebRTC.exactMatch(b.multiaddr)\n\n if (isAWebRTC && !isBWebRTC) {\n return -1\n }\n\n if (!isAWebRTC && isBWebRTC) {\n return 1\n }\n\n const isAWebRTCDirect = WebRTCDirect.exactMatch(a.multiaddr)\n const isBWebRTCDirect = WebRTCDirect.exactMatch(b.multiaddr)\n\n if (isAWebRTCDirect && !isBWebRTCDirect) {\n return -1\n }\n\n if (!isAWebRTCDirect && isBWebRTCDirect) {\n return 1\n }\n\n const isAWebTransport = WebTransport.exactMatch(a.multiaddr)\n const isBWebTransport = WebTransport.exactMatch(b.multiaddr)\n\n if (isAWebTransport && !isBWebTransport) {\n return -1\n }\n\n if (!isAWebTransport && isBWebTransport) {\n return 1\n }\n\n // ... everything else\n return 0\n}\n\n/**\n * Compare function for array.sort() that moves loopback addresses to the end\n * of the array.\n */\nexport function loopbackAddressLast (a: Address, b: Address): -1 | 0 | 1 {\n const isALoopback = isLoopback(a.multiaddr)\n const isBLoopback = isLoopback(b.multiaddr)\n\n if (isALoopback && !isBLoopback) {\n return 1\n } else if (!isALoopback && isBLoopback) {\n return -1\n }\n\n return 0\n}\n\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nexport function publicAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n const isAPrivate = isPrivate(a.multiaddr)\n const isBPrivate = isPrivate(b.multiaddr)\n\n if (isAPrivate && !isBPrivate) {\n return 1\n } else if (!isAPrivate && isBPrivate) {\n return -1\n }\n\n return 0\n}\n\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nexport function certifiedAddressesFirst (a: Address, b: Address): -1 | 0 | 1 {\n if (a.isCertified && !b.isCertified) {\n return -1\n } else if (!a.isCertified && b.isCertified) {\n return 1\n }\n\n return 0\n}\n\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * end of the array.\n */\nexport function circuitRelayAddressesLast (a: Address, b: Address): -1 | 0 | 1 {\n const isACircuit = Circuit.exactMatch(a.multiaddr)\n const isBCircuit = Circuit.exactMatch(b.multiaddr)\n\n if (isACircuit && !isBCircuit) {\n return 1\n } else if (!isACircuit && isBCircuit) {\n return -1\n }\n\n return 0\n}\n\nexport function defaultAddressSorter (addresses: Address[]): Address[] {\n return addresses\n .sort(reliableTransportsFirst)\n .sort(certifiedAddressesFirst)\n .sort(circuitRelayAddressesLast)\n .sort(publicAddressesFirst)\n .sort(loopbackAddressLast)\n}\n", "/* eslint-disable max-depth */\nimport { TimeoutError, DialError, setMaxListeners, AbortError } from '@libp2p/interface'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { PriorityQueue } from '@libp2p/utils/priority-queue'\nimport { resolvers, multiaddr } from '@multiformats/multiaddr'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport { Circuit } from '@multiformats/multiaddr-matcher'\nimport { anySignal } from 'any-signal'\nimport { CustomProgressEvent } from 'progress-events'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { DialDeniedError, NoValidAddressesError } from '../errors.js'\nimport { getPeerAddress } from '../get-peer.js'\nimport { defaultAddressSorter } from './address-sorter.js'\nimport {\n DIAL_TIMEOUT,\n MAX_PARALLEL_DIALS,\n MAX_PEER_ADDRS_TO_DIAL,\n LAST_DIAL_FAILURE_KEY,\n MAX_DIAL_QUEUE_LENGTH,\n LAST_DIAL_SUCCESS_KEY\n} from './constants.js'\nimport { resolveMultiaddrs } from './utils.js'\nimport { DEFAULT_DIAL_PRIORITY } from './index.js'\nimport type { AddressSorter, ComponentLogger, Logger, Connection, ConnectionGater, Metrics, PeerId, Address, PeerStore, PeerRouting, IsDialableOptions, OpenConnectionProgressEvents } from '@libp2p/interface'\nimport type { OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'\nimport type { PriorityQueueJobOptions } from '@libp2p/utils/priority-queue'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr, Resolver } from '@multiformats/multiaddr'\nimport type { ProgressOptions } from 'progress-events'\n\nexport interface PendingDialTarget {\n resolve(value: any): void\n reject(err: Error): void\n}\n\ninterface DialQueueJobOptions extends PriorityQueueJobOptions, ProgressOptions<OpenConnectionProgressEvents> {\n peerId?: PeerId\n multiaddrs: Set<string>\n}\n\ninterface DialerInit {\n addressSorter?: AddressSorter\n maxParallelDials?: number\n maxDialQueueLength?: number\n maxPeerAddrsToDial?: number\n dialTimeout?: number\n resolvers?: Record<string, Resolver>\n connections?: PeerMap<Connection[]>\n}\n\nconst defaultOptions = {\n maxParallelDials: MAX_PARALLEL_DIALS,\n maxDialQueueLength: MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n}\n\ninterface DialQueueComponents {\n peerId: PeerId\n metrics?: Metrics\n peerStore: PeerStore\n peerRouting: PeerRouting\n transportManager: TransportManager\n connectionGater: ConnectionGater\n logger: ComponentLogger\n dns?: DNS\n}\n\nexport class DialQueue {\n public queue: PriorityQueue<Connection, DialQueueJobOptions>\n private readonly components: DialQueueComponents\n private readonly addressSorter?: AddressSorter\n private readonly maxPeerAddrsToDial: number\n private readonly maxDialQueueLength: number\n private readonly dialTimeout: number\n private shutDownController: AbortController\n private readonly connections: PeerMap<Connection[]>\n private readonly log: Logger\n\n constructor (components: DialQueueComponents, init: DialerInit = {}) {\n this.addressSorter = init.addressSorter\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout\n this.connections = init.connections ?? new PeerMap()\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue')\n this.components = components\n\n this.shutDownController = new AbortController()\n setMaxListeners(Infinity, this.shutDownController.signal)\n\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value)\n }\n\n // controls dial concurrency\n this.queue = new PriorityQueue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n })\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n if (event.detail?.name !== AbortError.name) {\n this.log.error('error in dial queue - %e', event.detail)\n }\n })\n }\n\n start (): void {\n this.shutDownController = new AbortController()\n setMaxListeners(Infinity, this.shutDownController.signal)\n }\n\n /**\n * Clears any pending dials\n */\n stop (): void {\n this.shutDownController.abort()\n this.queue.abort()\n }\n\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {\n const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)\n\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false\n }\n\n if (conn.remotePeer.equals(peerId)) {\n return true\n }\n\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr)\n })\n })\n\n if (existingConnection?.status === 'open') {\n this.log('already connected to %a', existingConnection.remoteAddr)\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))\n return existingConnection\n }\n\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true\n }\n\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs\n\n if (addresses == null) {\n return false\n }\n\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true\n }\n }\n\n return false\n })\n\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId)\n\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString())\n }\n\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-in-dial-queue'))\n return existingDial.join(options)\n }\n\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new DialError('Dial queue is full')\n }\n\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()))\n\n options.onProgress?.(new CustomProgressEvent('dial-queue:add-to-dial-queue'))\n return this.queue.add(async (options) => {\n options.onProgress?.(new CustomProgressEvent('dial-queue:start-dial'))\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = anySignal([\n this.shutDownController.signal,\n options.signal\n ])\n setMaxListeners(Infinity, signal)\n\n try {\n return await this.dialPeer(options, signal)\n } finally {\n // clean up abort signals/controllers\n signal.clear()\n }\n }, {\n peerId,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal ?? AbortSignal.timeout(this.dialTimeout),\n onProgress: options.onProgress\n })\n }\n\n private async dialPeer (options: DialQueueJobOptions, signal: AbortSignal): Promise<Connection> {\n const peerId = options.peerId\n const multiaddrs = options.multiaddrs\n const failedMultiaddrs = new Set<string>()\n\n // if we have no multiaddrs, only a peer id, set a flag so we will look the\n // peer up in the peer routing to obtain multiaddrs\n let forcePeerLookup = options.multiaddrs.size === 0\n\n let dialed = 0\n let dialIteration = 0\n const errors: Error[] = []\n\n this.log('starting dial to %p', peerId)\n\n // repeat this operation in case addresses are added to the dial while we\n // resolve multiaddrs, etc\n while (forcePeerLookup || multiaddrs.size > 0) {\n dialIteration++\n\n // only perform peer lookup once\n forcePeerLookup = false\n\n // the addresses we will dial\n const addrsToDial: Address[] = []\n\n // copy the addresses into a new set\n const addrs = new Set(options.multiaddrs)\n\n // empty the old set - subsequent dial attempts for the same peer id may\n // add more addresses to try\n multiaddrs.clear()\n\n this.log('calculating addrs to dial %p from %s', peerId, [...addrs])\n\n // load addresses from address book, resolve and dnsaddrs, filter\n // undialables, add peer IDs, etc\n const calculatedAddrs = await this.calculateMultiaddrs(peerId, addrs, {\n ...options,\n signal\n })\n\n for (const addr of calculatedAddrs) {\n // skip any addresses we have previously failed to dial\n if (failedMultiaddrs.has(addr.multiaddr.toString())) {\n this.log.trace('skipping previously failed multiaddr %a while dialing %p', addr.multiaddr, peerId)\n continue\n }\n\n addrsToDial.push(addr)\n }\n\n this.log('%s dial to %p with %s', dialIteration === 1 ? 'starting' : 'continuing', peerId, addrsToDial.map(ma => ma.multiaddr.toString()))\n\n options?.onProgress?.(new CustomProgressEvent<Address[]>('dial-queue:calculated-addresses', addrsToDial))\n\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, options.peerId)\n\n throw new DialError('Peer had more than maxPeerAddrsToDial')\n }\n\n dialed++\n\n try {\n // try to dial the address\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n })\n\n this.log('dial to %a succeeded', address.multiaddr)\n\n // record the successful dial and the address\n try {\n await this.components.peerStore.merge(conn.remotePeer, {\n multiaddrs: [\n conn.remoteAddr\n ],\n metadata: {\n [LAST_DIAL_SUCCESS_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n })\n } catch (err: any) {\n this.log.error('could not update last dial failure key for %p', peerId, err)\n }\n\n // dial successful, return the connection\n return conn\n } catch (err: any) {\n this.log.error('dial failed to %a', address.multiaddr, err)\n\n // ensure we don't dial it again in this attempt\n failedMultiaddrs.add(address.multiaddr.toString())\n\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.merge(peerId, {\n metadata: {\n [LAST_DIAL_FAILURE_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n })\n } catch (err: any) {\n this.log.error('could not update last dial failure key for %p', peerId, err)\n }\n }\n\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new TimeoutError(err.message)\n }\n\n errors.push(err)\n }\n }\n }\n\n if (errors.length === 1) {\n throw errors[0]\n }\n\n throw new AggregateError(errors, 'All multiaddr dials failed')\n }\n\n // eslint-disable-next-line complexity\n private async calculateMultiaddrs (peerId?: PeerId, multiaddrs: Set<string> = new Set<string>(), options: OpenConnectionOptions = {}): Promise<Address[]> {\n const addrs: Address[] = [...multiaddrs].map(ma => ({\n multiaddr: multiaddr(ma),\n isCertified: false\n }))\n\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new DialError('Tried to dial self')\n }\n\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new DialDeniedError('The dial request is blocked by gater.allowDialPeer')\n }\n\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId)\n try {\n const peer = await this.components.peerStore.get(peerId)\n addrs.push(...peer.addresses)\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()))\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n }\n\n // if we still don't have any addresses for this peer, or the only\n // addresses we have are without any routing information (e.g.\n // `/p2p/Qmfoo`), try a lookup using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId)\n\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId, options)\n\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()))\n\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })))\n } catch (err: any) {\n if (err.name === 'NoPeerRoutersError') {\n this.log('no peer routers configured', peerId)\n } else {\n this.log.error('looking up multiaddrs for %p in the peer routing failed - %e', peerId, err)\n }\n }\n }\n }\n\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(\n addrs.map(async addr => {\n const result = await resolveMultiaddrs(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n })\n\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr\n }\n\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }))\n })\n ))\n .flat()\n\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop()\n\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr\n }\n\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n }\n }\n\n return addr\n })\n }\n\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.dialTransportForMultiaddr(addr.multiaddr) == null) {\n return false\n }\n\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId()\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId)\n }\n\n return true\n })\n\n // deduplicate addresses\n const dedupedAddrs = new Map<string, Address>()\n\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString()\n const existing = dedupedAddrs.get(maStr)\n\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false\n continue\n }\n\n dedupedAddrs.set(maStr, addr)\n }\n\n const dedupedMultiaddrs = [...dedupedAddrs.values()]\n\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new NoValidAddressesError('The dial request has no valid addresses')\n }\n\n const gatedAddrs: Address[] = []\n\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue\n }\n\n gatedAddrs.push(addr)\n }\n\n const sortedGatedAddrs = this.addressSorter == null ? defaultAddressSorter(gatedAddrs) : gatedAddrs.sort(this.addressSorter)\n\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new DialDeniedError('The connection gater denied all addresses in the dial request')\n }\n\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()))\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()))\n\n return sortedGatedAddrs\n }\n\n async isDialable (multiaddr: Multiaddr | Multiaddr[], options: IsDialableOptions = {}): Promise<boolean> {\n if (!Array.isArray(multiaddr)) {\n multiaddr = [multiaddr]\n }\n\n try {\n const addresses = await this.calculateMultiaddrs(undefined, new Set(multiaddr.map(ma => ma.toString())), options)\n\n if (options.runOnLimitedConnection === false) {\n // return true if any resolved multiaddrs are not relay addresses\n return addresses.find(addr => {\n return !Circuit.matches(addr.multiaddr)\n }) != null\n }\n\n return true\n } catch (err) {\n this.log.trace('error calculating if multiaddr(s) were dialable', err)\n }\n\n return false\n }\n}\n", "import { Queue } from './queue/index.js'\nimport type { Job } from './queue/job.js'\nimport type { AbortOptions, PeerId } from '@libp2p/interface'\n\nexport interface PeerQueueJobOptions extends AbortOptions {\n peerId: PeerId\n}\n\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nexport class PeerQueue<JobReturnType = void, JobOptions extends PeerQueueJobOptions = PeerQueueJobOptions> extends Queue<JobReturnType, JobOptions> {\n has (peerId: PeerId): boolean {\n return this.find(peerId) != null\n }\n\n find (peerId: PeerId): Job<JobOptions, JobReturnType> | undefined {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId)\n })\n }\n}\n", "import retry from 'retry';\nimport isNetworkError from 'is-network-error';\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nexport default async function pRetry(input, options) {\n\treturn new Promise((resolve, reject) => {\n\t\toptions = {...options};\n\t\toptions.onFailedAttempt ??= () => {};\n\t\toptions.shouldRetry ??= () => true;\n\t\toptions.retries ??= 10;\n\n\t\tconst operation = retry.operation(options);\n\n\t\tconst abortHandler = () => {\n\t\t\toperation.stop();\n\t\t\treject(options.signal?.reason);\n\t\t};\n\n\t\tif (options.signal && !options.signal.aborted) {\n\t\t\toptions.signal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tconst cleanUp = () => {\n\t\t\toptions.signal?.removeEventListener('abort', abortHandler);\n\t\t\toperation.stop();\n\t\t};\n\n\t\toperation.attempt(async attemptNumber => {\n\t\t\ttry {\n\t\t\t\tconst result = await input(attemptNumber);\n\t\t\t\tcleanUp();\n\t\t\t\tresolve(result);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(error instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof AbortError) {\n\t\t\t\t\t\tthrow error.originalError;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof TypeError && !isNetworkError(error)) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\n\t\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\t\tif (!(await options.shouldRetry(error))) {\n\t\t\t\t\t\toperation.stop();\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\n\t\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\t\tthrow operation.mainError();\n\t\t\t\t\t}\n\t\t\t\t} catch (finalError) {\n\t\t\t\t\tdecorateErrorWithCounts(finalError, attemptNumber, options);\n\t\t\t\t\tcleanUp();\n\t\t\t\t\treject(finalError);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}\n", "const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Load failed', // Safari 17+\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\t// We do an extra check for Safari 17+ as it has a very generic error message.\n\t// Network errors in Safari have no stack.\n\tif (error.message === 'Load failed') {\n\t\treturn error.stack === undefined;\n\t}\n\n\treturn errorMessages.has(error.message);\n}\n", "import { KEEP_ALIVE } from '@libp2p/interface'\nimport { PeerQueue } from '@libp2p/utils/peer-queue'\nimport pRetry from 'p-retry'\nimport { MAX_PARALLEL_RECONNECTS } from './constants.js'\nimport type { ComponentLogger, Libp2pEvents, Logger, Metrics, Peer, PeerId, PeerStore, Startable, TypedEventTarget } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\n\nexport interface ReconnectQueueComponents {\n connectionManager: ConnectionManager\n events: TypedEventTarget<Libp2pEvents>\n peerStore: PeerStore\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport interface ReconnectQueueInit {\n retries?: number\n retryInterval?: number\n backoffFactor?: number\n maxParallelReconnects?: number\n}\n\n/**\n * When peers tagged with `KEEP_ALIVE` disconnect, this component attempts to\n * redial them\n */\nexport class ReconnectQueue implements Startable {\n private readonly log: Logger\n private readonly queue: PeerQueue\n private started: boolean\n private readonly peerStore: PeerStore\n private readonly retries: number\n private readonly retryInterval?: number\n private readonly backoffFactor?: number\n private readonly connectionManager: ConnectionManager\n private readonly events: TypedEventTarget<Libp2pEvents>\n\n constructor (components: ReconnectQueueComponents, init: ReconnectQueueInit = {}) {\n this.log = components.logger.forComponent('libp2p:reconnect-queue')\n this.peerStore = components.peerStore\n this.connectionManager = components.connectionManager\n this.queue = new PeerQueue({\n concurrency: init.maxParallelReconnects ?? MAX_PARALLEL_RECONNECTS,\n metricName: 'libp2p_reconnect_queue',\n metrics: components.metrics\n })\n this.started = false\n this.retries = init.retries ?? 5\n this.backoffFactor = init.backoffFactor\n this.retryInterval = init.retryInterval\n this.events = components.events\n\n components.events.addEventListener('peer:disconnect', (evt) => {\n this.maybeReconnect(evt.detail)\n .catch(err => {\n this.log.error('failed to maybe reconnect to %p - %e', evt.detail, err)\n })\n })\n }\n\n private async maybeReconnect (peerId: PeerId): Promise<void> {\n if (!this.started) {\n return\n }\n\n const peer = await this.peerStore.get(peerId)\n\n if (!hasKeepAliveTag(peer)) {\n return\n }\n\n if (this.queue.has(peerId)) {\n return\n }\n\n this.queue.add(async (options) => {\n await pRetry(async (attempt) => {\n if (!this.started) {\n return\n }\n\n try {\n await this.connectionManager.openConnection(peerId, {\n signal: options?.signal\n })\n } catch (err) {\n this.log('reconnecting to %p attempt %d of %d failed - %e', peerId, attempt, this.retries, err)\n throw err\n }\n }, {\n signal: options?.signal,\n retries: this.retries,\n factor: this.backoffFactor,\n minTimeout: this.retryInterval\n })\n }, {\n peerId\n })\n .catch(async err => {\n this.log.error('failed to reconnect to %p - %e', peerId, err)\n\n const tags: Record<string, undefined> = {}\n\n ;[...peer.tags.keys()].forEach(key => {\n if (key.startsWith(KEEP_ALIVE)) {\n tags[key] = undefined\n }\n })\n\n await this.peerStore.merge(peerId, {\n tags\n })\n\n this.events.safeDispatchEvent('peer:reconnect-failure', {\n detail: peerId\n })\n })\n .catch(async err => {\n this.log.error('failed to remove keep-alive tag from %p - %e', peerId, err)\n })\n }\n\n start (): void {\n this.started = true\n }\n\n async afterStart (): Promise<void> {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers: Peer[] = await this.peerStore.all({\n filters: [\n (peer) => hasKeepAliveTag(peer)\n ]\n })\n\n await Promise.all(\n keepAlivePeers.map(async peer => {\n await this.connectionManager.openConnection(peer.id)\n .catch(err => {\n this.log.error(err)\n })\n })\n )\n })\n .catch(err => {\n this.log.error(err)\n })\n }\n\n stop (): void {\n this.started = false\n this.queue.abort()\n }\n}\n\nfunction hasKeepAliveTag (peer: Peer): boolean {\n for (const tag of peer.tags.keys()) {\n if (tag.startsWith(KEEP_ALIVE)) {\n return true\n }\n }\n\n return false\n}\n", "import { ConnectionClosedError, InvalidMultiaddrError, InvalidParametersError, InvalidPeerIdError, NotStartedError, start, stop } from '@libp2p/interface'\nimport { PeerMap } from '@libp2p/peer-collections'\nimport { RateLimiter } from '@libp2p/utils/rate-limiter'\nimport { type Multiaddr, type Resolver, multiaddr } from '@multiformats/multiaddr'\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\nimport { CustomProgressEvent } from 'progress-events'\nimport { getPeerAddress } from '../get-peer.js'\nimport { ConnectionPruner } from './connection-pruner.js'\nimport { DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL } from './constants.js'\nimport { DialQueue } from './dial-queue.js'\nimport { ReconnectQueue } from './reconnect-queue.js'\nimport { multiaddrToIpNet } from './utils.js'\nimport type { IpNet } from '@chainsafe/netmask'\nimport type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions } from '@libp2p/interface'\nimport type { ConnectionManager, OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'\nimport type { JobStatus } from '@libp2p/utils/queue'\n\nexport const DEFAULT_DIAL_PRIORITY = 50\n\nexport interface ConnectionManagerInit {\n /**\n * The maximum number of connections libp2p is willing to have before it\n * starts pruning connections to reduce resource usage.\n *\n * @default 300/100\n */\n maxConnections?: number\n\n /**\n * Sort the known addresses of a peer before trying to dial, By default public\n * addresses will be dialled before private (e.g. loopback or LAN) addresses.\n */\n addressSorter?: AddressSorter\n\n /**\n * The maximum number of dials across all peers to execute in parallel.\n *\n * @default 100/50\n */\n maxParallelDials?: number\n\n /**\n * The maximum size the dial queue is allowed to grow to. Promises returned\n * when dialing peers after this limit is reached will not resolve until the\n * queue size falls beneath this size.\n *\n * @default 500\n */\n maxDialQueueLength?: number\n\n /**\n * Maximum number of addresses allowed for a given peer before giving up\n *\n * @default 25\n */\n maxPeerAddrsToDial?: number\n\n /**\n * How long a dial attempt is allowed to take, including DNS resolution\n * of the multiaddr, opening a socket and upgrading it to a Connection.\n *\n * @default 10_000\n */\n dialTimeout?: number\n\n /**\n * When a new incoming connection is opened, the upgrade process (e.g.\n * protect, encrypt, multiplex etc) must complete within this number of ms.\n *\n * @default 10_000\n */\n inboundUpgradeTimeout?: number\n\n /**\n * When a new outbound connection is opened, the upgrade process (e.g.\n * protect, encrypt, multiplex etc) must complete within this number of ms.\n *\n * Does not apply if an abort signal is passed to the `.dial` method.\n *\n * @deprecated This is handled by `dialTimeout`\n */\n outboundUpgradeTimeout?: number\n\n /**\n * Protocol negotiation must complete within this number of ms\n *\n * @default 2000\n * @deprecated use outboundStreamProtocolNegotiationTimeout or inboundStreamProtocolNegotiationTimeout instead\n */\n protocolNegotiationTimeout?: number\n\n /**\n * Outbound protocol negotiation must complete within this number of ms.\n *\n * Does not apply if an abort signal is passed to the `.dial` or\n * `.dialProtocol` method of the `ConnectionManager` or the `openStream`\n * method of the `Connection`.\n *\n * @default 10_000\n */\n outboundStreamProtocolNegotiationTimeout?: number\n\n /**\n * Inbound protocol negotiation must complete within this number of ms\n *\n * @default 10_000\n */\n inboundStreamProtocolNegotiationTimeout?: number\n\n /**\n * Multiaddr resolvers to use when dialling\n */\n resolvers?: Record<string, Resolver>\n\n /**\n * A list of multiaddrs that will always be allowed (except if they are in the\n * deny list) to open connections to this node even if we've reached\n * maxConnections\n */\n allow?: string[]\n\n /**\n * A list of multiaddrs that will never be allowed to open connections to\n * this node under any circumstances\n */\n deny?: string[]\n\n /**\n * If more than this many connections are opened per second by a single\n * host, reject subsequent connections.\n *\n * @default 5\n */\n inboundConnectionThreshold?: number\n\n /**\n * The maximum number of parallel incoming connections allowed that have yet\n * to complete the connection upgrade - e.g. choosing connection encryption,\n * muxer, etc.\n *\n * @default 10\n */\n maxIncomingPendingConnections?: number\n\n /**\n * When a peer tagged with `KEEP_ALIVE` disconnects, attempt to redial them\n * this many times.\n *\n * @default 5\n */\n reconnectRetries?: number\n\n /**\n * When a peer tagged with `KEEP_ALIVE` disconnects, wait this long between\n * each retry. Note this will be multiplied by `reconnectFactor` to create an\n * increasing retry backoff.\n *\n * @default 1000\n */\n reconnectRetryInterval?: number\n\n /**\n * When a peer tagged with `KEEP_ALIVE` disconnects, apply this multiplication\n * factor to the time interval between each retry.\n *\n * @default 2\n */\n reconnectBackoffFactor?: number\n\n /**\n * When a peers tagged with `KEEP_ALIVE` disconnect, reconnect to this many at\n * once.\n *\n * @default 5\n */\n maxParallelReconnects?: number\n}\n\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS\n}\n\nexport interface DefaultConnectionManagerComponents {\n peerId: PeerId\n metrics?: Metrics\n peerStore: PeerStore\n peerRouting: PeerRouting\n transportManager: TransportManager\n connectionGater: ConnectionGater\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager implements ConnectionManager, Startable {\n private started: boolean\n private readonly connections: PeerMap<Connection[]>\n private readonly allow: IpNet[]\n private readonly deny: IpNet[]\n private readonly maxIncomingPendingConnections: number\n private incomingPendingConnections: number\n private outboundPendingConnections: number\n private readonly maxConnections: number\n\n public readonly dialQueue: DialQueue\n public readonly reconnectQueue: ReconnectQueue\n public readonly connectionPruner: ConnectionPruner\n private readonly inboundConnectionRateLimiter: RateLimiter\n private readonly peerStore: PeerStore\n private readonly metrics?: Metrics\n private readonly events: TypedEventTarget<Libp2pEvents>\n private readonly log: Logger\n private readonly peerId: PeerId\n\n constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerInit = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections\n\n if (this.maxConnections < 1) {\n throw new InvalidParametersError('Connection Manager maxConnections must be greater than 0')\n }\n\n /**\n * Map of connections per peer\n */\n this.connections = new PeerMap()\n\n this.started = false\n this.peerId = components.peerId\n this.peerStore = components.peerStore\n this.metrics = components.metrics\n this.events = components.events\n this.log = components.logger.forComponent('libp2p:connection-manager')\n\n this.onConnect = this.onConnect.bind(this)\n this.onDisconnect = this.onDisconnect.bind(this)\n\n // allow/deny lists\n this.allow = (init.allow ?? []).map(str => multiaddrToIpNet(str))\n this.deny = (init.deny ?? []).map(str => multiaddrToIpNet(str))\n\n this.incomingPendingConnections = 0\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections\n this.outboundPendingConnections = 0\n\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n })\n\n // controls what happens when we have too many connections\n this.connectionPruner = new ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: init.allow?.map(a => multiaddr(a))\n })\n\n this.dialQueue = new DialQueue(components, {\n addressSorter: init.addressSorter,\n maxParallelDials: init.maxParallelDials ?? MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: dnsaddrResolver\n },\n connections: this.connections\n })\n\n this.reconnectQueue = new ReconnectQueue({\n events: components.events,\n peerStore: components.peerStore,\n logger: components.logger,\n connectionManager: this\n }, {\n retries: init.reconnectRetries,\n retryInterval: init.reconnectRetryInterval,\n backoffFactor: init.reconnectBackoffFactor,\n maxParallelReconnects: init.maxParallelReconnects\n })\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/connection-manager'\n\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start (): Promise<void> {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n 'inbound pending': this.incomingPendingConnections,\n outbound: 0,\n 'outbound pending': this.outboundPendingConnections\n }\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n metric[conn.direction]++\n }\n }\n\n return metric\n }\n })\n\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric: Record<string, number> = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`\n\n metric[key] = (metric[key] ?? 0) + 1\n }\n }\n }\n\n return metric\n }\n })\n\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams: Record<string, number[]> = {}\n\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams: Record<string, number> = {}\n\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`\n\n streams[key] = (streams[key] ?? 0) + 1\n }\n\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? []\n allStreams[protocol].push(count)\n }\n }\n }\n\n const metric: Record<string, number> = {}\n\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b)\n\n const index = Math.floor(counts.length * 0.9)\n metric[protocol] = counts[index]\n }\n\n return metric\n }\n })\n\n this.events.addEventListener('connection:open', this.onConnect)\n this.events.addEventListener('connection:close', this.onDisconnect)\n\n await start(\n this.dialQueue,\n this.reconnectQueue,\n this.connectionPruner\n )\n\n this.started = true\n this.log('started')\n }\n\n /**\n * Stops the Connection Manager\n */\n async stop (): Promise<void> {\n this.events.removeEventListener('connection:open', this.onConnect)\n this.events.removeEventListener('connection:close', this.onDisconnect)\n\n await stop(\n this.reconnectQueue,\n this.dialQueue,\n this.connectionPruner\n )\n\n // Close all connections we're tracking\n const tasks: Array<Promise<void>> = []\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close()\n } catch (err) {\n this.log.error(err)\n }\n })())\n }\n }\n\n this.log('closing %d connections', tasks.length)\n await Promise.all(tasks)\n this.connections.clear()\n\n this.log('stopped')\n }\n\n getMaxConnections (): number {\n return this.maxConnections\n }\n\n onConnect (evt: CustomEvent<Connection>): void {\n void this._onConnect(evt).catch(err => {\n this.log.error(err)\n })\n }\n\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect (evt: CustomEvent<Connection>): Promise<void> {\n const { detail: connection } = evt\n\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close()\n return\n }\n\n if (connection.status !== 'open') {\n // this can happen when the remote closes the connection immediately after\n // opening\n return\n }\n\n const peerId = connection.remotePeer\n const isNewPeer = !this.connections.has(peerId)\n const storedConns = this.connections.get(peerId) ?? []\n storedConns.push(connection)\n\n this.connections.set(peerId, storedConns)\n\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n })\n }\n\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer })\n }\n }\n\n /**\n * Removes the connection from tracking\n */\n onDisconnect (evt: CustomEvent<Connection>): void {\n const { detail: connection } = evt\n const peerId = connection.remotePeer\n const peerConns = this.connections.get(peerId) ?? []\n\n // remove closed connection\n const filteredPeerConns = peerConns.filter(conn => conn.id !== connection.id)\n\n // update peer connections\n this.connections.set(peerId, filteredPeerConns)\n\n if (filteredPeerConns.length === 0) {\n // trigger disconnect event if no connections remain\n this.log('onDisconnect remove all connections for peer %p', peerId)\n this.connections.delete(peerId)\n\n // broadcast disconnect event\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer })\n }\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n if (peerId != null) {\n return this.connections.get(peerId) ?? []\n }\n\n let conns: Connection[] = []\n\n for (const c of this.connections.values()) {\n conns = conns.concat(c)\n }\n\n return conns\n }\n\n getConnectionsMap (): PeerMap<Connection[]> {\n return this.connections\n }\n\n async openConnection (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {\n if (!this.started) {\n throw new NotStartedError('Not started')\n }\n\n this.outboundPendingConnections++\n\n try {\n options.signal?.throwIfAborted()\n\n const { peerId } = getPeerAddress(peerIdOrMultiaddr)\n\n if (this.peerId.equals(peerId)) {\n throw new InvalidPeerIdError('Can not dial self')\n }\n\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId)\n const existingConnection = this.getConnections(peerId)\n .find(conn => conn.limits == null)\n\n if (existingConnection != null) {\n this.log('had an existing non-limited connection to %p', peerId)\n\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))\n return existingConnection\n }\n }\n\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n })\n\n if (connection.status !== 'open') {\n throw new ConnectionClosedError('Remote closed connection during opening')\n }\n\n let peerConnections = this.connections.get(connection.remotePeer)\n\n if (peerConnections == null) {\n peerConnections = []\n this.connections.set(connection.remotePeer, peerConnections)\n }\n\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false\n\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true\n }\n\n // make sure we don't already have a connection to this multiaddr\n if (options.force !== true && conn.id !== connection.id && conn.remoteAddr.equals(connection.remoteAddr)) {\n connection.abort(new InvalidMultiaddrError('Duplicate multiaddr connection'))\n\n // return the existing connection\n return conn\n }\n }\n\n if (!trackedConnection) {\n peerConnections.push(connection)\n }\n\n return connection\n } finally {\n this.outboundPendingConnections--\n }\n }\n\n async closeConnections (peerId: PeerId, options: AbortOptions = {}): Promise<void> {\n const connections = this.connections.get(peerId) ?? []\n\n await Promise.all(\n connections.map(async connection => {\n try {\n await connection.close(options)\n } catch (err: any) {\n connection.abort(err)\n }\n })\n )\n }\n\n async acceptIncomingConnection (maConn: MultiaddrConnection): Promise<boolean> {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return ma.contains(maConn.remoteAddr.nodeAddress().address)\n })\n\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr)\n return false\n }\n\n // check allow list\n const allowConnection = this.allow.some(ipNet => {\n return ipNet.contains(maConn.remoteAddr.nodeAddress().address)\n })\n\n if (allowConnection) {\n this.incomingPendingConnections++\n\n return true\n }\n\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr)\n return false\n }\n\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address\n\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1)\n } catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host)\n return false\n }\n }\n\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++\n\n return true\n }\n\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr)\n return false\n }\n\n afterUpgradeInbound (): void {\n this.incomingPendingConnections--\n }\n\n getDialQueue (): PendingDial[] {\n const statusMap: Record<JobStatus, PendingDialStatus> = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n }\n\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => multiaddr(ma))\n }\n })\n }\n\n async isDialable (multiaddr: Multiaddr | Multiaddr[], options: IsDialableOptions = {}): Promise<boolean> {\n return this.dialQueue.isDialable(multiaddr, options)\n }\n}\n", "/**\n * Implements exponential moving average. Ported from `moving-average`.\n *\n * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * @see https://www.npmjs.com/package/moving-average\n */\nexport class MovingAverage {\n public movingAverage: number\n public variance: number\n public deviation: number\n public forecast: number\n private readonly timeSpan: number\n private previousTime?: number\n\n constructor (timeSpan: number) {\n this.timeSpan = timeSpan\n this.movingAverage = 0\n this.variance = 0\n this.deviation = 0\n this.forecast = 0\n }\n\n alpha (t: number, pt: number): number {\n return 1 - (Math.exp(-(t - pt) / this.timeSpan))\n }\n\n push (value: number, time: number = Date.now()): void {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime)\n const diff = value - this.movingAverage\n const incr = a * diff\n this.movingAverage = a * value + (1 - a) * this.movingAverage\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr)\n this.deviation = Math.sqrt(this.variance)\n // calculate forecast\n this.forecast = this.movingAverage + a * diff\n } else {\n this.movingAverage = value\n }\n\n this.previousTime = time\n }\n}\n", "import { setMaxListeners } from '@libp2p/interface'\nimport { anySignal, type ClearableSignal } from 'any-signal'\nimport { MovingAverage } from './moving-average.js'\nimport type { MetricGroup, Metrics } from '@libp2p/interface'\n\nexport const DEFAULT_TIMEOUT_MULTIPLIER = 1.2\nexport const DEFAULT_FAILURE_MULTIPLIER = 2\nexport const DEFAULT_MIN_TIMEOUT = 5000\n\nexport interface AdaptiveTimeoutSignal extends ClearableSignal {\n start: number\n timeout: number\n}\n\nexport interface AdaptiveTimeoutInit {\n metricName?: string\n metrics?: Metrics\n interval?: number\n timeoutMultiplier?: number\n failureMultiplier?: number\n minTimeout?: number\n}\n\nexport interface GetTimeoutSignalOptions {\n timeoutFactor?: number\n signal?: AbortSignal\n}\n\nexport class AdaptiveTimeout {\n private readonly success: MovingAverage\n private readonly failure: MovingAverage\n private readonly next: MovingAverage\n private readonly metric?: MetricGroup\n private readonly timeoutMultiplier: number\n private readonly failureMultiplier: number\n private readonly minTimeout: number\n\n constructor (init: AdaptiveTimeoutInit = {}) {\n this.success = new MovingAverage(init.interval ?? 5000)\n this.failure = new MovingAverage(init.interval ?? 5000)\n this.next = new MovingAverage(init.interval ?? 5000)\n this.failureMultiplier = init.failureMultiplier ?? DEFAULT_FAILURE_MULTIPLIER\n this.timeoutMultiplier = init.timeoutMultiplier ?? DEFAULT_TIMEOUT_MULTIPLIER\n this.minTimeout = init.minTimeout ?? DEFAULT_MIN_TIMEOUT\n\n if (init.metricName != null) {\n this.metric = init.metrics?.registerMetricGroup(init.metricName)\n }\n }\n\n getTimeoutSignal (options: GetTimeoutSignalOptions = {}): AdaptiveTimeoutSignal {\n // calculate timeout for individual peers based on moving average of\n // previous successful requests\n const timeout = Math.max(\n Math.round(this.next.movingAverage * (options.timeoutFactor ?? this.timeoutMultiplier)),\n this.minTimeout\n )\n const sendTimeout = AbortSignal.timeout(timeout)\n const timeoutSignal = anySignal([options.signal, sendTimeout]) as AdaptiveTimeoutSignal\n setMaxListeners(Infinity, timeoutSignal, sendTimeout)\n\n timeoutSignal.start = Date.now()\n timeoutSignal.timeout = timeout\n\n return timeoutSignal\n }\n\n cleanUp (signal: AdaptiveTimeoutSignal): void {\n const time = Date.now() - signal.start\n\n if (signal.aborted) {\n this.failure.push(time)\n this.next.push(time * this.failureMultiplier)\n this.metric?.update({\n failureMovingAverage: this.failure.movingAverage,\n failureDeviation: this.failure.deviation,\n failureForecast: this.failure.forecast,\n failureVariance: this.failure.variance,\n failure: time\n })\n } else {\n this.success.push(time)\n this.next.push(time)\n this.metric?.update({\n successMovingAverage: this.success.movingAverage,\n successDeviation: this.success.deviation,\n successForecast: this.success.forecast,\n successVariance: this.success.variance,\n success: time\n })\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 * 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", "/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\n\nimport { queuelessPushable } from 'it-queueless-pushable'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { UnexpectedEOFError } from './errors.js'\nimport type { AbortOptions } from 'abort-error'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface ReadOptions extends AbortOptions {\n bytes: number\n}\n\nexport interface ByteStream <Stream = unknown> {\n /**\n * Read bytes from the stream.\n *\n * If a required number of bytes is passed as an option, this will wait for\n * the underlying stream to supply that number of bytes, throwing an\n * `UnexpectedEOFError` if the stream closes before this happens.\n *\n * If no required number of bytes is passed, this will return `null` if the\n * underlying stream closes before supplying any bytes.\n */\n read(options: ReadOptions): Promise<Uint8ArrayList>\n read(options?: AbortOptions): Promise<Uint8ArrayList | null>\n\n /**\n * Write the passed bytes to the stream\n */\n write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\nexport interface ByteStreamOpts {\n /**\n * After the stream is unwrapped, any bytes that have been read from the\n * incoming stream will be yielded in-order as `Uint8Array`(s).\n *\n * To yield a single `Uint8ArrayList` with all unread bytes instead, pass\n * `false` here.\n */\n yieldBytes?: boolean\n}\n\nexport function byteStream <Stream extends Duplex<any, any, any>> (duplex: Stream, opts?: ByteStreamOpts): ByteStream<Stream> {\n const write = queuelessPushable()\n\n duplex.sink(write).catch(async (err: Error) => {\n await write.end(err)\n })\n\n duplex.sink = async (source: any) => {\n for await (const buf of source) {\n await write.push(buf)\n }\n\n await write.end()\n }\n\n let source: AsyncGenerator<any> = duplex.source\n\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]()\n } else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]()\n }\n\n const readBuffer = new Uint8ArrayList()\n\n const W: ByteStream<Stream> = {\n read: async (options?: ReadOptions) => {\n options?.signal?.throwIfAborted()\n\n if (options?.bytes == null) {\n // just read whatever arrives\n const { done, value } = await raceSignal(source.next(), options?.signal)\n\n if (done === true) {\n return null\n }\n\n return value\n }\n\n while (readBuffer.byteLength < options.bytes) {\n const { value, done } = await raceSignal(source.next(), options?.signal)\n\n if (done === true) {\n throw new UnexpectedEOFError('unexpected end of input')\n }\n\n readBuffer.append(value)\n }\n\n const buf = readBuffer.sublist(0, options.bytes)\n readBuffer.consume(options.bytes)\n\n return buf\n },\n write: async (data, options?: AbortOptions) => {\n options?.signal?.throwIfAborted()\n\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options)\n } else {\n await write.push(data.subarray(), options)\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source\n duplex.source = (async function * () {\n if (opts?.yieldBytes === false) {\n yield readBuffer\n } else {\n yield * readBuffer\n }\n\n yield * originalStream\n }())\n }\n\n return duplex\n }\n }\n\n return W\n}\n", "import { randomBytes } from '@libp2p/crypto'\nimport { serviceCapabilities, setMaxListeners } from '@libp2p/interface'\nimport { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout'\nimport { byteStream } from 'it-byte-stream'\nimport type { ComponentLogger, Logger, Metrics, Startable } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\nimport type { AdaptiveTimeoutInit } from '@libp2p/utils/adaptive-timeout'\n\nconst DEFAULT_PING_INTERVAL_MS = 10000\nconst PROTOCOL_VERSION = '1.0.0'\nconst PROTOCOL_NAME = 'ping'\nconst PROTOCOL_PREFIX = 'ipfs'\nconst PING_LENGTH = 32\nconst DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE = true\n\nexport interface ConnectionMonitorInit {\n /**\n * Whether the connection monitor is enabled\n *\n * @default true\n */\n enabled?: boolean\n\n /**\n * How often to ping remote peers in ms\n *\n * @default 10000\n */\n pingInterval?: number\n\n /**\n * Timeout settings for how long the ping is allowed to take before the\n * connection will be judged inactive and aborted.\n *\n * The timeout is adaptive to cope with slower networks or nodes that\n * have changing network characteristics, such as mobile.\n */\n pingTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * If true, any connection that fails the ping will be aborted\n *\n * @default true\n */\n abortConnectionOnPingFailure?: boolean\n\n /**\n * Override the ping protocol prefix\n *\n * @default 'ipfs'\n */\n protocolPrefix?: string\n}\n\nexport interface ConnectionMonitorComponents {\n logger: ComponentLogger\n connectionManager: ConnectionManager\n metrics?: Metrics\n}\n\nexport class ConnectionMonitor implements Startable {\n private readonly protocol: string\n private readonly components: ConnectionMonitorComponents\n private readonly log: Logger\n private heartbeatInterval?: ReturnType<typeof setInterval>\n private readonly pingIntervalMs: number\n private abortController?: AbortController\n private readonly timeout: AdaptiveTimeout\n private readonly abortConnectionOnPingFailure: boolean\n\n constructor (components: ConnectionMonitorComponents, init: ConnectionMonitorInit = {}) {\n this.components = components\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n\n this.log = components.logger.forComponent('libp2p:connection-monitor')\n this.pingIntervalMs = init.pingInterval ?? DEFAULT_PING_INTERVAL_MS\n this.abortConnectionOnPingFailure = init.abortConnectionOnPingFailure ?? DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE\n this.timeout = new AdaptiveTimeout({\n ...(init.pingTimeout ?? {}),\n metrics: components.metrics,\n metricName: 'libp2p_connection_monitor_ping_time_milliseconds'\n })\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/connection-monitor'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/connection-monitor'\n ]\n\n start (): void {\n this.abortController = new AbortController()\n setMaxListeners(Infinity, this.abortController.signal)\n\n this.heartbeatInterval = setInterval(() => {\n this.components.connectionManager.getConnections().forEach(conn => {\n Promise.resolve().then(async () => {\n let start = Date.now()\n try {\n const signal = this.timeout.getTimeoutSignal({\n signal: this.abortController?.signal\n })\n const stream = await conn.newStream(this.protocol, {\n signal,\n runOnLimitedConnection: true\n })\n const bs = byteStream(stream)\n start = Date.now()\n\n await Promise.all([\n bs.write(randomBytes(PING_LENGTH), {\n signal\n }),\n bs.read({\n bytes: PING_LENGTH,\n signal\n })\n ])\n\n conn.rtt = Date.now() - start\n\n await bs.unwrap().close({\n signal\n })\n } catch (err: any) {\n if (err.name !== 'UnsupportedProtocolError') {\n throw err\n }\n\n // protocol was unsupported, but that's ok as it means the remote\n // peer was still alive. We ran multistream-select which means two\n // round trips (e.g. 1x for the mss header, then another for the\n // protocol) so divide the time it took by two\n conn.rtt = (Date.now() - start) / 2\n }\n })\n .catch(err => {\n this.log.error('error during heartbeat', err)\n\n if (this.abortConnectionOnPingFailure) {\n this.log.error('aborting connection due to ping failure')\n conn.abort(err)\n } else {\n this.log('connection ping failed, but not aborting due to abortConnectionOnPingFailure flag')\n }\n })\n })\n }, this.pingIntervalMs)\n }\n\n stop (): void {\n this.abortController?.abort()\n\n if (this.heartbeatInterval != null) {\n clearInterval(this.heartbeatInterval)\n }\n }\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 { NotStartedError } from '@libp2p/interface'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport merge from 'it-merge'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { NoContentRoutersError } from './errors.js'\nimport type { AbortOptions, ComponentLogger, ContentRouting, Metrics, PeerInfo, PeerRouting, PeerStore, RoutingOptions, Startable } from '@libp2p/interface'\nimport type { CID } from 'multiformats/cid'\n\nexport interface CompoundContentRoutingInit {\n routers: ContentRouting[]\n}\n\nexport interface CompoundContentRoutingComponents {\n peerStore: PeerStore\n peerRouting: PeerRouting\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport class CompoundContentRouting implements ContentRouting, Startable {\n private readonly routers: ContentRouting[]\n private started: boolean\n private readonly components: CompoundContentRoutingComponents\n\n constructor (components: CompoundContentRoutingComponents, init: CompoundContentRoutingInit) {\n this.routers = init.routers ?? []\n this.started = false\n this.components = components\n\n this.findProviders = components.metrics?.traceFunction('libp2p.contentRouting.findProviders', this.findProviders.bind(this), {\n optionsIndex: 1,\n getAttributesFromArgs: ([cid], attrs) => {\n return {\n ...attrs,\n cid: cid.toString()\n }\n },\n getAttributesFromYieldedValue: (value, attrs: { providers?: string[] }) => {\n return {\n ...attrs,\n providers: [...(Array.isArray(attrs.providers) ? attrs.providers : []), value.id.toString()]\n }\n }\n }) ?? this.findProviders\n this.provide = components.metrics?.traceFunction('libp2p.contentRouting.provide', this.provide.bind(this), {\n optionsIndex: 1,\n getAttributesFromArgs: ([cid], attrs) => {\n return {\n ...attrs,\n cid: cid.toString()\n }\n }\n }) ?? this.provide\n this.cancelReprovide = components.metrics?.traceFunction('libp2p.contentRouting.cancelReprovide', this.cancelReprovide.bind(this), {\n optionsIndex: 1,\n getAttributesFromArgs: ([cid], attrs) => {\n return {\n ...attrs,\n cid: cid.toString()\n }\n }\n }) ?? this.cancelReprovide\n this.put = components.metrics?.traceFunction('libp2p.contentRouting.put', this.put.bind(this), {\n optionsIndex: 2,\n getAttributesFromArgs: ([key]) => {\n return {\n key: uint8ArrayToString(key, 'base36')\n }\n }\n }) ?? this.put\n this.get = components.metrics?.traceFunction('libp2p.contentRouting.get', this.get.bind(this), {\n optionsIndex: 1,\n getAttributesFromArgs: ([key]) => {\n return {\n key: uint8ArrayToString(key, 'base36')\n }\n }\n }) ?? this.get\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/content-routing'\n\n isStarted (): boolean {\n return this.started\n }\n\n async start (): Promise<void> {\n this.started = true\n }\n\n async stop (): Promise<void> {\n this.started = false\n }\n\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async * findProviders (key: CID, options: RoutingOptions = {}): AsyncGenerator<PeerInfo> {\n if (this.routers.length === 0) {\n throw new NoContentRoutersError('No content routers available')\n }\n\n const self = this\n const seen = new PeerSet()\n\n for await (const peer of merge(\n ...self.routers\n .filter(router => router.findProviders instanceof Function)\n .map(router => router.findProviders(key, options))\n )) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue\n }\n\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n }\n\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue\n }\n\n seen.add(peer.id)\n\n yield peer\n }\n }\n\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide (key: CID, options: AbortOptions = {}): Promise<void> {\n if (this.routers.length === 0) {\n throw new NoContentRoutersError('No content routers available')\n }\n\n await Promise.all(\n this.routers\n .filter(router => router.provide instanceof Function)\n .map(async (router) => {\n await router.provide(key, options)\n }))\n }\n\n async cancelReprovide (key: CID, options: AbortOptions = {}): Promise<void> {\n if (this.routers.length === 0) {\n throw new NoContentRoutersError('No content routers available')\n }\n\n await Promise.all(\n this.routers\n .filter(router => router.cancelReprovide instanceof Function)\n .map(async (router) => {\n await router.cancelReprovide(key, options)\n })\n )\n }\n\n /**\n * Store the given key/value pair in the available content routings\n */\n async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise<void> {\n if (!this.isStarted()) {\n throw new NotStartedError()\n }\n\n await Promise.all(\n this.routers\n .filter(router => router.put instanceof Function)\n .map(async (router) => {\n await router.put(key, value, options)\n })\n )\n }\n\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get (key: Uint8Array, options?: AbortOptions): Promise<Uint8Array> {\n if (!this.isStarted()) {\n throw new NotStartedError()\n }\n\n return Promise.any(\n this.routers\n .filter(router => router.get instanceof Function)\n .map(async (router) => {\n return router.get(key, options)\n })\n )\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Takes an (async) iterable that emits promise-returning functions, invokes them in parallel up to the concurrency limit and emits the results as they become available, optionally in the same order as the input\n *\n * @example\n *\n * ```javascript\n * import parallel from 'it-parallel'\n * import all from 'it-all'\n * import delay from 'delay'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const input = [\n * async () => {\n * console.info('start 1')\n * await delay(500)\n *\n * console.info('end 1')\n * return 1\n * },\n * async () => {\n * console.info('start 2')\n * await delay(200)\n *\n * console.info('end 2')\n * return 2\n * },\n * async () => {\n * console.info('start 3')\n * await delay(100)\n *\n * console.info('end 3')\n * return 3\n * }\n * ]\n *\n * const result = await all(parallel(input, {\n * concurrency: 2\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [2, 3, 1]\n * ```\n *\n * If order is important, pass `ordered: true` as an option:\n *\n * ```javascript\n * const result = await all(parallel(input, {\n * concurrency: 2,\n * ordered: true\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [1, 2, 3]\n * ```\n */\n\nimport defer from 'p-defer'\n\ninterface Operation<T> {\n done: boolean\n ok: boolean\n err: Error\n value: T\n}\n\nconst CustomEvent = globalThis.CustomEvent ?? Event\n\nexport interface ParallelOptions {\n /**\n * How many jobs to execute in parallel (default: )\n */\n concurrency?: number\n ordered?: boolean\n}\n\n/**\n * Takes an (async) iterator that emits promise-returning functions,\n * invokes them in parallel and emits the results as they become available but\n * in the same order as the input\n */\nexport default async function * parallel <T> (source: Iterable<() => Promise<T>> | AsyncIterable<() => Promise<T>>, options: ParallelOptions = {}): AsyncGenerator<T, void, undefined> {\n let concurrency = options.concurrency ?? Infinity\n\n if (concurrency < 1) {\n concurrency = Infinity\n }\n\n const ordered = options.ordered ?? false\n const emitter = new EventTarget()\n\n const ops: Array<Operation<T>> = []\n let slotAvailable = defer()\n let resultAvailable = defer()\n let sourceFinished = false\n let sourceErr: Error | undefined\n let opErred = false\n\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve()\n })\n\n void Promise.resolve().then(async () => {\n try {\n for await (const task of source) {\n if (ops.length === concurrency) {\n slotAvailable = defer()\n await slotAvailable.promise\n }\n\n if (opErred) {\n break\n }\n\n const op: any = {\n done: false\n }\n ops.push(op)\n\n task()\n .then(result => {\n op.done = true\n op.ok = true\n op.value = result\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }, err => {\n op.done = true\n op.err = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n })\n }\n\n sourceFinished = true\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n } catch (err: any) {\n sourceErr = err\n emitter.dispatchEvent(new CustomEvent('task-complete'))\n }\n })\n\n function valuesAvailable (): boolean {\n if (ordered) {\n return ops[0]?.done\n }\n\n return Boolean(ops.find(op => op.done))\n }\n\n function * yieldOrderedValues (): Generator<T, void, unknown> {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0]\n ops.shift()\n\n if (op.ok) {\n yield op.value\n } else {\n // allow the source to exit\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n\n function * yieldUnOrderedValues (): Generator<T, void, unknown> {\n // more values can become available while we wait for `yield`\n // to return control to this function\n while (valuesAvailable()) {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].done) {\n const op = ops[i]\n ops.splice(i, 1)\n i--\n\n if (op.ok) {\n yield op.value\n } else {\n opErred = true\n slotAvailable.resolve()\n\n throw op.err\n }\n\n slotAvailable.resolve()\n }\n }\n }\n }\n\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer()\n await resultAvailable.promise\n }\n\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr\n }\n\n if (ordered) {\n yield * yieldOrderedValues()\n } else {\n yield * yieldUnOrderedValues()\n }\n\n if (sourceErr != null) {\n // if the source yields an array that is `yield *`, it can throw while the\n // onward consumer is processing the array contents - make sure we\n // propagate the error\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw sourceErr\n }\n\n if (sourceFinished && ops.length === 0) {\n // not waiting for any results and no more tasks so we are done\n break\n }\n }\n}\n", "import { NotFoundError } from '@libp2p/interface'\nimport { createScalableCuckooFilter } from '@libp2p/utils/filters'\nimport merge from 'it-merge'\nimport parallel from 'it-parallel'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { NoPeerRoutersError, QueriedForSelfError } from './errors.js'\nimport type { Logger, Metrics, PeerId, PeerInfo, PeerRouting, PeerStore, RoutingOptions } from '@libp2p/interface'\nimport type { ComponentLogger } from '@libp2p/logger'\n\nexport interface PeerRoutingInit {\n routers?: PeerRouting[]\n}\n\nexport interface DefaultPeerRoutingComponents {\n peerId: PeerId\n peerStore: PeerStore\n logger: ComponentLogger\n metrics?: Metrics\n}\n\nexport class DefaultPeerRouting implements PeerRouting {\n private readonly log: Logger\n private readonly peerId: PeerId\n private readonly peerStore: PeerStore\n private readonly routers: PeerRouting[]\n\n constructor (components: DefaultPeerRoutingComponents, init: PeerRoutingInit = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing')\n this.peerId = components.peerId\n this.peerStore = components.peerStore\n this.routers = init.routers ?? []\n\n this.findPeer = components.metrics?.traceFunction('libp2p.peerRouting.findPeer', this.findPeer.bind(this), {\n optionsIndex: 1,\n getAttributesFromArgs: ([peer], attrs) => {\n return {\n ...attrs,\n peer: peer.toString()\n }\n }\n }) ?? this.findPeer\n this.getClosestPeers = components.metrics?.traceFunction('libp2p.peerRouting.getClosestPeers', this.getClosestPeers.bind(this), {\n optionsIndex: 1,\n getAttributesFromArgs: ([key], attrs) => {\n return {\n ...attrs,\n key: uint8ArrayToString(key, 'base36')\n }\n },\n getAttributesFromYieldedValue: (value, attrs: { peers?: string[] }) => {\n return {\n ...attrs,\n peers: [...(Array.isArray(attrs.peers) ? attrs.peers : []), value.id.toString()]\n }\n }\n }) ?? this.getClosestPeers\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/peer-routing'\n\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer (id: PeerId, options?: RoutingOptions): Promise<PeerInfo> {\n if (this.routers.length === 0) {\n throw new NoPeerRoutersError('No peer routers available')\n }\n\n if (id.toString() === this.peerId.toString()) {\n throw new QueriedForSelfError('Should not try to find self')\n }\n\n const self = this\n const source = merge(\n ...this.routers\n .filter(router => router.findPeer instanceof Function)\n .map(router => (async function * () {\n try {\n yield await router.findPeer(id, options)\n } catch (err) {\n self.log.error(err)\n }\n })())\n )\n\n for await (const peer of source) {\n if (peer == null) {\n continue\n }\n\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n }\n\n return peer\n }\n\n throw new NotFoundError()\n }\n\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async * getClosestPeers (key: Uint8Array, options: RoutingOptions = {}): AsyncGenerator<PeerInfo> {\n if (this.routers.length === 0) {\n throw new NoPeerRoutersError('No peer routers available')\n }\n\n const self = this\n const seen = createScalableCuckooFilter(1024)\n\n for await (const peer of parallel(\n async function * () {\n const source = merge(\n ...self.routers\n .filter(router => router.getClosestPeers instanceof Function)\n .map(router => router.getClosestPeers(key, options))\n )\n\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n })\n } catch (err) {\n self.log.error('could not find peer multiaddrs', err)\n return\n }\n }\n\n return peer\n }\n }\n }()\n )) {\n if (peer == null) {\n continue\n }\n\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n }\n\n // deduplicate peers\n if (seen.has(peer.id.toMultihash().bytes)) {\n continue\n }\n\n seen.add(peer.id.toMultihash().bytes)\n\n yield peer\n }\n }\n}\n", "import { randomBytes } from '@libp2p/crypto'\nimport { TypedEventEmitter, setMaxListeners } from '@libp2p/interface'\nimport { anySignal } from 'any-signal'\nimport pDefer, { type DeferredPromise } from 'p-defer'\nimport { raceEvent } from 'race-event'\nimport { raceSignal } from 'race-signal'\nimport type { AbortOptions, ComponentLogger, Logger, PeerInfo, PeerRouting, Startable } from '@libp2p/interface'\nimport type { RandomWalk as RandomWalkInterface } from '@libp2p/interface-internal'\n\nexport interface RandomWalkComponents {\n peerRouting: PeerRouting\n logger: ComponentLogger\n}\n\ninterface RandomWalkEvents {\n 'walk:peer': CustomEvent<PeerInfo>\n 'walk:error': CustomEvent<Error>\n}\n\nexport class RandomWalk extends TypedEventEmitter<RandomWalkEvents> implements RandomWalkInterface, Startable {\n private readonly peerRouting: PeerRouting\n private readonly log: Logger\n private walking: boolean\n private walkers: number\n private shutdownController: AbortController\n private walkController?: AbortController\n private needNext?: DeferredPromise<void>\n\n constructor (components: RandomWalkComponents) {\n super()\n\n this.log = components.logger.forComponent('libp2p:random-walk')\n this.peerRouting = components.peerRouting\n this.walkers = 0\n this.walking = false\n\n // stops any in-progress walks when the node is shut down\n this.shutdownController = new AbortController()\n setMaxListeners(Infinity, this.shutdownController.signal)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/random-walk'\n\n start (): void {\n this.shutdownController = new AbortController()\n setMaxListeners(Infinity, this.shutdownController.signal)\n }\n\n stop (): void {\n this.shutdownController.abort()\n }\n\n async * walk (options?: AbortOptions): AsyncGenerator<PeerInfo> {\n if (!this.walking) {\n // start the query that causes walk:peer events to be emitted\n this.startWalk()\n }\n\n this.walkers++\n const signal = anySignal([this.shutdownController.signal, options?.signal])\n setMaxListeners(Infinity, signal)\n\n try {\n while (true) {\n // if another consumer has paused the query, start it again\n this.needNext?.resolve()\n this.needNext = pDefer()\n\n // wait for a walk:peer or walk:error event\n const event = await raceEvent<CustomEvent<PeerInfo>>(this, 'walk:peer', signal, {\n errorEvent: 'walk:error'\n })\n\n yield event.detail\n }\n } finally {\n signal.clear()\n this.walkers--\n\n // stop the walk if no more consumers are interested\n if (this.walkers === 0) {\n this.walkController?.abort()\n this.walkController = undefined\n }\n }\n }\n\n private startWalk (): void {\n this.walking = true\n\n // the signal for this controller will be aborted if no more random peers\n // are required\n this.walkController = new AbortController()\n setMaxListeners(Infinity, this.walkController.signal)\n\n const signal = anySignal([this.walkController.signal, this.shutdownController.signal])\n setMaxListeners(Infinity, signal)\n\n const start = Date.now()\n let found = 0\n\n Promise.resolve().then(async () => {\n this.log('start walk')\n\n // find peers until no more consumers are interested\n while (this.walkers > 0) {\n try {\n const data = randomBytes(32)\n let s = Date.now()\n\n for await (const peer of this.peerRouting.getClosestPeers(data, { signal })) {\n if (signal.aborted) {\n this.log('aborting walk')\n }\n\n signal.throwIfAborted()\n\n this.log('found peer %p after %dms for %d walkers', peer.id, Date.now() - s, this.walkers)\n found++\n this.safeDispatchEvent('walk:peer', {\n detail: peer\n })\n\n // if we only have one consumer, pause the query until they request\n // another random peer or they signal they are no longer interested\n if (this.walkers === 1 && this.needNext != null) {\n this.log('wait for need next')\n await raceSignal(this.needNext.promise, signal)\n }\n\n s = Date.now()\n }\n\n this.log('walk iteration for %b and %d walkers finished, found %d peers', data, this.walkers, found)\n } catch (err) {\n this.log.error('random walk errored', err)\n\n this.safeDispatchEvent('walk:error', {\n detail: err\n })\n }\n }\n\n this.log('no walkers left, ended walk')\n })\n .catch(err => {\n this.log.error('random walk errored', err)\n })\n .finally(() => {\n this.log('finished walk, found %d peers after %dms', found, Date.now() - start)\n this.walking = false\n })\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport merge from 'merge-options'\nimport * as errorsJs from './errors.js'\nimport type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, TypedEventTarget, PeerId, PeerStore, Topology, StreamHandler, StreamHandlerRecord, StreamHandlerOptions } from '@libp2p/interface'\nimport type { Registrar as RegistrarInterface } from '@libp2p/interface-internal'\nimport type { ComponentLogger } from '@libp2p/logger'\n\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64\n\nexport interface RegistrarComponents {\n peerId: PeerId\n peerStore: PeerStore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class Registrar implements RegistrarInterface {\n private readonly log: Logger\n private readonly topologies: Map<string, Map<string, Topology>>\n private readonly handlers: Map<string, StreamHandlerRecord>\n private readonly components: RegistrarComponents\n\n constructor (components: RegistrarComponents) {\n this.log = components.logger.forComponent('libp2p:registrar')\n this.topologies = new Map()\n this.handlers = new Map()\n this.components = components\n\n this._onDisconnect = this._onDisconnect.bind(this)\n this._onPeerUpdate = this._onPeerUpdate.bind(this)\n this._onPeerIdentify = this._onPeerIdentify.bind(this)\n\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect)\n this.components.events.addEventListener('peer:update', this._onPeerUpdate)\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/registrar'\n\n getProtocols (): string[] {\n return Array.from(new Set<string>([\n ...this.handlers.keys()\n ])).sort()\n }\n\n getHandler (protocol: string): StreamHandlerRecord {\n const handler = this.handlers.get(protocol)\n\n if (handler == null) {\n throw new errorsJs.UnhandledProtocolError(`No handler registered for protocol ${protocol}`)\n }\n\n return handler\n }\n\n getTopologies (protocol: string): Topology[] {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n return []\n }\n\n return [\n ...topologies.values()\n ]\n }\n\n /**\n * Registers the `handler` for each protocol\n */\n async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise<void> {\n if (this.handlers.has(protocol) && opts?.force !== true) {\n throw new errorsJs.DuplicateProtocolHandlerError(`Handler already registered for protocol ${protocol}`)\n }\n\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts)\n\n this.handlers.set(protocol, {\n handler,\n options\n })\n\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n })\n }\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle (protocols: string | string[]): Promise<void> {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols]\n\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol)\n })\n\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n })\n }\n\n /**\n * Register handlers for a set of multicodecs given\n */\n async register (protocol: string, topology: Topology): Promise<string> {\n if (topology == null) {\n throw new InvalidParametersError('invalid topology')\n }\n\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`\n\n let topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n topologies = new Map<string, Topology>()\n this.topologies.set(protocol, topologies)\n }\n\n topologies.set(id, topology)\n\n return id\n }\n\n /**\n * Unregister topology\n */\n unregister (id: string): void {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id)\n\n if (topologies.size === 0) {\n this.topologies.delete(protocol)\n }\n }\n }\n }\n\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect (evt: CustomEvent<PeerId>): void {\n const remotePeer = evt.detail\n\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n if (topology.filter?.has(remotePeer) === false) {\n continue\n }\n\n topology.filter?.remove(remotePeer)\n topology.onDisconnect?.(remotePeer)\n }\n }\n })\n .catch(err => {\n if (err.name === 'NotFoundError') {\n // peer has not completed identify so they are not in the peer store\n return\n }\n\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err)\n })\n }\n\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate (evt: CustomEvent<PeerUpdate>): void {\n const { peer, previous } = evt.detail\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol))\n\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n if (topology.filter?.has(peer.id) === false) {\n continue\n }\n\n topology.filter?.remove(peer.id)\n topology.onDisconnect?.(peer.id)\n }\n }\n }\n\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify (evt: CustomEvent<IdentifyResult>): void {\n const protocols = evt.detail.protocols\n const connection = evt.detail.connection\n const peerId = evt.detail.peerId\n\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol)\n\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue\n }\n\n for (const topology of topologies.values()) {\n if (connection.limits != null && topology.notifyOnLimitedConnection !== true) {\n continue\n }\n\n if (topology.filter?.has(peerId) === true) {\n continue\n }\n\n topology.filter?.add(peerId)\n topology.onConnect?.(peerId, connection)\n }\n }\n }\n}\n", "import type { Metric, Metrics } from '@libp2p/interface'\n\nexport interface TrackedMapInit {\n name: string\n metrics: Metrics\n}\n\nclass TrackedMap<K, V> extends Map<K, V> {\n private readonly metric: Metric\n\n constructor (init: TrackedMapInit) {\n super()\n\n const { name, metrics } = init\n\n this.metric = metrics.registerMetric(name)\n this.updateComponentMetric()\n }\n\n set (key: K, value: V): this {\n super.set(key, value)\n this.updateComponentMetric()\n return this\n }\n\n delete (key: K): boolean {\n const deleted = super.delete(key)\n this.updateComponentMetric()\n return deleted\n }\n\n clear (): void {\n super.clear()\n this.updateComponentMetric()\n }\n\n private updateComponentMetric (): void {\n this.metric.update(this.size)\n }\n}\n\nexport interface CreateTrackedMapInit {\n /**\n * The metric name to use\n */\n name: string\n\n /**\n * A metrics implementation\n */\n metrics?: Metrics\n}\n\nexport function trackedMap <K, V> (config: CreateTrackedMapInit): Map<K, V> {\n const { name, metrics } = config\n let map: Map<K, V>\n\n if (metrics != null) {\n map = new TrackedMap<K, V>({ name, metrics })\n } else {\n map = new Map<K, V>()\n }\n\n return map\n}\n", "import { FaultTolerance, InvalidParametersError, NotStartedError } from '@libp2p/interface'\nimport { trackedMap } from '@libp2p/utils/tracked-map'\nimport { IP4, IP6 } from '@multiformats/multiaddr-matcher'\nimport { CustomProgressEvent } from 'progress-events'\nimport { TransportUnavailableError, UnsupportedListenAddressError, UnsupportedListenAddressesError } from './errors.js'\nimport type { Libp2pEvents, ComponentLogger, Logger, Connection, TypedEventTarget, Metrics, Startable, Listener, Transport, Upgrader } from '@libp2p/interface'\nimport type { AddressManager, TransportManager, TransportManagerDialOptions } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface TransportManagerInit {\n faultTolerance?: FaultTolerance\n}\n\nexport interface DefaultTransportManagerComponents {\n metrics?: Metrics\n addressManager: AddressManager\n upgrader: Upgrader\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\ninterface IPStats {\n success: number\n attempts: number\n}\n\ninterface ListenStats {\n errors: Map<string, Error>\n ipv4: IPStats\n ipv6: IPStats\n}\n\nexport class DefaultTransportManager implements TransportManager, Startable {\n private readonly log: Logger\n private readonly components: DefaultTransportManagerComponents\n private readonly transports: Map<string, Transport>\n private readonly listeners: Map<string, Listener[]>\n private readonly faultTolerance: FaultTolerance\n private started: boolean\n\n constructor (components: DefaultTransportManagerComponents, init: TransportManagerInit = {}) {\n this.log = components.logger.forComponent('libp2p:transports')\n this.components = components\n this.started = false\n this.transports = new Map<string, Transport>()\n this.listeners = trackedMap({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n })\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/transport-manager'\n\n /**\n * Adds a `Transport` to the manager\n */\n add (transport: Transport): void {\n const tag = transport[Symbol.toStringTag]\n\n if (tag == null) {\n throw new InvalidParametersError('Transport must have a valid tag')\n }\n\n if (this.transports.has(tag)) {\n throw new InvalidParametersError(`There is already a transport with the tag ${tag}`)\n }\n\n this.log('adding transport %s', tag)\n\n this.transports.set(tag, transport)\n\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, [])\n }\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n start (): void {\n this.started = true\n }\n\n async afterStart (): Promise<void> {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs()\n\n await this.listen(addrs)\n }\n\n /**\n * Stops all listeners\n */\n async stop (): Promise<void> {\n const tasks = []\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n }\n\n await Promise.all(tasks)\n this.log('all listeners closed')\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, [])\n }\n\n this.started = false\n }\n\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial (ma: Multiaddr, options?: TransportManagerDialOptions): Promise<Connection> {\n const transport = this.dialTransportForMultiaddr(ma)\n\n if (transport == null) {\n throw new TransportUnavailableError(`No transport available for address ${String(ma)}`)\n }\n\n options?.onProgress?.(new CustomProgressEvent<string>('transport-manager:selected-transport', transport[Symbol.toStringTag]))\n\n // @ts-expect-error the transport has a typed onProgress option but we\n // can't predict what transport implementation we selected so all we can\n // do is pass the onProgress handler in and hope for the best\n return transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n })\n }\n\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs (): Multiaddr[] {\n let addrs: Multiaddr[] = []\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()]\n }\n }\n return addrs\n }\n\n /**\n * Returns all the transports instances\n */\n getTransports (): Transport[] {\n return Array.of(...this.transports.values())\n }\n\n /**\n * Returns all the listener instances\n */\n getListeners (): Listener[] {\n return Array.of(...this.listeners.values()).flat()\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n dialTransportForMultiaddr (ma: Multiaddr): Transport | undefined {\n for (const transport of this.transports.values()) {\n const addrs = transport.dialFilter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Finds a transport that matches the given Multiaddr\n */\n listenTransportForMultiaddr (ma: Multiaddr): Transport | undefined {\n for (const transport of this.transports.values()) {\n const addrs = transport.listenFilter([ma])\n\n if (addrs.length > 0) {\n return transport\n }\n }\n }\n\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen (addrs: Multiaddr[]): Promise<void> {\n if (!this.isStarted()) {\n throw new NotStartedError('Not started')\n }\n\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only')\n return\n }\n\n // track IPv4/IPv6 results - if we succeed on IPv4 but all IPv6 attempts\n // fail then we are probably on a network without IPv6 support\n const listenStats: ListenStats = {\n errors: new Map(),\n ipv4: {\n success: 0,\n attempts: 0\n },\n ipv6: {\n success: 0,\n attempts: 0\n }\n }\n\n addrs.forEach(ma => {\n listenStats.errors.set(ma.toString(), new UnsupportedListenAddressError())\n })\n\n const tasks: Array<Promise<void>> = []\n\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.listenFilter(addrs)\n\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr)\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n })\n\n let listeners: Listener[] = this.listeners.get(key) ?? []\n\n if (listeners == null) {\n listeners = []\n this.listeners.set(key, listeners)\n }\n\n listeners.push(listener)\n\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n })\n })\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener)\n\n // remove the listener\n listeners.splice(index, 1)\n\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n })\n })\n\n // track IPv4/IPv6 support\n if (IP4.matches(addr)) {\n listenStats.ipv4.attempts++\n } else if (IP6.matches(addr)) {\n listenStats.ipv6.attempts++\n }\n\n // We need to attempt to listen on everything\n tasks.push(\n listener.listen(addr)\n .then(() => {\n listenStats.errors.delete(addr.toString())\n\n if (IP4.matches(addr)) {\n listenStats.ipv4.success++\n }\n\n if (IP6.matches(addr)) {\n listenStats.ipv6.success++\n }\n }, (err) => {\n this.log.error('transport %s could not listen on address %a - %e', key, addr, err)\n listenStats.errors.set(addr.toString(), err)\n throw err\n })\n )\n }\n }\n\n const results = await Promise.allSettled(tasks)\n\n // listening on all addresses, all good\n if (results.length > 0 && results.every(res => res.status === 'fulfilled')) {\n return\n }\n\n // detect lack of IPv6 support on the current network - if we tried to\n // listen on IPv4 and IPv6 addresses, and all IPv4 addresses succeeded but\n // all IPv6 addresses fail, then we can assume there's no IPv6 here\n if (this.ipv6Unsupported(listenStats)) {\n this.log('all IPv4 addresses succeed but all IPv6 failed')\n return\n }\n\n if (this.faultTolerance === FaultTolerance.NO_FATAL) {\n // ok to be dial-only\n this.log('failed to listen on any address but fault tolerance allows this')\n return\n }\n\n // if a configured address was not able to be listened on, throw an error\n throw new UnsupportedListenAddressesError(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \\`transportManager.faultTolerance\\` to NO_FATAL:\\n${\n [...listenStats.errors.entries()].map(([addr, err]) => {\n return `\n ${addr}: ${`${err.stack ?? err}`.split('\\n').join('\\n ')}\n`\n }).join('')\n }`)\n }\n\n private ipv6Unsupported (listenStats: ListenStats): boolean {\n if (listenStats.ipv4.attempts === 0 || listenStats.ipv6.attempts === 0) {\n return false\n }\n\n const allIpv4Succeeded = listenStats.ipv4.attempts === listenStats.ipv4.success\n const allIpv6Failed = listenStats.ipv6.success === 0\n\n return allIpv4Succeeded && allIpv6Failed\n }\n\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove (key: string): Promise<void> {\n const listeners = this.listeners.get(key) ?? []\n this.log.trace('removing transport %s', key)\n\n // Close any running listeners\n const tasks = []\n this.log.trace('closing listeners for %s', key)\n while (listeners.length > 0) {\n const listener = listeners.pop()\n\n if (listener == null) {\n continue\n }\n\n tasks.push(listener.close())\n }\n await Promise.all(tasks)\n\n this.transports.delete(key)\n this.listeners.delete(key)\n }\n\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll (): Promise<void> {\n const tasks = []\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key))\n }\n\n await Promise.all(tasks)\n }\n}\n", "export const PROTOCOL_ID = '/multistream/1.0.0'\n\n// Conforming to go-libp2p\n// See https://github.com/multiformats/go-multistream/blob/master/multistream.go#L297\nexport const MAX_PROTOCOL_LENGTH = 1024\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 * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\nimport { byteStream } from 'it-byte-stream'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError } from './errors.js'\nimport type { AbortOptions } from 'abort-error'\nimport type { ByteStreamOpts } from 'it-byte-stream'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface LengthPrefixedStream <Stream = unknown> {\n /**\n * Read the next length-prefixed number of bytes from the stream\n */\n read(options?: AbortOptions): Promise<Uint8ArrayList>\n\n /**\n * Write the passed bytes to the stream prefixed by their length\n */\n write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>\n\n /**\n * Write passed list of bytes, prefix by their individual lengths to the stream as a single write\n */\n writeV(input: Array<Uint8Array | Uint8ArrayList>, options?: AbortOptions): Promise<void>\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\nexport interface LengthPrefixedStreamOpts extends ByteStreamOpts {\n // encoding opts\n lengthEncoder (value: number): Uint8ArrayList | Uint8Array\n\n // decoding opts\n lengthDecoder (data: Uint8ArrayList): number\n maxLengthLength: number\n maxDataLength: number\n}\n\nexport function lpStream <Stream extends Duplex<any, any, any>> (duplex: Stream, opts: Partial<LengthPrefixedStreamOpts> = {}): LengthPrefixedStream<Stream> {\n const bytes = byteStream(duplex, opts)\n\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength)\n }\n\n const decodeLength = opts?.lengthDecoder ?? varint.decode\n const encodeLength = opts?.lengthEncoder ?? varint.encode\n\n const W: LengthPrefixedStream<Stream> = {\n read: async (options?: AbortOptions) => {\n let dataLength: number = -1\n const lengthBuffer = new Uint8ArrayList()\n\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read({\n ...options,\n bytes: 1\n }))\n\n try {\n dataLength = decodeLength(lengthBuffer)\n } catch (err) {\n if (err instanceof RangeError) {\n continue\n }\n\n throw err\n }\n\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length')\n }\n\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new InvalidDataLengthLengthError('message length length too long')\n }\n\n if (dataLength > -1) {\n break\n }\n }\n\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new InvalidDataLengthError('message length too long')\n }\n\n return bytes.read({\n ...options,\n bytes: dataLength\n })\n },\n write: async (data, options?: AbortOptions) => {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options)\n },\n writeV: async (data, options?: AbortOptions) => {\n const list = new Uint8ArrayList(\n ...data.flatMap(buf => ([encodeLength(buf.byteLength), buf]))\n )\n\n // encode, write\n await bytes.write(list, options)\n },\n unwrap: () => {\n return bytes.unwrap()\n }\n }\n\n return W\n}\n", "import { InvalidMessageError } from '@libp2p/interface'\nimport { type Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { AbortOptions, LoggerOptions } from '@libp2p/interface'\nimport type { LengthPrefixedStream } from 'it-length-prefixed-stream'\nimport type { Duplex, Source } from 'it-stream-types'\n\nconst NewLine = uint8ArrayFromString('\\n')\n\n/**\n * `write` encodes and writes a single buffer\n */\nexport async function write (writer: LengthPrefixedStream<Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>, Source<Uint8Array>>>, buffer: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void> {\n await writer.write(buffer, options)\n}\n\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport async function writeAll (writer: LengthPrefixedStream<Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>, Source<Uint8Array>>>, buffers: Uint8Array[], options?: AbortOptions): Promise<void> {\n await writer.writeV(buffers, options)\n}\n\n/**\n * Read a length-prefixed buffer from the passed stream, stripping the final newline character\n */\nexport async function read (reader: LengthPrefixedStream<Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>, Source<Uint8Array>>>, options: AbortOptions & LoggerOptions): Promise<Uint8ArrayList> {\n const buf = await reader.read(options)\n\n if (buf.byteLength === 0 || buf.get(buf.byteLength - 1) !== NewLine[0]) {\n options.log.error('Invalid mss message - missing newline', buf)\n throw new InvalidMessageError('Missing newline')\n }\n\n return buf.sublist(0, -1) // Remove newline\n}\n\n/**\n * Read a length-prefixed string from the passed stream, stripping the final newline character\n */\nexport async function readString (reader: LengthPrefixedStream<Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>, Source<Uint8Array>>>, options: AbortOptions & LoggerOptions): Promise<string> {\n const buf = await read(reader, options)\n\n return uint8ArrayToString(buf.subarray())\n}\n", "import { UnsupportedProtocolError } from '@libp2p/interface'\nimport { lpStream } from 'it-length-prefixed-stream'\nimport pDefer from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport * as varint from 'uint8-varint'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { MAX_PROTOCOL_LENGTH } from './constants.js'\nimport * as multistream from './multistream.js'\nimport { PROTOCOL_ID } from './index.js'\nimport type { MultistreamSelectInit, ProtocolStream } from './index.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface SelectStream extends Duplex<any, any, any> {\n readStatus?: string\n closeWrite?(options?: AbortOptions): Promise<void>\n closeRead?(options?: AbortOptions): Promise<void>\n close?(options?: AbortOptions): Promise<void>\n}\n\n/**\n * Negotiate a protocol to use from a list of protocols.\n *\n * @param stream - A duplex iterable stream to dial on\n * @param protocols - A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made.\n * @param options - An options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`.\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex()\n * const muxedStream = muxer.newStream()\n *\n * // mss.select(protocol(s))\n * // Select from one of the passed protocols (in priority order)\n * // Returns selected stream and protocol\n * const { stream: dhtStream, protocol } = await mss.select(muxedStream, [\n * // This might just be different versions of DHT, but could be different implementations\n * '/ipfs-dht/2.0.0', // Most of the time this will probably just be one item.\n * '/ipfs-dht/1.0.0'\n * ])\n *\n * // Typically this stream will be passed back to the caller of libp2p.dialProtocol\n * //\n * // ...it might then do something like this:\n * // try {\n * // await pipe(\n * // [uint8ArrayFromString('Some DHT data')]\n * // dhtStream,\n * // async source => {\n * // for await (const chunk of source)\n * // // DHT response data\n * // }\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * ```\n */\nexport async function select <Stream extends SelectStream> (stream: Stream, protocols: string | string[], options: MultistreamSelectInit): Promise<ProtocolStream<Stream>> {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols]\n\n if (protocols.length === 1 && options.negotiateFully === false) {\n return optimisticSelect(stream, protocols[0], options)\n }\n\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n })\n const protocol = protocols.shift()\n\n if (protocol == null) {\n throw new Error('At least one protocol must be specified')\n }\n\n options.log.trace('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol)\n const p1 = uint8ArrayFromString(`${PROTOCOL_ID}\\n`)\n const p2 = uint8ArrayFromString(`${protocol}\\n`)\n await multistream.writeAll(lp, [p1, p2], options)\n\n options.log.trace('select: reading multistream-select header')\n let response = await multistream.readString(lp, options)\n options.log.trace('select: read \"%s\"', response)\n\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n options.log.trace('select: reading protocol response')\n response = await multistream.readString(lp, options)\n options.log.trace('select: read \"%s\"', response)\n }\n\n // We're done\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol }\n }\n\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n options.log.trace('select: write \"%s\"', protocol)\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options)\n options.log.trace('select: reading protocol response')\n const response = await multistream.readString(lp, options)\n options.log.trace('select: read \"%s\" for \"%s\"', response, protocol)\n\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol }\n }\n }\n\n throw new UnsupportedProtocolError('protocol selection failed')\n}\n\n/**\n * Optimistically negotiates a protocol.\n *\n * It *does not* block writes waiting for the other end to respond. Instead, it\n * simply assumes the negotiation went successfully and starts writing data.\n *\n * Use when it is known that the receiver supports the desired protocol.\n */\nfunction optimisticSelect <Stream extends SelectStream> (stream: Stream, protocol: string, options: MultistreamSelectInit): ProtocolStream<Stream> {\n const originalSink = stream.sink.bind(stream)\n const originalSource = stream.source\n\n let negotiated = false\n let negotiating = false\n const doneNegotiating = pDefer()\n\n let sentProtocol = false\n let sendingProtocol = false\n const doneSendingProtocol = pDefer()\n\n let readProtocol = false\n let readingProtocol = false\n const doneReadingProtocol = pDefer()\n\n const lp = lpStream({\n sink: originalSink,\n source: originalSource\n }, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n })\n\n stream.sink = async source => {\n const { sink } = lp.unwrap()\n\n await sink(async function * () {\n let sentData = false\n\n for await (const buf of source) {\n // started reading before the source yielded, wait for protocol send\n if (sendingProtocol) {\n await doneSendingProtocol.promise\n }\n\n // writing before reading, send the protocol and the first chunk of data\n if (!sentProtocol) {\n sendingProtocol = true\n\n options.log.trace('optimistic: write [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength)\n\n const protocolString = `${protocol}\\n`\n\n // send protocols in first chunk of data written to transport\n yield new Uint8ArrayList(\n Uint8Array.from([19]), // length of PROTOCOL_ID plus newline\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n varint.encode(protocolString.length),\n uint8ArrayFromString(protocolString),\n buf\n ).subarray()\n\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength)\n\n sentProtocol = true\n sendingProtocol = false\n doneSendingProtocol.resolve()\n\n // read the negotiation response but don't block more sending\n negotiate()\n .catch(err => {\n options.log.error('could not finish optimistic protocol negotiation of %s', protocol, err)\n })\n } else {\n yield buf\n }\n\n sentData = true\n }\n\n // special case - the source passed to the sink has ended but we didn't\n // negotiated the protocol yet so do it now\n if (!sentData) {\n await negotiate()\n }\n }())\n }\n\n async function negotiate (): Promise<void> {\n if (negotiating) {\n options.log.trace('optimistic: already negotiating %s stream', protocol)\n await doneNegotiating.promise\n return\n }\n\n negotiating = true\n\n try {\n // we haven't sent the protocol yet, send it now\n if (!sentProtocol) {\n options.log.trace('optimistic: doing send protocol for %s stream', protocol)\n await doSendProtocol()\n }\n\n // if we haven't read the protocol response yet, do it now\n if (!readProtocol) {\n options.log.trace('optimistic: doing read protocol for %s stream', protocol)\n await doReadProtocol()\n }\n } finally {\n negotiating = false\n negotiated = true\n doneNegotiating.resolve()\n }\n }\n\n async function doSendProtocol (): Promise<void> {\n if (sendingProtocol) {\n await doneSendingProtocol.promise\n return\n }\n\n sendingProtocol = true\n\n try {\n options.log.trace('optimistic: write [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol)\n await lp.writeV([\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n uint8ArrayFromString(`${protocol}\\n`)\n ])\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol)\n } finally {\n sentProtocol = true\n sendingProtocol = false\n doneSendingProtocol.resolve()\n }\n }\n\n async function doReadProtocol (): Promise<void> {\n if (readingProtocol) {\n await doneReadingProtocol.promise\n return\n }\n\n readingProtocol = true\n\n try {\n options.log.trace('optimistic: reading multistream select header')\n let response = await multistream.readString(lp, options)\n options.log.trace('optimistic: read multistream select header \"%s\"', response)\n\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(lp, options)\n }\n\n options.log.trace('optimistic: read protocol \"%s\", expecting \"%s\"', response, protocol)\n\n if (response !== protocol) {\n throw new UnsupportedProtocolError('protocol selection failed')\n }\n } finally {\n readProtocol = true\n readingProtocol = false\n doneReadingProtocol.resolve()\n }\n }\n\n stream.source = (async function * () {\n // make sure we've done protocol negotiation before we read stream data\n await negotiate()\n\n options.log.trace('optimistic: reading data from \"%s\" stream', protocol)\n yield * lp.unwrap().source\n })()\n\n if (stream.closeRead != null) {\n const originalCloseRead = stream.closeRead.bind(stream)\n\n stream.closeRead = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the readable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close read', err)\n })\n }\n\n // protocol has been negotiated, ok to close the readable end\n await originalCloseRead(opts)\n }\n }\n\n if (stream.closeWrite != null) {\n const originalCloseWrite = stream.closeWrite.bind(stream)\n\n stream.closeWrite = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the writable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close write', err)\n })\n }\n\n // protocol has been negotiated, ok to close the writable end\n await originalCloseWrite(opts)\n }\n }\n\n if (stream.close != null) {\n const originalClose = stream.close.bind(stream)\n\n stream.close = async (opts) => {\n // if we are in the process of negotiation, let it finish before closing\n // because we may have unsent early data\n const tasks = []\n\n if (sendingProtocol) {\n tasks.push(doneSendingProtocol.promise)\n }\n\n if (readingProtocol) {\n tasks.push(doneReadingProtocol.promise)\n }\n\n if (tasks.length > 0) {\n // let the in-flight protocol negotiation finish gracefully\n await raceSignal(\n Promise.all(tasks),\n opts?.signal\n )\n } else {\n // no protocol negotiation attempt has occurred so don't start one\n negotiated = true\n negotiating = false\n doneNegotiating.resolve()\n }\n\n // protocol has been negotiated, ok to close the writable end\n await originalClose(opts)\n }\n }\n\n return {\n stream,\n protocol\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 { encode } from 'it-length-prefixed'\nimport { lpStream } from 'it-length-prefixed-stream'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { MAX_PROTOCOL_LENGTH, PROTOCOL_ID } from './constants.js'\nimport * as multistream from './multistream.js'\nimport type { MultistreamSelectInit, ProtocolStream } from './index.js'\nimport type { Duplex } from 'it-stream-types'\n\n/**\n * Handle multistream protocol selections for the given list of protocols.\n *\n * Note that after a protocol is handled `listener` can no longer be used.\n *\n * @param stream - A duplex iterable stream to listen on\n * @param protocols - A list of protocols (or single protocol) that this listener is able to speak.\n * @param options - an options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex({\n * async onStream (muxedStream) {\n * // mss.handle(handledProtocols)\n * // Returns selected stream and protocol\n * const { stream, protocol } = await mss.handle(muxedStream, [\n * '/ipfs-dht/1.0.0',\n * '/ipfs-bitswap/1.0.0'\n * ])\n *\n * // Typically here we'd call the handler function that was registered in\n * // libp2p for the given protocol:\n * // e.g. handlers[protocol].handler(stream)\n * //\n * // If protocol was /ipfs-dht/1.0.0 it might do something like this:\n * // try {\n * // await pipe(\n * // dhtStream,\n * // source => (async function * () {\n * // for await (const chunk of source)\n * // // Incoming DHT data -> process and yield to respond\n * // })(),\n * // dhtStream\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * }\n * })\n * ```\n */\nexport async function handle <Stream extends Duplex<any, any, any>> (stream: Stream, protocols: string | string[], options: MultistreamSelectInit): Promise<ProtocolStream<Stream>> {\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n options.log.trace('handle: available protocols %s', protocols)\n\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH,\n maxLengthLength: 2 // 2 bytes is enough to length-prefix MAX_PROTOCOL_LENGTH\n })\n\n while (true) {\n options.log.trace('handle: reading incoming string')\n const protocol = await multistream.readString(lp, options)\n options.log.trace('handle: read \"%s\"', protocol)\n\n if (protocol === PROTOCOL_ID) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n await multistream.write(lp, uint8ArrayFromString(`${PROTOCOL_ID}\\n`), options)\n options.log.trace('handle: responded with \"%s\" for \"%s\"', PROTOCOL_ID, protocol)\n continue\n }\n\n if (protocols.includes(protocol)) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', protocol, protocol)\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options)\n options.log.trace('handle: responded with \"%s\" for \"%s\"', protocol, protocol)\n\n return { stream: lp.unwrap(), protocol }\n }\n\n if (protocol === 'ls') {\n // <varint-msg-len><varint-proto-name-len><proto-name>\\n<varint-proto-name-len><proto-name>\\n\\n\n const protos = new Uint8ArrayList(\n ...protocols.map(p => encode.single(uint8ArrayFromString(`${p}\\n`))),\n uint8ArrayFromString('\\n')\n )\n\n options.log.trace('handle: respond with \"%s\" for %s', protocols, protocol)\n await multistream.write(lp, protos, options)\n options.log.trace('handle: responded with \"%s\" for %s', protocols, protocol)\n continue\n }\n\n options.log.trace('handle: respond with \"na\" for \"%s\"', protocol)\n await multistream.write(lp, uint8ArrayFromString('na\\n'), options)\n options.log('handle: responded with \"na\" for \"%s\"', protocol)\n }\n}\n", "import { connectionSymbol, setMaxListeners, LimitedConnectionError, ConnectionClosedError, ConnectionClosingError } from '@libp2p/interface'\nimport type { AbortOptions, Logger, ComponentLogger, Direction, Connection, Stream, ConnectionTimeline, ConnectionStatus, NewStreamOptions, PeerId, ConnectionLimits } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nconst CLOSE_TIMEOUT = 500\n\ninterface ConnectionInit {\n remoteAddr: Multiaddr\n remotePeer: PeerId\n newStream(protocols: string[], options?: AbortOptions): Promise<Stream>\n close(options?: AbortOptions): Promise<void>\n abort(err: Error): void\n getStreams(): Stream[]\n status: ConnectionStatus\n direction: Direction\n timeline: ConnectionTimeline\n multiplexer?: string\n encryption?: string\n limits?: ConnectionLimits\n logger: ComponentLogger\n}\n\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl implements Connection {\n /**\n * Connection identifier.\n */\n public readonly id: string\n\n /**\n * Observed multiaddr of the remote peer\n */\n public readonly remoteAddr: Multiaddr\n\n /**\n * Remote peer id\n */\n public readonly remotePeer: PeerId\n\n public direction: Direction\n public timeline: ConnectionTimeline\n public multiplexer?: string\n public encryption?: string\n public status: ConnectionStatus\n public limits?: ConnectionLimits\n public readonly log: Logger\n\n /**\n * User provided tags\n *\n */\n public tags: string[]\n\n /**\n * Reference to the new stream function of the multiplexer\n */\n private readonly _newStream: (protocols: string[], options?: NewStreamOptions) => Promise<Stream>\n\n /**\n * Reference to the close function of the raw connection\n */\n private readonly _close: (options?: AbortOptions) => Promise<void>\n\n private readonly _abort: (err: Error) => void\n\n /**\n * Reference to the getStreams function of the muxer\n */\n private readonly _getStreams: () => Stream[]\n\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor (init: ConnectionInit) {\n const { remoteAddr, remotePeer, newStream, close, abort, getStreams } = init\n\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`\n this.remoteAddr = remoteAddr\n this.remotePeer = remotePeer\n this.direction = init.direction\n this.status = 'open'\n this.timeline = init.timeline\n this.multiplexer = init.multiplexer\n this.encryption = init.encryption\n this.limits = init.limits\n this.log = init.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`)\n\n if (this.remoteAddr.getPeerId() == null) {\n this.remoteAddr = this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)\n }\n\n this._newStream = newStream\n this._close = close\n this._abort = abort\n this._getStreams = getStreams\n this.tags = []\n }\n\n readonly [Symbol.toStringTag] = 'Connection'\n\n readonly [connectionSymbol] = true\n\n /**\n * Get all the streams of the muxer\n */\n get streams (): Stream[] {\n return this._getStreams()\n }\n\n /**\n * Create a new stream from this connection\n */\n async newStream (protocols: string | string[], options?: NewStreamOptions): Promise<Stream> {\n if (this.status === 'closing') {\n throw new ConnectionClosingError('the connection is being closed')\n }\n\n if (this.status === 'closed') {\n throw new ConnectionClosedError('the connection is closed')\n }\n\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n if (this.limits != null && options?.runOnLimitedConnection !== true) {\n throw new LimitedConnectionError('Cannot open protocol stream on limited connection')\n }\n\n const stream = await this._newStream(protocols, options)\n\n stream.direction = 'outbound'\n\n return stream\n }\n\n /**\n * Close the connection\n */\n async close (options: AbortOptions = {}): Promise<void> {\n if (this.status === 'closed' || this.status === 'closing') {\n return\n }\n\n this.log('closing connection to %a', this.remoteAddr)\n\n this.status = 'closing'\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT)\n setMaxListeners(Infinity, signal)\n\n options = {\n ...options,\n signal\n }\n }\n\n try {\n this.log.trace('closing underlying transport')\n\n // close raw connection\n await this._close(options)\n\n this.log.trace('updating timeline with close time')\n\n this.status = 'closed'\n this.timeline.close = Date.now()\n } catch (err: any) {\n this.log.error('error encountered during graceful close of connection to %a', this.remoteAddr, err)\n this.abort(err)\n }\n }\n\n abort (err: Error): void {\n if (this.status === 'closed') {\n return\n }\n\n this.log.error('aborting connection to %a due to error', this.remoteAddr, err)\n\n this.status = 'closing'\n\n // Abort raw connection\n this._abort(err)\n\n this.status = 'closed'\n this.timeline.close = Date.now()\n }\n}\n\nexport function createConnection (init: ConnectionInit): Connection {\n return new ConnectionImpl(init)\n}\n", "import { InvalidMultiaddrError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, setMaxListeners, InvalidPeerIdError } from '@libp2p/interface'\nimport * as mss from '@libp2p/multistream-select'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { anySignal } from 'any-signal'\nimport { CustomProgressEvent } from 'progress-events'\nimport { createConnection } from './connection/index.js'\nimport { PROTOCOL_NEGOTIATION_TIMEOUT, INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js'\nimport { ConnectionDeniedError, ConnectionInterceptedError, EncryptionFailedError, MuxerUnavailableError } from './errors.js'\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'\nimport type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, Stream, ConnectionProtector, NewStreamOptions, ConnectionEncrypter, SecuredConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, StreamMuxer, StreamMuxerFactory, Upgrader as UpgraderInterface, UpgraderOptions, ConnectionLimits, SecureConnectionOptions, CounterGroup, ClearableSignal } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\n\ninterface CreateConnectionOptions {\n cryptoProtocol: string\n direction: 'inbound' | 'outbound'\n maConn: MultiaddrConnection\n upgradedConn: MultiaddrConnection\n remotePeer: PeerId\n muxerFactory?: StreamMuxerFactory\n limits?: ConnectionLimits\n}\n\ninterface OnStreamOptions {\n connection: Connection\n stream: Stream\n protocol: string\n}\n\nexport interface CryptoResult extends SecuredConnection<MultiaddrConnection> {\n protocol: string\n}\n\nexport interface UpgraderInit {\n connectionEncrypters: ConnectionEncrypter[]\n streamMuxers: StreamMuxerFactory[]\n\n /**\n * An amount of ms by which an inbound connection upgrade must complete\n *\n * @default 3000\n */\n inboundUpgradeTimeout?: number\n\n /**\n * When a new incoming stream is opened on a multiplexed connection, protocol\n * negotiation on that stream must complete within this many ms\n *\n * @default 2000\n */\n inboundStreamProtocolNegotiationTimeout?: number\n\n /**\n * When a new incoming stream is opened on a multiplexed connection, protocol\n * negotiation on that stream must complete within this many ms\n *\n * @default 2000\n */\n outboundStreamProtocolNegotiationTimeout?: number\n}\n\nfunction findIncomingStreamLimit (protocol: string, registrar: Registrar): number | undefined {\n try {\n const { options } = registrar.getHandler(protocol)\n\n return options.maxInboundStreams\n } catch (err: any) {\n if (err.name !== 'UnhandledProtocolError') {\n throw err\n }\n }\n\n return DEFAULT_MAX_INBOUND_STREAMS\n}\n\nfunction findOutgoingStreamLimit (protocol: string, registrar: Registrar, options: NewStreamOptions = {}): number {\n try {\n const { options } = registrar.getHandler(protocol)\n\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams\n }\n } catch (err: any) {\n if (err.name !== 'UnhandledProtocolError') {\n throw err\n }\n }\n\n return options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS\n}\n\nfunction countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection): number {\n let streamCount = 0\n\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++\n }\n })\n\n return streamCount\n}\n\nexport interface UpgraderComponents {\n peerId: PeerId\n metrics?: Metrics\n connectionManager: ConnectionManager\n connectionGater: ConnectionGater\n connectionProtector?: ConnectionProtector\n registrar: Registrar\n peerStore: PeerStore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\ntype ConnectionDeniedType = keyof Pick<ConnectionGater, 'denyOutboundConnection' | 'denyInboundEncryptedConnection' | 'denyOutboundEncryptedConnection' | 'denyInboundUpgradedConnection' | 'denyOutboundUpgradedConnection'>\n\nexport class Upgrader implements UpgraderInterface {\n private readonly components: UpgraderComponents\n private readonly connectionEncrypters: Map<string, ConnectionEncrypter>\n private readonly streamMuxers: Map<string, StreamMuxerFactory>\n private readonly inboundUpgradeTimeout: number\n private readonly inboundStreamProtocolNegotiationTimeout: number\n private readonly outboundStreamProtocolNegotiationTimeout: number\n private readonly events: TypedEventTarget<Libp2pEvents>\n private readonly metrics: {\n dials?: CounterGroup<'inbound' | 'outbound'>\n errors?: CounterGroup<'inbound' | 'outbound'>\n }\n\n constructor (components: UpgraderComponents, init: UpgraderInit) {\n this.components = components\n this.connectionEncrypters = new Map()\n\n init.connectionEncrypters.forEach(encrypter => {\n this.connectionEncrypters.set(encrypter.protocol, encrypter)\n })\n\n this.streamMuxers = new Map()\n\n init.streamMuxers.forEach(muxer => {\n this.streamMuxers.set(muxer.protocol, muxer)\n })\n\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? INBOUND_UPGRADE_TIMEOUT\n this.inboundStreamProtocolNegotiationTimeout = init.inboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT\n this.outboundStreamProtocolNegotiationTimeout = init.outboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT\n this.events = components.events\n this.metrics = {\n dials: components.metrics?.registerCounterGroup('libp2p_connection_manager_dials_total'),\n errors: components.metrics?.registerCounterGroup('libp2p_connection_manager_dial_errors_total')\n }\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/upgrader'\n\n async shouldBlockConnection (connectionType: 'denyInboundConnection', maConn: MultiaddrConnection): Promise<void>\n async shouldBlockConnection (connectionType: ConnectionDeniedType, remotePeer: PeerId, maConn: MultiaddrConnection): Promise<void>\n async shouldBlockConnection (method: ConnectionDeniedType | 'denyInboundConnection', ...args: any[]): Promise<void> {\n const denyOperation: any = this.components.connectionGater[method]\n\n if (denyOperation == null) {\n return\n }\n\n const result = await denyOperation.apply(this.components.connectionGater, args)\n\n if (result === true) {\n throw new ConnectionInterceptedError(`The multiaddr connection is blocked by gater.${method}`)\n }\n }\n\n createInboundAbortSignal (signal: AbortSignal): ClearableSignal {\n const output = anySignal([\n AbortSignal.timeout(this.inboundUpgradeTimeout),\n signal\n ])\n setMaxListeners(Infinity, output)\n\n return output\n }\n\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound (maConn: MultiaddrConnection, opts: UpgraderOptions): Promise<void> {\n let accepted = false\n\n // always apply upgrade timeout for incoming upgrades\n const signal = this.createInboundAbortSignal(opts.signal)\n\n try {\n this.metrics.dials?.increment({\n inbound: true\n })\n\n accepted = await this.components.connectionManager.acceptIncomingConnection(maConn)\n\n if (!accepted) {\n throw new ConnectionDeniedError('Connection denied')\n }\n\n await this.shouldBlockConnection('denyInboundConnection', maConn)\n\n await this._performUpgrade(maConn, 'inbound', {\n ...opts,\n signal\n })\n } catch (err) {\n this.metrics.errors?.increment({\n inbound: true\n })\n\n throw err\n } finally {\n signal.clear()\n\n if (accepted) {\n this.components.connectionManager.afterUpgradeInbound()\n }\n }\n }\n\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound (maConn: MultiaddrConnection, opts: UpgraderOptions): Promise<Connection> {\n try {\n this.metrics.dials?.increment({\n outbound: true\n })\n\n const idStr = maConn.remoteAddr.getPeerId()\n let remotePeerId: PeerId | undefined\n\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr)\n await this.shouldBlockConnection('denyOutboundConnection', remotePeerId, maConn)\n }\n\n let direction: 'inbound' | 'outbound' = 'outbound'\n\n // act as the multistream-select server if we are not to be the initiator\n if (opts.initiator === false) {\n direction = 'inbound'\n }\n\n return await this._performUpgrade(maConn, direction, opts)\n } catch (err) {\n this.metrics.errors?.increment({\n outbound: true\n })\n\n throw err\n }\n }\n\n private async _performUpgrade (maConn: MultiaddrConnection, direction: 'inbound' | 'outbound', opts: UpgraderOptions): Promise<Connection> {\n let encryptedConn: MultiaddrConnection\n let remotePeer: PeerId\n let upgradedConn: MultiaddrConnection\n let muxerFactory: StreamMuxerFactory | undefined\n let cryptoProtocol\n\n this.components.metrics?.trackMultiaddrConnection(maConn)\n\n maConn.log.trace('starting the %s connection upgrade', direction)\n\n // Protect\n let protectedConn = maConn\n\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector\n\n if (protector != null) {\n maConn.log('protecting the %s connection', direction)\n protectedConn = await protector.protect(maConn, opts)\n }\n }\n\n try {\n // Encrypt the connection\n encryptedConn = protectedConn\n if (opts?.skipEncryption !== true) {\n opts?.onProgress?.(new CustomProgressEvent(`upgrader:encrypt-${direction}-connection`));\n\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol,\n streamMuxer: muxerFactory\n } = await (direction === 'inbound'\n ? this._encryptInbound(protectedConn, opts)\n : this._encryptOutbound(protectedConn, opts)\n ))\n\n const maConn: MultiaddrConnection = {\n ...protectedConn,\n ...encryptedConn\n }\n\n await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundEncryptedConnection' : 'denyOutboundEncryptedConnection', remotePeer, maConn)\n } else {\n const idStr = maConn.remoteAddr.getPeerId()\n\n if (idStr == null) {\n throw new InvalidMultiaddrError(`${direction} connection that skipped encryption must have a peer id`)\n }\n\n const remotePeerId = peerIdFromString(idStr)\n\n cryptoProtocol = 'native'\n remotePeer = remotePeerId\n }\n\n // this can happen if we dial a multiaddr without a peer id, we only find\n // out the identity of the remote after the connection is encrypted\n if (remotePeer.equals(this.components.peerId)) {\n const err = new InvalidPeerIdError('Can not dial self')\n maConn.abort(err)\n throw err\n }\n\n upgradedConn = encryptedConn\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory\n } else if (muxerFactory == null && this.streamMuxers.size > 0) {\n opts?.onProgress?.(new CustomProgressEvent(`upgrader:multiplex-${direction}-connection`))\n\n // Multiplex the connection\n const multiplexed = await (direction === 'inbound'\n ? this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.streamMuxers, opts)\n : this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.streamMuxers, opts))\n muxerFactory = multiplexed.muxerFactory\n upgradedConn = multiplexed.stream\n }\n } catch (err: any) {\n maConn.log.error('failed to upgrade inbound connection %s %a - %e', direction === 'inbound' ? 'from' : 'to', maConn.remoteAddr, err)\n throw err\n }\n\n await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundUpgradedConnection' : 'denyOutboundUpgradedConnection', remotePeer, maConn)\n\n maConn.log('successfully upgraded %s connection', direction)\n\n return this._createConnection({\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n limits: opts?.limits\n })\n }\n\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection (opts: CreateConnectionOptions): Connection {\n const {\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n remotePeer,\n muxerFactory,\n limits\n } = opts\n\n let muxer: StreamMuxer | undefined\n let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise<Stream>) | undefined\n let connection: Connection // eslint-disable-line prefer-const\n\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return\n }\n\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols()\n const signal = AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout)\n setMaxListeners(Infinity, signal)\n\n const { stream, protocol } = await mss.handle(muxedStream, protocols, {\n signal,\n log: muxedStream.log,\n yieldBytes: false\n })\n\n if (connection == null) {\n return\n }\n\n connection.log('incoming stream opened on %s', protocol)\n\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)\n const streamCount = countStreams(protocol, 'inbound', connection)\n\n if (streamCount === incomingLimit) {\n const err = new TooManyInboundProtocolStreamsError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`)\n muxedStream.abort(err)\n\n throw err\n }\n\n // after the handshake the returned stream can have early data so override\n // the source/sink\n muxedStream.source = stream.source\n muxedStream.sink = stream.sink\n muxedStream.protocol = protocol\n\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite\n }\n\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead\n }\n\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close\n }\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peer store should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n })\n\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n this._onStream({ connection, stream: muxedStream, protocol })\n })\n .catch(async err => {\n connection.log.error('error handling incoming stream id %s - %e', muxedStream.id, err)\n\n if (muxedStream.timeline.close == null) {\n await muxedStream.close()\n }\n })\n }\n })\n\n newStream = async (protocols: string[], options: NewStreamOptions = {}): Promise<Stream> => {\n if (muxer == null) {\n throw new MuxerUnavailableError('Connection is not multiplexed')\n }\n\n connection.log.trace('starting new stream for protocols %s', protocols)\n const muxedStream = await muxer.newStream()\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols)\n\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)\n\n const signal = AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout)\n setMaxListeners(Infinity, signal)\n\n options = {\n ...options,\n signal\n }\n }\n\n muxedStream.log.trace('selecting protocol from protocols %s', protocols)\n\n const {\n stream,\n protocol\n } = await mss.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n })\n\n muxedStream.log.trace('selected protocol %s', protocol)\n\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options)\n const streamCount = countStreams(protocol, 'outbound', connection)\n\n if (streamCount >= outgoingLimit) {\n const err = new TooManyOutboundProtocolStreamsError(`Too many outbound protocol streams for protocol \"${protocol}\" - ${streamCount}/${outgoingLimit}`)\n muxedStream.abort(err)\n\n throw err\n }\n\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peer store should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n })\n\n // after the handshake the returned stream can have early data so override\n // the source/sink\n muxedStream.source = stream.source\n muxedStream.sink = stream.sink\n muxedStream.protocol = protocol\n\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite\n }\n\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead\n }\n\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close\n }\n\n this.components.metrics?.trackProtocolStream(muxedStream, connection)\n\n return muxedStream\n } catch (err: any) {\n connection.log.error('could not create new outbound stream on connection %s %a for protocols %s - %e', direction === 'inbound' ? 'from' : 'to', opts.maConn.remoteAddr, protocols, err)\n\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err)\n }\n\n throw err\n }\n }\n\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer - %e', err)\n })\n }\n\n const _timeline = maConn.timeline\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close()\n }\n } catch (err: any) {\n connection.log.error('error closing connection after timeline close %e', err)\n } finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n })\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event %e', err)\n })\n }\n\n return Reflect.set(...args)\n }\n })\n maConn.timeline.upgraded = Date.now()\n\n const errConnectionNotMultiplexed = (): any => {\n throw new MuxerUnavailableError('Connection is not multiplexed')\n }\n\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n limits,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => {\n return muxer?.streams ?? []\n },\n close: async (options?: AbortOptions) => {\n // ensure remaining streams are closed gracefully\n await muxer?.close(options)\n\n // close the underlying transport\n await maConn.close(options)\n },\n abort: (err) => {\n maConn.abort(err)\n\n // ensure remaining streams are aborted\n muxer?.abort(err)\n }\n })\n\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n })\n\n // @ts-expect-error nah\n connection.__maConnTimeline = _timeline\n\n return connection\n }\n\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream (opts: OnStreamOptions): void {\n const { connection, stream, protocol } = opts\n const { handler, options } = this.components.registrar.getHandler(protocol)\n\n if (connection.limits != null && options.runOnLimitedConnection !== true) {\n throw new LimitedConnectionError('Cannot open protocol stream on limited connection')\n }\n\n handler({ connection, stream })\n }\n\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound (connection: MultiaddrConnection, options?: AbortOptions): Promise<CryptoResult> {\n const protocols = Array.from(this.connectionEncrypters.keys())\n\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n ...options,\n log: connection.log\n })\n const encrypter = this.connectionEncrypters.get(protocol)\n\n if (encrypter == null) {\n throw new EncryptionFailedError(`no crypto module found for ${protocol}`)\n }\n\n connection.log('encrypting inbound connection to %a using %s', connection.remoteAddr, protocol)\n\n return {\n ...await encrypter.secureInbound(stream, options),\n protocol\n }\n } catch (err: any) {\n connection.log.error('encrypting inbound connection from %a failed', connection.remoteAddr, err)\n throw new EncryptionFailedError(err.message)\n }\n }\n\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound (connection: MultiaddrConnection, options: SecureConnectionOptions): Promise<CryptoResult> {\n const protocols = Array.from(this.connectionEncrypters.keys())\n\n try {\n connection.log.trace('selecting encrypter from %s', protocols)\n\n const { stream, protocol } = await mss.select(connection, protocols, {\n ...options,\n log: connection.log,\n yieldBytes: true\n })\n const encrypter = this.connectionEncrypters.get(protocol)\n\n if (encrypter == null) {\n throw new EncryptionFailedError(`no crypto module found for ${protocol}`)\n }\n\n connection.log('encrypting outbound connection to %a using %s', connection.remoteAddr, protocol)\n\n return {\n ...await encrypter.secureOutbound(stream, options),\n protocol\n }\n } catch (err: any) {\n connection.log.error('encrypting outbound connection to %a failed', connection.remoteAddr, err)\n throw new EncryptionFailedError(err.message)\n }\n }\n\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {\n const protocols = Array.from(muxers.keys())\n connection.log('outbound selecting muxer %s', protocols)\n try {\n connection.log.trace('selecting stream muxer from %s', protocols)\n\n const {\n stream,\n protocol\n } = await mss.select(connection, protocols, {\n ...options,\n log: connection.log,\n yieldBytes: true\n })\n\n connection.log('selected %s as muxer protocol', protocol)\n const muxerFactory = muxers.get(protocol)\n\n return { stream, muxerFactory }\n } catch (err: any) {\n connection.log.error('error multiplexing outbound connection', err)\n throw new MuxerUnavailableError(String(err))\n }\n }\n\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {\n const protocols = Array.from(muxers.keys())\n connection.log('inbound handling muxers %s', protocols)\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n ...options,\n log: connection.log\n })\n const muxerFactory = muxers.get(protocol)\n\n return { stream, muxerFactory }\n } catch (err: any) {\n connection.log.error('error multiplexing inbound connection', err)\n throw new MuxerUnavailableError(String(err))\n }\n }\n\n getConnectionEncrypters (): Map<string, ConnectionEncrypter<unknown>> {\n return this.connectionEncrypters\n }\n\n getStreamMuxers (): Map<string, StreamMuxerFactory> {\n return this.streamMuxers\n }\n}\n", "export const version = '2.8.6'\nexport const name = 'js-libp2p'\n", "import * as pkg from './version.js'\n\nexport function userAgent (name?: string, version?: string): string {\n return `${name ?? pkg.name}/${version ?? pkg.version} browser/${globalThis.navigator.userAgent}`\n}\n", "import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'\nimport { contentRoutingSymbol, TypedEventEmitter, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol, InvalidParametersError } from '@libp2p/interface'\nimport { defaultLogger } from '@libp2p/logger'\nimport { PeerSet } from '@libp2p/peer-collections'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { persistentPeerStore } from '@libp2p/peer-store'\nimport { isMultiaddr, type Multiaddr } from '@multiformats/multiaddr'\nimport { MemoryDatastore } from 'datastore-core/memory'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { AddressManager } from './address-manager/index.js'\nimport { checkServiceDependencies, defaultComponents } from './components.js'\nimport { connectionGater } from './config/connection-gater.js'\nimport { DefaultConnectionManager } from './connection-manager/index.js'\nimport { ConnectionMonitor } from './connection-monitor.js'\nimport { CompoundContentRouting } from './content-routing.js'\nimport { DefaultPeerRouting } from './peer-routing.js'\nimport { RandomWalk } from './random-walk.js'\nimport { Registrar } from './registrar.js'\nimport { DefaultTransportManager } from './transport-manager.js'\nimport { Upgrader } from './upgrader.js'\nimport { userAgent } from './user-agent.js'\nimport * as pkg from './version.js'\nimport type { Components } from './components.js'\nimport type { Libp2p as Libp2pInterface, Libp2pInit } from './index.js'\nimport type { PeerRouting, ContentRouting, Libp2pEvents, PendingDial, ServiceMap, AbortOptions, ComponentLogger, Logger, Connection, NewStreamOptions, Stream, Metrics, PeerId, PeerInfo, PeerStore, Topology, Libp2pStatus, IsDialableOptions, DialOptions, PublicKey, Ed25519PeerId, Secp256k1PeerId, RSAPublicKey, RSAPeerId, URLPeerId, Ed25519PublicKey, Secp256k1PublicKey, StreamHandler, StreamHandlerOptions } from '@libp2p/interface'\n\nexport class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter<Libp2pEvents> implements Libp2pInterface<T> {\n public peerId: PeerId\n public peerStore: PeerStore\n public contentRouting: ContentRouting\n public peerRouting: PeerRouting\n public metrics?: Metrics\n public services: T\n public logger: ComponentLogger\n public status: Libp2pStatus\n\n public components: Components & T\n private readonly log: Logger\n\n // eslint-disable-next-line complexity\n constructor (init: Libp2pInit<T> & { peerId: PeerId }) {\n super()\n\n this.status = 'stopped'\n\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new TypedEventEmitter<Libp2pEvents>()\n const originalDispatch = events.dispatchEvent.bind(events)\n events.dispatchEvent = (evt: any) => {\n const internalResult = originalDispatch(evt)\n const externalResult = this.dispatchEvent(\n new CustomEvent(evt.type, { detail: evt.detail })\n )\n\n return internalResult || externalResult\n }\n\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, events)\n\n this.peerId = init.peerId\n this.logger = init.logger ?? defaultLogger()\n this.log = this.logger.forComponent('libp2p')\n // @ts-expect-error {} may not be of type T\n this.services = {}\n\n const nodeInfoName = init.nodeInfo?.name ?? pkg.name\n const nodeInfoVersion = init.nodeInfo?.version ?? pkg.version\n\n // @ts-expect-error defaultComponents is missing component types added later\n const components = this.components = defaultComponents({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: {\n name: nodeInfoName,\n version: nodeInfoVersion,\n userAgent: init.nodeInfo?.userAgent ?? userAgent(nodeInfoName, nodeInfoVersion)\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: connectionGater(init.connectionGater),\n dns: init.dns\n })\n\n this.peerStore = this.configureComponent('peerStore', persistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }))\n\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components))\n }\n\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo: PeerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n }\n\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo })\n }\n })\n\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components))\n }\n\n // Set up the Upgrader\n this.components.upgrader = new Upgrader(this.components, {\n connectionEncrypters: (init.connectionEncrypters ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n streamMuxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout,\n inboundStreamProtocolNegotiationTimeout: init.connectionManager?.inboundStreamProtocolNegotiationTimeout ?? init.connectionManager?.protocolNegotiationTimeout,\n outboundStreamProtocolNegotiationTimeout: init.connectionManager?.outboundStreamProtocolNegotiationTimeout ?? init.connectionManager?.protocolNegotiationTimeout\n })\n\n // Setup the transport manager\n this.configureComponent('transportManager', new DefaultTransportManager(this.components, init.transportManager))\n\n // Create the Connection Manager\n this.configureComponent('connectionManager', new DefaultConnectionManager(this.components, init.connectionManager))\n\n if (init.connectionMonitor?.enabled !== false) {\n // Create the Connection Monitor if not disabled\n this.configureComponent('connectionMonitor', new ConnectionMonitor(this.components, init.connectionMonitor))\n }\n\n // Create the Registrar\n this.configureComponent('registrar', new Registrar(this.components))\n\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new AddressManager(this.components, init.addresses))\n\n // Peer routers\n const peerRouters: PeerRouting[] = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)))\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new DefaultPeerRouting(this.components, {\n routers: peerRouters\n }))\n\n // Content routers\n const contentRouters: ContentRouting[] = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)))\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new CompoundContentRouting(this.components, {\n routers: contentRouters\n }))\n\n // Random walk\n this.configureComponent('randomWalk', new RandomWalk(this.components))\n\n // Discovery modules\n ;(init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components))\n\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt)\n })\n })\n\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)))\n })\n\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name]\n const service: any = createService(this.components)\n\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name)\n continue\n }\n\n this.services[name as keyof T] = service\n this.configureComponent(name, service)\n\n if (service[contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name)\n contentRouters.push(service[contentRoutingSymbol])\n }\n\n if (service[peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name)\n peerRouters.push(service[peerRoutingSymbol])\n }\n\n if (service[peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name)\n service[peerDiscoverySymbol].addEventListener?.('peer', (evt: CustomEvent<PeerInfo>) => {\n this.#onDiscoveryPeer(evt)\n })\n }\n }\n }\n\n // Ensure all services have their required dependencies\n checkServiceDependencies(components)\n }\n\n private configureComponent <T> (name: string, component: T): T {\n if (component == null) {\n this.log.error('component %s was null or undefined', name)\n }\n\n // @ts-expect-error cannot assign props\n this.components[name] = component\n\n return component\n }\n\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start (): Promise<void> {\n if (this.status !== 'stopped') {\n return\n }\n\n this.status = 'starting'\n\n this.log('libp2p is starting')\n\n try {\n await this.components.beforeStart?.()\n await this.components.start()\n await this.components.afterStart?.()\n\n this.status = 'started'\n this.safeDispatchEvent('start', { detail: this })\n this.log('libp2p has started')\n } catch (err: any) {\n this.log.error('An error occurred starting libp2p', err)\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started'\n await this.stop()\n throw err\n }\n }\n\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop (): Promise<void> {\n if (this.status !== 'started') {\n return\n }\n\n this.log('libp2p is stopping')\n\n this.status = 'stopping'\n\n await this.components.beforeStop?.()\n await this.components.stop()\n await this.components.afterStop?.()\n\n this.status = 'stopped'\n this.safeDispatchEvent('stop', { detail: this })\n this.log('libp2p has stopped')\n }\n\n getConnections (peerId?: PeerId): Connection[] {\n return this.components.connectionManager.getConnections(peerId)\n }\n\n getDialQueue (): PendingDial[] {\n return this.components.connectionManager.getDialQueue()\n }\n\n getPeers (): PeerId[] {\n const peerSet = new PeerSet()\n\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer)\n }\n\n return Array.from(peerSet)\n }\n\n async dial (peer: PeerId | Multiaddr | Multiaddr[], options: DialOptions = {}): Promise<Connection> {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n })\n }\n\n async dialProtocol (peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options: NewStreamOptions = {}): Promise<Stream> {\n if (protocols == null) {\n throw new InvalidParametersError('no protocols were provided to open a stream')\n }\n\n protocols = Array.isArray(protocols) ? protocols : [protocols]\n\n if (protocols.length === 0) {\n throw new InvalidParametersError('no protocols were provided to open a stream')\n }\n\n const connection = await this.dial(peer, options)\n\n return connection.newStream(protocols, options)\n }\n\n getMultiaddrs (): Multiaddr[] {\n return this.components.addressManager.getAddresses()\n }\n\n getProtocols (): string[] {\n return this.components.registrar.getProtocols()\n }\n\n async hangUp (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise<void> {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '')\n }\n\n await this.components.connectionManager.closeConnections(peer, options)\n }\n\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey (peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n async getPublicKey (peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n async getPublicKey (peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n async getPublicKey (peer: URLPeerId, options?: AbortOptions): Promise<never>\n async getPublicKey (peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise<PublicKey> {\n this.log('getPublicKey %p', peer)\n\n if (peer.publicKey != null) {\n return peer.publicKey\n }\n\n try {\n const peerInfo = await this.peerStore.get(peer)\n\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey\n }\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.toMultihash().bytes\n ])\n\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options)\n\n // ensure the returned key is valid\n const publicKey = publicKeyFromProtobuf(bytes)\n\n await this.peerStore.patch(peer, {\n publicKey\n })\n\n return publicKey\n }\n\n async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void> {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.handle(protocol, handler, options)\n })\n )\n }\n\n async unhandle (protocols: string[] | string): Promise<void> {\n if (!Array.isArray(protocols)) {\n protocols = [protocols]\n }\n\n await Promise.all(\n protocols.map(async protocol => {\n await this.components.registrar.unhandle(protocol)\n })\n )\n }\n\n async register (protocol: string, topology: Topology): Promise<string> {\n return this.components.registrar.register(protocol, topology)\n }\n\n unregister (id: string): void {\n this.components.registrar.unregister(id)\n }\n\n async isDialable (multiaddr: Multiaddr, options: IsDialableOptions = {}): Promise<boolean> {\n return this.components.connectionManager.isDialable(multiaddr, options)\n }\n\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer (evt: CustomEvent<PeerInfo>): void {\n const { detail: peer } = evt\n\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error('peer discovery mechanism discovered self')\n return\n }\n\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err) })\n }\n}\n"],
|
|
5
|
+
"mappings": ";2pBAAA,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,gBAI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MC,EAAO,IAAIC,GAAY,CAC3B,GAAG,MAAMC,GAAeJ,CAAO,EAC/B,OAAQK,GAAqBL,EAAQ,UAAU,EAChD,EAED,OAAIA,EAAQ,QAAU,IACpB,MAAME,EAAK,MAAK,EAGXA,CACT",
|
|
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", "require_hashlru", "__commonJSMin", "exports", "module", "max", "size", "cache", "_cache", "update", "key", "value", "v", "require_is_plain_obj", "__commonJSMin", "exports", "module", "value", "prototype", "require_merge_options", "__commonJSMin", "exports", "module", "isOptionObject", "hasOwnProperty", "propertyIsEnumerable", "defineProperty", "object", "name", "value", "globalThis", "defaultMergeOptions", "getEnumerableOwnPropertyKeys", "keys", "key", "symbols", "symbol", "clone", "cloneArray", "cloneOptionObject", "array", "result", "mergeKeys", "merged", "source", "config", "merge", "concatArrays", "resultIndex", "indices", "k", "options", "option", "require_netmask", "__commonJSMin", "exports", "Netmask", "atob", "chr", "chr0", "chrA", "chra", "ip2long", "long2ip", "long", "a", "b", "c", "ip", "i", "j", "n", "ref", "s", "base", "dmax", "start", "net", "mask", "error", "error1", "count", "fn", "index", "lastLong", "require_retry_operation", "__commonJSMin", "exports", "module", "RetryOperation", "timeouts", "options", "err", "currentTime", "timeout", "self", "fn", "timeoutOps", "counts", "mainError", "mainErrorCount", "i", "error", "message", "count", "require_retry", "__commonJSMin", "exports", "RetryOperation", "options", "timeouts", "opts", "key", "i", "a", "b", "attempt", "random", "timeout", "obj", "methods", "method", "original", "op", "args", "callback", "err", "require_retry", "__commonJSMin", "exports", "module", "index_exports", "__export", "createLibp2p", "connectionSymbol", "contentRoutingSymbol", "peerDiscoverySymbol", "peerIdSymbol", "isPeerId", "other", "peerRoutingSymbol", "KEEP_ALIVE", "transportSymbol", "FaultTolerance", "AbortError", "message", "InvalidParametersError", "message", "InvalidPublicKeyError", "InvalidPrivateKeyError", "ConnectionClosingError", "message", "ConnectionClosedError", "NotFoundError", "message", "InvalidPeerIdError", "InvalidMultiaddrError", "InvalidCIDError", "InvalidMultihashError", "UnsupportedProtocolError", "InvalidMessageError", "TimeoutError", "message", "NotStartedError", "DialError", "message", "LimitedConnectionError", "message", "TooManyInboundProtocolStreamsError", "TooManyOutboundProtocolStreamsError", "UnsupportedKeyTypeError", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "options", "list", "callback", "event", "result", "once", "detail", "isStartable", "obj", "start", "objs", "startables", "s", "stop", "serviceCapabilities", "serviceDependencies", "base58_exports", "__export", "base58btc", "base58flickr", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "base", "ALPHABET", "name", "BASE_MAP", "j", "i", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "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", "encodeOctetString", "encodeSequence", "values", "output", "generateECDSAKey", "curve", "keyPair", "hashAndSign", "key", "msg", "privateKey", "signature", "hashAndVerify", "sig", "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", "privateKeyToPKIMessage", "privateKey", "encodeSequence", "encodeInteger", "encodeOctetString", "fromString", "getOID", "encodeBitString", "Uint8ArrayList", "publicKeyToPKIMessage", "publicKey", "curve", "OID_256", "OID_384", "OID_521", "generateECDSAKeyPair", "key", "generateECDSAKey", "ECDSAPrivateKey", "ECDSAPublicKey", "jwk", "publicKeyToPKIMessage", "identity", "publicKeyToProtobuf", "CID", "base58btc", "key", "equals", "data", "sig", "hashAndVerify", "ECDSAPrivateKey", "privateKeyToPKIMessage", "message", "hashAndSign", "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", "a", "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", "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", "y", "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", "PRIVATE_KEY_BYTE_LENGTH", "KEYS_BYTE_LENGTH", "generateKey", "privateKeyRaw", "ed25519", "publicKey", "concatKeys", "hashAndSign", "privateKey", "msg", "privateKeyRaw", "KEYS_BYTE_LENGTH", "ed25519", "hashAndVerify", "publicKey", "sig", "concatKeys", "PRIVATE_KEY_BYTE_LENGTH", "i", "Ed25519PublicKey", "key", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "hashAndVerify", "Ed25519PrivateKey", "publicKey", "PRIVATE_KEY_BYTE_LENGTH", "message", "hashAndSign", "unmarshalEd25519PublicKey", "bytes", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "Ed25519PublicKey", "generateEd25519KeyPair", "privateKey", "publicKey", "generateKey", "Ed25519PrivateKey", "ensureEd25519Key", "key", "length", "InvalidParametersError", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "MSB", "REST", "encodingLength", "value", "encodeUint8Array", "buf", "offset", "encodeUint8ArrayList", "decodeUint8Array", "b", "res", "decodeUint8ArrayList", "encode", "allocUnsafe", "decode", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "_LongBits", "lo", "hi", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "pool", "size", "SIZE", "MAX", "slab", "offset", "allocUnsafe", "buf", "Op", "fn", "len", "val", "noop", "State", "writer", "bufferPool", "pool", "alloc", "size", "allocUnsafe", "Uint8ArrayWriter", "value", "VarintOp", "writeVarint64", "LongBits", "bits", "encodeUint8Array", "encodingLength", "writeByte", "writeFixed32", "writeFloatLE", "writeDoubleLE", "writeBytes", "length", "write", "head", "tail", "buf", "pos", "writeVarint32", "writeBytesBuffer", "writeStringBuffer", "fromString", "createWriter", "encodeMessage", "message", "codec", "w", "createWriter", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "MaxLengthError", "MaxSizeError", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "randomBytes", "length", "InvalidParametersError", "SigningError", "message", "VerificationError", "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", "hashAndSign", "key", "msg", "p", "sha256", "isPromise", "digest", "secp256k1", "err", "SigningError", "hashAndVerify", "sig", "VerificationError", "Secp256k1PublicKey", "key", "validateSecp256k1PublicKey", "compressSecp256k1PublicKey", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "hashAndVerify", "Secp256k1PrivateKey", "publicKey", "validateSecp256k1PrivateKey", "computeSecp256k1PublicKey", "message", "hashAndSign", "unmarshalSecp256k1PublicKey", "bytes", "Secp256k1PublicKey", "generateSecp256k1KeyPair", "privateKeyBytes", "generateSecp256k1PrivateKey", "Secp256k1PrivateKey", "compressSecp256k1PublicKey", "key", "secp256k1", "validateSecp256k1PrivateKey", "key", "secp256k1", "err", "InvalidPrivateKeyError", "validateSecp256k1PublicKey", "InvalidPublicKeyError", "computeSecp256k1PublicKey", "privateKey", "generateSecp256k1PrivateKey", "generateKeyPair", "type", "bits", "generateEd25519KeyPair", "generateSecp256k1KeyPair", "generateRSAKeyPair", "toBits", "generateECDSAKeyPair", "toCurve", "UnsupportedKeyTypeError", "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", "toBits", "bits", "toCurve", "curve", "InvalidParametersError", "inspect", "LIBP2P_KEY_CODE", "PeerIdImpl", "init", "peerIdSymbol", "base58btc", "CID", "id", "equals", "RSAPeerId", "Ed25519PeerId", "Secp256k1PeerId", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "URLPeerId", "url", "identity", "fromString", "other", "toString", "LIBP2P_KEY_CODE", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "peerIdFromString", "str", "decoder", "multihash", "decode", "base58btc", "peerIdFromCID", "CID", "InvalidParametersError", "peerIdFromMultihash", "peerIdFromPublicKey", "publicKey", "Ed25519PeerId", "Secp256k1PeerId", "RSAPeerId", "UnsupportedKeyTypeError", "peerIdFromPrivateKey", "privateKey", "isSha256Multihash", "isIdentityMultihash", "publicKeyFromMultihash", "url", "toString", "URLPeerId", "InvalidMultihashError", "cid", "InvalidCIDError", "identity", "sha256", "CustomProgressEvent", "type", "detail", "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", "getTypes", "types", "DEFAULT_TYPES", "RecordType", "DEFAULT_TTL", "toDNSResponse", "obj", "question", "RecordType", "answer", "toString", "DEFAULT_QUERY_CONCURRENCY", "dnsJsonOverHttps", "url", "init", "httpQueue", "PQueue", "fqdn", "options", "searchParams", "getTypes", "type", "RecordType", "CustomProgressEvent", "response", "res", "toDNSResponse", "defaultResolver", "dnsJsonOverHttps", "import_hashlru", "CachedAnswers", "maxSize", "hashlru", "fqdn", "types", "foundAllAnswers", "answers", "type", "cached", "toDNSResponse", "domain", "key", "cachedAnswers", "entry", "expires", "value", "RecordType", "answer", "DEFAULT_TTL", "cache", "size", "DEFAULT_ANSWER_CACHE_SIZE", "DNS", "init", "cache", "tld", "resolver", "defaultResolver", "domain", "options", "types", "getTypes", "cached", "CustomProgressEvent", "resolvers", "errors", "result", "answer", "err", "RecordType", "dns", "init", "DNS", "Parser", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "input", "MAX_IPV6_LENGTH", "parser", "parseIP", "mapIPv4ToIPv6", "addr", "allFF", "a", "from", "to", "i", "e", "deepEqual", "b", "ipToString", "ip", "IPv4Len", "IPv6Len", "result", "simpleMaskLength", "mask", "ones", "index", "byte", "maskToHex", "hex", "IPv4Len", "IPv6Len", "maxIPv6Octet", "ipv4Prefix", "maskIp", "ip", "mask", "allFF", "deepEqual", "n", "out", "i", "containsIp", "net", "parseIP", "parseCidr", "s", "address", "maskString", "ipLength", "IPv4Len", "ip", "parseIPv4", "IPv6Len", "parseIPv6", "m", "mask", "cidrMask", "maskIp", "ones", "bits", "l", "i", "IpNet", "ipOrCidr", "mask", "parseCidr", "ipResult", "parseIP", "m", "maskResult", "cidrMask", "maskIp", "ip", "containsIp", "l", "simpleMaskLength", "maskToHex", "ipToString", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "isIP", "parseIP", "isV4", "isIPv4", "isV6", "isIPv6", "toBytes", "ip", "offset", "bytes", "byte", "sections", "i", "isv4", "v4Buffer", "toString", "argv", "word", "buf", "length", "view", "result", "names", "codes", "table", "row", "proto", "createProtocol", "code", "size", "name", "resolvable", "path", "getProtocol", "ip4Protocol", "getProtocol", "ip6Protocol", "ipcidrProtocol", "convertToString", "proto", "buf", "getProtocol", "bytes2ip", "bytes2str", "toString", "bytes2port", "bytes2mh", "bytes2onion", "bytes2mb", "convertToBytes", "str", "ip2bytes", "str2bytes", "fromString", "port2bytes", "mh2bytes", "onion2bytes", "onion32bytes", "mb2bytes", "convertToIpNet", "multiaddr", "mask", "addr", "code", "value", "ip4Protocol", "ip6Protocol", "ipcidrProtocol", "IpNet", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "ipString", "isIP", "toBytes", "ipBuff", "port", "size", "encode", "concat", "decode", "encodingLength", "hash", "mh", "base58btc", "CID", "mbstr", "mb", "address", "base32", "portBuf", "addrBytes", "portBytes", "stringToMultiaddrParts", "str", "cleanPath", "tuples", "stringTuples", "path", "parts", "p", "part", "proto", "getProtocol", "ParseError", "convertToBytes", "bytes", "convertToString", "stringTuplesToString", "tuplesToBytes", "bytesToMultiaddrParts", "i", "code", "decode", "n", "encodingLength", "size", "sizeForAddr", "addr", "toString", "stringAddr", "stringTuplesToString", "tuples", "parts", "tup", "proto", "getProtocol", "cleanPath", "tuplesToBytes", "concat", "buf", "encode", "sizeForAddr", "p", "addr", "size", "decode", "encodingLength", "cleanPath", "str", "a", "ParseError", "inspect", "symbol", "DNS_CODES", "getProtocol", "NoAvailableResolverError", "message", "Multiaddr", "_Multiaddr", "#string", "#tuples", "#stringTuples", "#path", "addr", "parts", "bytesToMultiaddrParts", "stringToMultiaddrParts", "isMultiaddr", "family", "transport", "host", "port", "zone", "tcp", "udp", "ip4", "ip6", "dns6", "ip6zone", "code", "value", "addrString", "s", "i", "tuples", "tuplesToBytes", "name", "names", "tuple", "peerIdStr", "toString", "base58btc", "CID", "equals", "options", "resolvableProto", "p", "resolver", "resolvers", "str", "multiaddr", "protos", "resolvers", "isMultiaddr", "value", "symbol", "multiaddr", "addr", "Multiaddr", "MAX_RECURSIVE_DEPTH", "dnsaddrCode", "getProtocol", "RecursionLimitError", "message", "dnsaddrResolver", "ma", "options", "recursionLimit", "hostname", "proto", "result", "dns", "RecordType", "peerId", "output", "answer", "addr", "multiaddr", "resolved", "import_index", "merge_options_default", "mergeOptions", "DefaultConfig", "multiaddrs", "dnsaddrResolver", "FaultTolerance", "validateConfig", "opts", "resultingOptions", "merge_options_default", "InvalidParametersError", "ms", "value", "options", "parse", "fmtLong", "fmtShort", "error", "message", "isError", "str", "match", "n", "type", "dist_default", "msAbs", "plural", "name", "isPlural", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "dist_default", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "storage", "localstorage", "colors", "useColors", "formatArgs", "args", "dist_default", "c", "index", "lastC", "match", "log", "save", "namespaces", "load", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "src_default", "v", "base58btc", "base32", "base64", "notEmpty", "createDisabledLogger", "namespace", "logger", "defaultLogger", "name", "logger", "trace", "createDisabledLogger", "src_default", "r", "n", "notEmpty", "str", "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", "FNV_PRIMES", "FNV_OFFSETS", "cachedEncoder", "fnv1aUint8Array", "uint8Array", "size", "fnvPrime", "hash", "index", "fnv1aEncodeInto", "string", "utf8Buffer", "remaining", "result", "fnv1a", "value", "fnv1a", "input", "seed", "numberToBuffer", "num", "hex", "fromString", "MAX_FINGERPRINT_SIZE", "Fingerprint", "buf", "hash", "seed", "fingerprintSize", "fnv", "fp", "alloc", "i", "other", "equals", "getRandomInt", "min", "max", "Bucket", "size", "fingerprint", "Fingerprint", "fp", "i", "getRandomInt", "current", "found", "maxCuckooCount", "CuckooFilter", "init", "fnv1a", "getRandomInt", "item", "fromString", "fingerprint", "Fingerprint", "j", "k", "Bucket", "rand", "n", "swapped", "inJ", "inK", "MAX_LOAD", "calculateBucketSize", "errorRate", "optimize", "maxItems", "bucketSize", "load", "filterSize", "fingerprintSize", "MAX_FINGERPRINT_SIZE", "ScalableCuckooFilter", "init", "fnv1a", "getRandomInt", "CuckooFilter", "item", "fromString", "current", "cuckoo", "curSize", "i", "acc", "curr", "createScalableCuckooFilter", "maxItems", "errorRate", "options", "optimize", "Envelope", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "encodeMessage", "buf", "decodeMessage", "InvalidSignatureError", "message", "RecordEnvelope", "_RecordEnvelope", "data", "envelopeData", "Envelope", "publicKey", "publicKeyFromProtobuf", "record", "privateKey", "domain", "payloadType", "payload", "signData", "formatSignaturePayload", "signature", "envelope", "InvalidSignatureError", "init", "publicKeyToProtobuf", "other", "equals", "domainUint8Array", "fromString", "domainLength", "encode", "payloadTypeLength", "payloadLength", "Uint8ArrayList", "arrayEquals", "a", "b", "sort", "item", "index", "ENVELOPE_DOMAIN_PEER_RECORD", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "PeerRecord", "AddressInfo", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "encodeMessage", "buf", "decodeMessage", "value", "MaxLengthError", "PeerRecord", "_PeerRecord", "buf", "peerRecord", "peerId", "peerIdFromMultihash", "decode", "multiaddrs", "a", "multiaddr", "seqNumber", "ENVELOPE_DOMAIN_PEER_RECORD", "ENVELOPE_PAYLOAD_TYPE_PEER_RECORD", "init", "m", "other", "arrayEquals", "isAsyncIterable", "thing", "all", "source", "arr", "entry", "src_default", "events", "observable", "worker", "event", "type", "fn", "listener", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "nanoid", "size", "handleWorkerLockRequest", "emitter", "masterEvent", "requestType", "releaseType", "grantType", "worker", "event", "requestEvent", "resolve", "releaseEventListener", "releaseEvent", "makeWorkerLockRequest", "name", "id", "nanoid", "listener", "responseEvent", "defaultOptions", "browser_default", "options", "src_default", "WORKER_REQUEST_READ_LOCK", "WORKER_RELEASE_READ_LOCK", "MASTER_GRANT_READ_LOCK", "WORKER_REQUEST_WRITE_LOCK", "WORKER_RELEASE_WRITE_LOCK", "MASTER_GRANT_WRITE_LOCK", "mutexes", "implementation", "createReleaseable", "queue", "options", "res", "p", "resolve", "pTimeout", "createMutex", "name", "masterQueue", "PQueue", "readQueue", "localReadQueue", "readPromise", "defaultOptions", "createMortice", "opts", "browser_default", "event", "release", "Peer", "Peer$metadataEntry", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "encodeMessage", "buf", "decodeMessage", "Peer$tagsEntry", "Tag", "value", "Address", "key", "MaxLengthError", "MaxSizeError", "entry", "populatePublicKey", "peerId", "protobuf", "digest", "multihash", "base58btc", "decode", "publicKey", "publicKeyFromProtobuf", "peerIdFromPublicKey", "bytesToPeer", "buf", "maxAddressAge", "peer", "Peer", "pbToPeer", "tags", "now", "key", "tag", "observed", "ma", "isCertified", "multiaddr", "peerEquals", "peerA", "peerB", "addressesEqual", "protocolsEqual", "publicKeyEqual", "peerRecordEnvelope", "metadataEqual", "tagsEqual", "addressesA", "addressesB", "compareArrays", "a", "b", "equals", "protocolsA", "protocolsB", "publicKeyA", "publicKeyB", "compareOptionalUint8Arrays", "envelopeA", "envelopeB", "metadataA", "metadataB", "compareMaps", "arrA", "arrB", "compare", "i", "mapA", "mapB", "key", "value", "valueB", "pathSepS", "pathSepB", "pathSep", "Key", "_Key", "s", "clean", "fromString", "encoding", "toString", "list", "other", "bytes", "key", "list1", "list2", "i", "c1", "c2", "ns", "namespaceType", "namespaceValue", "p", "keys", "flatten", "parts", "arr", "NAMESPACE_COMMON", "peerIdToDatastoreKey", "peerId", "isPeerId", "InvalidParametersError", "b32key", "Key", "dedupeFilterAndSortAddresses", "peerId", "filter", "addresses", "existingAddresses", "addressMap", "addr", "multiaddr", "isMultiaddr", "InvalidParametersError", "isCertified", "maStr", "existingAddr", "a", "b", "ma", "addrPeer", "toPeerPB", "peerId", "data", "strategy", "options", "InvalidParametersError", "existingPeer", "addresses", "protocols", "metadata", "tags", "peerRecordEnvelope", "multiaddr", "metadataEntries", "createSortedMap", "validateMetadata", "tagsEntries", "validateTag", "mapTag", "key", "value", "mergedTags", "publicKey", "publicKeyToProtobuf", "output", "dedupeFilterAndSortAddresses", "a", "b", "addr", "equals", "entries", "tag", "expiry", "keyToPeerId", "key", "base32Str", "buf", "CID", "base32", "peerIdFromCID", "decodePeer", "value", "maxAddressAge", "peerId", "bytesToPeer", "mapQuery", "query", "NAMESPACE_COMMON", "fn", "a", "b", "PersistentStore", "components", "init", "createMortice", "err", "peerIdToDatastoreKey", "peer", "Peer", "#peerIsExpired", "NotFoundError", "pbToPeer", "data", "existingPeer", "#findExistingPeer", "peerPb", "toPeerPB", "#saveIfDifferent", "peerPB", "peerEquals", "expired", "minAddressObserved", "addrs", "addr", "PersistentPeerStore", "components", "init", "PersistentStore", "fn", "query", "release", "peer", "src_default", "peerId", "multiaddr", "id", "data", "result", "#emitIfUpdated", "buf", "expectedPeer", "envelope", "RecordEnvelope", "PeerRecord", "peerIdFromCID", "peerRecord", "err", "storedEnvelope", "storedRecord", "persistentPeerStore", "NotFoundError", "_NotFoundError", "message", "isAsyncIterable", "thing", "drain", "source", "_", "src_default", "peekable", "iterable", "iterator", "symbol", "queue", "value", "src_default", "isAsyncIterable", "thing", "filter", "source", "fn", "index", "entry", "peekable", "src_default", "value", "done", "res", "func", "isAsyncIterable", "thing", "sort", "source", "sorter", "src_default", "isAsyncIterable", "thing", "take", "source", "limit", "items", "entry", "src_default", "BaseDatastore", "key", "val", "options", "source", "value", "puts", "dels", "src_default", "q", "it", "prefix", "e", "f", "i", "offset", "MemoryDatastore", "BaseDatastore", "key", "val", "result", "NotFoundError", "value", "Key", "debounce", "func", "wait", "timeout", "output", "later", "import_netmask", "PRIVATE_IP_RANGES", "NETMASK_RANGES", "ipRange", "ipv4Check", "ipAddr", "r", "isIpv4MappedIpv6", "ipv4MappedIpv6Check", "parts", "octet34", "octet12", "ip4", "isIpv4EmbeddedIpv6", "ipv4EmbeddedIpv6Check", "ipv6Check", "isPrivateIp", "ip", "isIPv4", "isIPv6", "toParts", "ma", "func", "fn", "vals", "literal", "str", "val", "string", "number", "peerId", "base58btc", "certhash", "base64url", "optional", "matcher", "result", "or", "matchers", "matches", "m", "and", "fmt", "match", "parts", "exactMatch", "_PEER_ID", "peerId", "PEER_ID", "fmt", "_DNS4", "and", "literal", "string", "_DNS6", "_DNSADDR", "_DNS", "DNS4", "optional", "DNS6", "DNSADDR", "DNS", "or", "_IP4", "func", "isIPv4", "_IP6", "isIPv6", "_IP", "_IP_OR_DOMAIN", "IP_OR_DOMAIN", "IP4", "IP6", "IP", "_TCP", "number", "_UDP", "TCP", "UDP", "_QUIC", "_QUICV1", "QUIC_V0_OR_V1", "QUIC", "QUICV1", "_WEB", "_WebSockets", "WebSockets", "_WebSocketsSecure", "WebSocketsSecure", "_WebRTCDirect", "certhash", "WebRTCDirect", "_WebTransport", "WebTransport", "_P2P", "P2P", "_Circuit", "Circuit", "_WebRTC", "WebRTC", "_HTTP", "HTTP", "_HTTPS", "HTTPS", "_Memory", "Memory", "MAX_DATE", "CODEC_TLS", "CODEC_SNI", "CODEC_DNS", "CODEC_DNS4", "CODEC_DNS6", "CODEC_DNSADDR", "DNSMappings", "components", "init", "ma", "host", "mapping", "domain", "addresses", "ip", "verified", "isPrivateIp", "MAX_DATE", "wasConfident", "dnsMappedAddresses", "i", "tuples", "multiaddr", "tuple", "getProtocol", "j", "ttl", "startingConfidence", "CODEC_IP4", "CODEC_IP6", "CODEC_TCP", "CODEC_UDP", "IPMappings", "components", "init", "ma", "tuples", "mappings", "mapping", "internalIp", "internalPort", "externalIp", "externalPort", "protocol", "key", "isIPv4", "host", "port", "wasConfident", "i", "addresses", "ipMappedAddresses", "tuple", "multiaddr", "getProtocol", "ttl", "startingConfidence", "isLinkLocal", "ma", "codec", "value", "isIpBased", "ma", "codec", "isPrivate", "ma", "isIpBased", "value", "isPrivateIp", "defaultValues", "ObservedAddresses", "components", "init", "ma", "prefix", "key", "isPrivate", "isLinkLocal", "metadata", "multiaddr", "startingConfidence", "ttl", "addrString", "NETWORK_CODECS", "isNetworkAddress", "ma", "codec", "defaultValues", "TransportAddresses", "components", "init", "multiaddr", "ttl", "isPrivate", "key", "metadata", "isNetworkAddress", "ma", "startingConfidence", "options", "ONE_MINUTE", "defaultValues", "defaultAddressFilter", "addrs", "stripPeerId", "ma", "peerId", "observedPeerIdStr", "peerIdFromString", "multiaddr", "AddressManager", "components", "init", "listen", "announce", "appendAnnounce", "ObservedAddresses", "DNSMappings", "IPMappings", "TransportAddresses", "createScalableCuckooFilter", "debounce", "err", "a", "addr", "tuples", "socketAddress", "options", "startingConfidence", "addresses", "multiaddrs", "maStr", "address", "str", "announceMultiaddrs", "listener", "appendAnnounceMultiaddrs", "domain", "internalIp", "internalPort", "externalIp", "externalPort", "protocol", "isIPv4", "maOptions", "isPrivateIp", "listeners", "transportMatchers", "WebSockets", "WebSocketsSecure", "TCP", "QUICV1", "matcher", "transportListeners", "linkLocalAddr", "linkLocalOptions", "messages", "MissingServiceError", "message", "UnmetServiceDependenciesError", "NoContentRoutersError", "NoPeerRoutersError", "QueriedForSelfError", "UnhandledProtocolError", "DuplicateProtocolHandlerError", "DialDeniedError", "UnsupportedListenAddressError", "UnsupportedListenAddressesError", "NoValidAddressesError", "ConnectionInterceptedError", "ConnectionDeniedError", "MuxerUnavailableError", "EncryptionFailedError", "TransportUnavailableError", "DefaultComponents", "init", "key", "value", "defaultLogger", "methodName", "obj", "isStartable", "startable", "OPTIONAL_SERVICES", "NON_SERVICE_PROPERTIES", "defaultComponents", "components", "target", "prop", "receiver", "service", "MissingServiceError", "checkServiceDependencies", "serviceCapabilities", "capability", "getServiceCapabilities", "getServiceDependencies", "UnmetServiceDependenciesError", "getServiceName", "serviceDependencies", "CODEC_IP4", "CODEC_IP6", "connectionGater", "gater", "multiaddr", "WebSockets", "tuples", "isPrivateIp", "createAbortError", "error", "clearMethods", "createDelay", "defaultClear", "defaultSet", "milliseconds", "value", "signal", "timeoutId", "settle", "rejectFunction", "clear", "signalListener", "cleanup", "delayPromise", "resolve", "reject", "delay", "delay_default", "RateLimitError", "message", "props", "QueueFullError", "RateLimiter", "opts", "MemoryStorage", "key", "pointsToConsume", "options", "rlKey", "secDuration", "res", "RateLimitError", "delayMs", "delay_default", "points", "msDuration", "initPoints", "value", "durationSec", "existing", "msBeforeExpires", "durationMs", "record", "getPeerAddress", "peer", "isPeerId", "multiaddrs", "peerId", "peerIdStr", "peerIdFromString", "ma", "isMultiaddr", "InvalidMultiaddrError", "maPeerIdStr", "InvalidParametersError", "maPeerId", "PEER_ID", "DEFAULT_CLOSABLE_PROTOCOLS", "safelyCloseConnectionIfUnused", "connection", "options", "streamProtocols", "stream", "closableProtocols", "proto", "err", "LAST_DIAL_FAILURE_KEY", "LAST_DIAL_SUCCESS_KEY", "MAX_CONNECTIONS", "MAX_PARALLEL_DIALS", "resolveMultiaddrs", "ma", "options", "resolvable", "key", "resolvers", "output", "multiaddrToIpNet", "parsedMa", "multiaddr", "cidr", "convertToIpNet", "defaultOptions", "MAX_CONNECTIONS", "ConnectionPruner", "components", "init", "ma", "multiaddrToIpNet", "err", "connections", "numConnections", "peerValues", "PeerMap", "connection", "remotePeer", "peer", "acc", "curr", "sortedConnections", "toPrune", "toClose", "ipNet", "safelyCloseConnectionIfUnused", "a", "b", "connectionALifespan", "connectionBLifespan", "peerAValue", "peerBValue", "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", "raceEvent", "emitter", "eventName", "signal", "opts", "error", "resolve", "reject", "removeListeners", "abortListener", "eventListener", "errorEventListener", "evt", "err", "AbortError", "message", "code", "name", "raceSignal", "promise", "signal", "opts", "listener", "error", "resolve", "reject", "JobRecipient", "signal", "pDefer", "AbortError", "randomId", "Job", "fn", "options", "err", "acc", "curr", "AbortError", "recipient", "JobRecipient", "result", "raceSignal", "Queue", "TypedEventEmitter", "init", "debounce", "job", "j", "i", "fn", "options", "QueueFullError", "Job", "result", "err", "AbortError", "raceEvent", "limit", "stream", "pushable", "cleanup", "onQueueJobComplete", "evt", "onQueueError", "onQueueIdle", "onSignalAbort", "PriorityQueue", "Queue", "init", "a", "b", "anySignal", "signals", "controller", "onAbort", "signal", "clear", "isLoopbackAddr", "ip", "isLoopback", "ma", "isIpBased", "address", "isLoopbackAddr", "reliableTransportsFirst", "a", "b", "isATcp", "TCP", "isBTcp", "isAWebSocketSecure", "WebSocketsSecure", "isBWebSocketSecure", "isAWebSocket", "WebSockets", "isBWebSocket", "isAWebRTC", "WebRTC", "isBWebRTC", "isAWebRTCDirect", "WebRTCDirect", "isBWebRTCDirect", "isAWebTransport", "WebTransport", "isBWebTransport", "loopbackAddressLast", "isALoopback", "isLoopback", "isBLoopback", "publicAddressesFirst", "isAPrivate", "isPrivate", "isBPrivate", "certifiedAddressesFirst", "circuitRelayAddressesLast", "isACircuit", "Circuit", "isBCircuit", "defaultAddressSorter", "addresses", "defaultOptions", "MAX_PARALLEL_DIALS", "dnsaddrResolver", "DialQueue", "components", "init", "PeerMap", "key", "value", "resolvers", "PriorityQueue", "event", "AbortError", "peerIdOrMultiaddr", "options", "peerId", "multiaddrs", "getPeerAddress", "existingConnection", "conn", "addr", "CustomProgressEvent", "existingDial", "job", "addresses", "multiaddr", "DialError", "ma", "signal", "anySignal", "DEFAULT_DIAL_PRIORITY", "failedMultiaddrs", "forcePeerLookup", "dialed", "dialIteration", "errors", "addrsToDial", "addrs", "calculatedAddrs", "address", "LAST_DIAL_SUCCESS_KEY", "fromString", "err", "LAST_DIAL_FAILURE_KEY", "TimeoutError", "DialDeniedError", "peer", "peerInfo", "resolvedAddresses", "result", "resolveMultiaddrs", "peerIdMultiaddr", "filteredAddrs", "addrPeerId", "dedupedAddrs", "maStr", "existing", "dedupedMultiaddrs", "NoValidAddressesError", "gatedAddrs", "sortedGatedAddrs", "defaultAddressSorter", "Circuit", "PeerQueue", "Queue", "peerId", "job", "import_retry", "objectToString", "isError", "value", "errorMessages", "isNetworkError", "error", "AbortError", "message", "decorateErrorWithCounts", "error", "attemptNumber", "options", "retriesLeft", "pRetry", "input", "resolve", "reject", "operation", "retry", "abortHandler", "cleanUp", "result", "isNetworkError", "finalError", "ReconnectQueue", "components", "init", "PeerQueue", "evt", "err", "peerId", "peer", "hasKeepAliveTag", "options", "pRetry", "attempt", "tags", "key", "KEEP_ALIVE", "keepAlivePeers", "tag", "DEFAULT_DIAL_PRIORITY", "defaultOptions", "MAX_CONNECTIONS", "DefaultConnectionManager", "components", "init", "InvalidParametersError", "PeerMap", "str", "multiaddrToIpNet", "RateLimiter", "ConnectionPruner", "a", "multiaddr", "DialQueue", "MAX_PARALLEL_DIALS", "dnsaddrResolver", "ReconnectQueue", "metric", "conns", "conn", "stream", "key", "allStreams", "streams", "protocol", "count", "counts", "b", "index", "start", "stop", "tasks", "connectionList", "connection", "err", "evt", "peerId", "isNewPeer", "storedConns", "filteredPeerConns", "c", "peerIdOrMultiaddr", "options", "NotStartedError", "getPeerAddress", "InvalidPeerIdError", "existingConnection", "CustomProgressEvent", "ConnectionClosedError", "peerConnections", "trackedConnection", "InvalidMultiaddrError", "connections", "maConn", "ma", "ipNet", "host", "statusMap", "job", "MovingAverage", "timeSpan", "pt", "value", "time", "a", "diff", "incr", "DEFAULT_TIMEOUT_MULTIPLIER", "DEFAULT_FAILURE_MULTIPLIER", "DEFAULT_MIN_TIMEOUT", "AdaptiveTimeout", "init", "MovingAverage", "options", "timeout", "sendTimeout", "timeoutSignal", "anySignal", "signal", "time", "QueuelessPushable", "pDefer", "nextResult", "err", "result", "value", "options", "raceSignal", "queuelessPushable", "UnexpectedEOFError", "byteStream", "duplex", "opts", "write", "queuelessPushable", "err", "source", "buf", "readBuffer", "Uint8ArrayList", "options", "done", "value", "raceSignal", "UnexpectedEOFError", "data", "originalStream", "DEFAULT_PING_INTERVAL_MS", "PROTOCOL_VERSION", "PROTOCOL_NAME", "PROTOCOL_PREFIX", "PING_LENGTH", "DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE", "ConnectionMonitor", "components", "init", "AdaptiveTimeout", "serviceCapabilities", "conn", "start", "signal", "stream", "bs", "byteStream", "randomBytes", "err", "isAsyncIterable", "thing", "addAllToPushable", "sources", "output", "signal", "source", "item", "err", "mergeSources", "controller", "queuelessPushable", "mergeSyncSources", "syncSources", "merge", "src_default", "CompoundContentRouting", "components", "init", "cid", "attrs", "value", "key", "toString", "options", "NoContentRoutersError", "self", "seen", "PeerSet", "peer", "src_default", "router", "NotStartedError", "CustomEvent", "parallel", "source", "options", "concurrency", "ordered", "emitter", "ops", "slotAvailable", "pDefer", "resultAvailable", "sourceFinished", "sourceErr", "opErred", "task", "op", "result", "err", "valuesAvailable", "yieldOrderedValues", "yieldUnOrderedValues", "i", "DefaultPeerRouting", "components", "init", "peer", "attrs", "key", "toString", "value", "id", "options", "NoPeerRoutersError", "QueriedForSelfError", "self", "source", "src_default", "router", "err", "NotFoundError", "seen", "createScalableCuckooFilter", "parallel", "RandomWalk", "TypedEventEmitter", "components", "options", "signal", "anySignal", "pDefer", "raceEvent", "start", "found", "data", "randomBytes", "peer", "raceSignal", "err", "DEFAULT_MAX_INBOUND_STREAMS", "DEFAULT_MAX_OUTBOUND_STREAMS", "Registrar", "components", "protocol", "handler", "UnhandledProtocolError", "topologies", "opts", "DuplicateProtocolHandlerError", "options", "merge_options_default", "protocols", "topology", "InvalidParametersError", "id", "evt", "remotePeer", "peer", "err", "previous", "removed", "connection", "peerId", "TrackedMap", "init", "name", "metrics", "key", "value", "deleted", "trackedMap", "config", "map", "DefaultTransportManager", "components", "init", "trackedMap", "FaultTolerance", "transport", "tag", "InvalidParametersError", "addrs", "tasks", "key", "listeners", "listener", "ma", "options", "TransportUnavailableError", "CustomProgressEvent", "NotStartedError", "listenStats", "UnsupportedListenAddressError", "supportedAddrs", "addr", "index", "l", "IP4", "IP6", "err", "results", "res", "UnsupportedListenAddressesError", "allIpv4Succeeded", "allIpv6Failed", "PROTOCOL_ID", "InvalidMessageLengthError", "InvalidDataLengthError", "InvalidDataLengthLengthError", "lpStream", "duplex", "opts", "bytes", "byteStream", "encodingLength", "decodeLength", "decode", "encodeLength", "encode", "options", "dataLength", "lengthBuffer", "Uint8ArrayList", "err", "InvalidMessageLengthError", "InvalidDataLengthLengthError", "InvalidDataLengthError", "data", "list", "buf", "NewLine", "fromString", "write", "writer", "buffer", "options", "writeAll", "buffers", "read", "reader", "buf", "InvalidMessageError", "readString", "toString", "select", "stream", "protocols", "options", "optimisticSelect", "lp", "lpStream", "protocol", "PROTOCOL_ID", "p1", "fromString", "p2", "writeAll", "response", "readString", "write", "UnsupportedProtocolError", "originalSink", "originalSource", "negotiated", "negotiating", "doneNegotiating", "pDefer", "sentProtocol", "sendingProtocol", "doneSendingProtocol", "readProtocol", "readingProtocol", "doneReadingProtocol", "source", "sink", "sentData", "buf", "protocolString", "Uint8ArrayList", "encode", "negotiate", "err", "doSendProtocol", "doReadProtocol", "originalCloseRead", "opts", "originalCloseWrite", "originalClose", "tasks", "raceSignal", "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", "handle", "stream", "protocols", "options", "lp", "lpStream", "protocol", "readString", "PROTOCOL_ID", "write", "fromString", "protos", "Uint8ArrayList", "p", "encode", "CLOSE_TIMEOUT", "ConnectionImpl", "init", "remoteAddr", "remotePeer", "newStream", "close", "abort", "getStreams", "connectionSymbol", "protocols", "options", "ConnectionClosingError", "ConnectionClosedError", "LimitedConnectionError", "stream", "signal", "err", "createConnection", "findIncomingStreamLimit", "protocol", "registrar", "options", "err", "DEFAULT_MAX_INBOUND_STREAMS", "findOutgoingStreamLimit", "DEFAULT_MAX_OUTBOUND_STREAMS", "countStreams", "direction", "connection", "streamCount", "stream", "Upgrader", "components", "init", "encrypter", "muxer", "method", "args", "denyOperation", "ConnectionInterceptedError", "signal", "output", "anySignal", "maConn", "opts", "accepted", "ConnectionDeniedError", "idStr", "remotePeerId", "peerIdFromString", "encryptedConn", "remotePeer", "upgradedConn", "muxerFactory", "cryptoProtocol", "protectedConn", "protector", "CustomProgressEvent", "InvalidMultiaddrError", "InvalidPeerIdError", "multiplexed", "limits", "newStream", "muxedStream", "protocols", "handle", "incomingLimit", "TooManyInboundProtocolStreamsError", "MuxerUnavailableError", "select", "outgoingLimit", "TooManyOutboundProtocolStreamsError", "_timeline", "errConnectionNotMultiplexed", "createConnection", "handler", "LimitedConnectionError", "EncryptionFailedError", "muxers", "version", "name", "userAgent", "name", "version", "Libp2p", "TypedEventEmitter", "init", "events", "originalDispatch", "evt", "internalResult", "externalResult", "defaultLogger", "nodeInfoName", "name", "nodeInfoVersion", "version", "components", "defaultComponents", "userAgent", "MemoryDatastore", "connectionGater", "persistentPeerStore", "peerInfo", "a", "Upgrader", "fn", "index", "DefaultTransportManager", "DefaultConnectionManager", "ConnectionMonitor", "Registrar", "AddressManager", "peerRouters", "DefaultPeerRouting", "contentRouters", "CompoundContentRouting", "RandomWalk", "#onDiscoveryPeer", "createService", "service", "contentRoutingSymbol", "peerRoutingSymbol", "peerDiscoverySymbol", "checkServiceDependencies", "component", "err", "peerId", "peerSet", "PeerSet", "conn", "peer", "options", "protocols", "InvalidParametersError", "isMultiaddr", "peerIdFromString", "peerKey", "concat", "fromString", "bytes", "publicKey", "publicKeyFromProtobuf", "handler", "protocol", "topology", "id", "multiaddr", "createLibp2p", "options", "generateKeyPair", "node", "Libp2p", "validateConfig", "peerIdFromPrivateKey"]
|
|
7
|
+
}
|