libp2p 2.10.0-a02cb0461 → 2.10.0-e8398d97e
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/README.md +39 -37
- package/dist/index.min.js +13 -12
- package/dist/index.min.js.map +4 -4
- package/dist/src/address-manager/dns-mappings.d.ts +1 -2
- package/dist/src/address-manager/dns-mappings.d.ts.map +1 -1
- package/dist/src/address-manager/dns-mappings.js +39 -42
- package/dist/src/address-manager/dns-mappings.js.map +1 -1
- package/dist/src/address-manager/index.d.ts.map +1 -1
- package/dist/src/address-manager/index.js +31 -12
- package/dist/src/address-manager/index.js.map +1 -1
- package/dist/src/address-manager/ip-mappings.d.ts +1 -0
- package/dist/src/address-manager/ip-mappings.d.ts.map +1 -1
- package/dist/src/address-manager/ip-mappings.js +51 -40
- package/dist/src/address-manager/ip-mappings.js.map +1 -1
- package/dist/src/address-manager/transport-addresses.js +6 -6
- package/dist/src/address-manager/transport-addresses.js.map +1 -1
- package/dist/src/config/connection-gater.browser.d.ts.map +1 -1
- package/dist/src/config/connection-gater.browser.js +8 -22
- package/dist/src/config/connection-gater.browser.js.map +1 -1
- package/dist/src/config/connection-gater.d.ts.map +1 -1
- package/dist/src/config/connection-gater.js +1 -12
- package/dist/src/config/connection-gater.js.map +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +3 -22
- package/dist/src/config.js.map +1 -1
- package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
- package/dist/src/connection-manager/connection-pruner.js +6 -1
- package/dist/src/connection-manager/connection-pruner.js.map +1 -1
- package/dist/src/connection-manager/dial-queue.js +2 -2
- package/dist/src/connection-manager/dial-queue.js.map +1 -1
- package/dist/src/connection-manager/index.d.ts +0 -16
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js +18 -10
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/connection-manager/utils.d.ts +3 -3
- package/dist/src/connection-manager/utils.d.ts.map +1 -1
- package/dist/src/connection-manager/utils.js +24 -21
- package/dist/src/connection-manager/utils.js.map +1 -1
- package/dist/src/connection.d.ts +1 -0
- package/dist/src/connection.d.ts.map +1 -1
- package/dist/src/connection.js +32 -2
- package/dist/src/connection.js.map +1 -1
- package/dist/src/get-peer.js +3 -3
- package/dist/src/get-peer.js.map +1 -1
- package/dist/src/libp2p.d.ts +3 -1
- package/dist/src/libp2p.d.ts.map +1 -1
- package/dist/src/libp2p.js +11 -5
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/registrar.d.ts +5 -1
- package/dist/src/registrar.d.ts.map +1 -1
- package/dist/src/registrar.js +17 -6
- package/dist/src/registrar.js.map +1 -1
- package/dist/src/upgrader.d.ts.map +1 -1
- package/dist/src/upgrader.js +3 -2
- package/dist/src/upgrader.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +13 -13
- package/src/address-manager/dns-mappings.ts +50 -49
- package/src/address-manager/index.ts +36 -14
- package/src/address-manager/ip-mappings.ts +64 -44
- package/src/address-manager/transport-addresses.ts +7 -7
- package/src/config/connection-gater.browser.ts +8 -24
- package/src/config/connection-gater.ts +1 -12
- package/src/config.ts +3 -25
- package/src/connection-manager/connection-pruner.ts +7 -1
- package/src/connection-manager/dial-queue.ts +2 -2
- package/src/connection-manager/index.ts +20 -28
- package/src/connection-manager/utils.ts +26 -22
- package/src/connection.ts +40 -3
- package/src/get-peer.ts +3 -3
- package/src/libp2p.ts +14 -6
- package/src/registrar.ts +21 -8
- package/src/upgrader.ts +3 -2
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2P=(()=>{var um=Object.create;var Yo=Object.defineProperty;var fm=Object.getOwnPropertyDescriptor;var dm=Object.getOwnPropertyNames;var hm=Object.getPrototypeOf,pm=Object.prototype.hasOwnProperty;var ka=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Me=(r,e)=>{for(var t in e)Yo(r,t,{get:e[t],enumerable:!0})},uf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dm(e))!pm.call(r,o)&&o!==t&&Yo(r,o,{get:()=>e[o],enumerable:!(n=fm(e,o))||n.enumerable});return r};var Na=(r,e,t)=>(t=r!=null?um(hm(r)):{},uf(e||!r||!r.__esModule?Yo(t,"default",{value:r,enumerable:!0}):t,r)),mm=r=>uf(Yo({},"__esModule",{value:!0}),r);var zh=ka(Io=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},i=function(c){var l,u,f,d,h,p;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],u=p[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+t(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+t(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=(function(){function c(l,u){var f,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw f=m,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),Io.ip2long=i,Io.long2ip=a,Io.Netmask=r}).call(Io)});var np=ka((SI,lu)=>{"use strict";var Lb=Object.prototype.hasOwnProperty,ke="~";function Oo(){}Object.create&&(Oo.prototype=Object.create(null),new Oo().__proto__||(ke=!1));function Db(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function rp(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Db(t,n||r,o),i=ke?ke+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function mi(r,e){--r._eventsCount===0?r._events=new Oo:delete r._events[e]}function Ae(){this._events=new Oo,this._eventsCount=0}Ae.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Lb.call(t,n)&&e.push(ke?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ae.prototype.listeners=function(e){var t=ke?ke+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ae.prototype.listenerCount=function(e){var t=ke?ke+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ae.prototype.emit=function(e,t,n,o,s,i){var a=ke?ke+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Ae.prototype.on=function(e,t,n){return rp(this,e,t,n,!1)};Ae.prototype.once=function(e,t,n){return rp(this,e,t,n,!0)};Ae.prototype.removeListener=function(e,t,n,o){var s=ke?ke+e:e;if(!this._events[s])return this;if(!t)return mi(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&mi(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:mi(this,s)}return this};Ae.prototype.removeAllListeners=function(e){var t;return e?(t=ke?ke+e:e,this._events[t]&&mi(this,t)):(this._events=new Oo,this._eventsCount=0),this};Ae.prototype.off=Ae.prototype.removeListener;Ae.prototype.addListener=Ae.prototype.on;Ae.prefixed=ke;Ae.EventEmitter=Ae;typeof lu<"u"&&(lu.exports=Ae)});var ip=ka((HI,sp)=>{sp.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var sx={};Me(sx,{createLibp2p:()=>rx,dnsaddrResolver:()=>Nt,isLibp2p:()=>ox});var ff=Symbol.for("@libp2p/connection");var Ma=Symbol.for("@libp2p/content-routing");var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var O=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Kr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Nn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var nr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var or=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},qr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ut=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Qo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Jo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},es=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},ts=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var rs=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},gt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Vr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Mn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ns=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},os=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ft=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ss=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Ba=Symbol.for("@libp2p/peer-discovery");var is=Symbol.for("@libp2p/peer-id");function Kt(r){return!!r?.[is]}var Ua=Symbol.for("@libp2p/peer-routing");var Fa="keep-alive";function as(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function df(...r){let e=[];for(let t of r)as(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function hf(...r){let e=[];for(let t of r)as(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var gx=Symbol.for("@libp2p/transport");var sr;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(sr||(sr={}));var Ie=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Bn=Symbol.for("@libp2p/service-capabilities"),Ka=Symbol.for("@libp2p/service-dependencies");var Ha={};Me(Ha,{base58btc:()=>Z,base58flickr:()=>vm});var Hx=new Uint8Array(0);function pf(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function yt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function mf(r){return new TextEncoder().encode(r)}function gf(r){return new TextDecoder().decode(r)}function gm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,w=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,m++;for(var E=(_-g)*u+1>>>0,I=new Uint8Array(E);g!==_;){for(var k=p[g],q=0,V=E-1;(k!==0||q<w)&&V!==-1;V--,q++)k+=256*I[V]>>>0,I[V]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");w=q,g++}for(var N=E-w;N!==E&&I[N]===0;)N++;for(var v=c.repeat(m);N<E;++N)v+=r.charAt(I[N]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var w=0,g=0;p[m]===c;)w++,m++;for(var _=(p.length-m)*l+1>>>0,E=new Uint8Array(_);p[m];){var I=t[p.charCodeAt(m)];if(I===255)return;for(var k=0,q=_-1;(I!==0||k<g)&&q!==-1;q--,k++)I+=a*E[q]>>>0,E[q]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");g=k,m++}if(p[m]!==" "){for(var V=_-g;V!==_&&E[V]===0;)V++;for(var N=new Uint8Array(w+(_-V)),v=w;V!==_;)N[v++]=E[V++];return N}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var ym=gm,bm=ym,bf=bm;var qa=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Va=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return wf(this,e)}},za=class{decoders;constructor(e){this.decoders=e}or(e){return wf(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function wf(r,e){return new za({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var $a=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new qa(e,t,n),this.decoder=new Va(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zr({name:r,prefix:e,encode:t,decode:n}){return new $a(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=bf(t,r);return zr({prefix:e,name:r,encode:n,decode:s=>yt(o(s))})}function wm(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function xm(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Em(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Em(n);return zr({prefix:e,name:r,encode(s){return xm(s,n,t)},decode(s){return wm(s,o,t,r)}})}var Z=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vm=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ga={};Me(Ga,{base32:()=>We,base32hex:()=>Cm,base32hexpad:()=>Tm,base32hexpadupper:()=>Pm,base32hexupper:()=>Im,base32pad:()=>_m,base32padupper:()=>Am,base32upper:()=>Sm,base32z:()=>Lm});var We=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sm=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_m=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Am=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Cm=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Im=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tm=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pm=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Lm=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Wa={};Me(Wa,{base36:()=>Un,base36upper:()=>Dm});var Un=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dm=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Om=vf,xf=128,Rm=127,km=~Rm,Nm=Math.pow(2,31);function vf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Nm;)e[t++]=r&255|xf,r/=128;for(;r&km;)e[t++]=r&255|xf,r>>>=7;return e[t]=r|0,vf.bytes=t-n+1,e}var Mm=ja,Bm=128,Ef=127;function ja(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ja.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Ef)<<o:(i&Ef)*Math.pow(2,o),o+=7}while(i>=Bm);return ja.bytes=s-n,t}var Um=Math.pow(2,7),Fm=Math.pow(2,14),Km=Math.pow(2,21),qm=Math.pow(2,28),Vm=Math.pow(2,35),zm=Math.pow(2,42),$m=Math.pow(2,49),Hm=Math.pow(2,56),Gm=Math.pow(2,63),Wm=function(r){return r<Um?1:r<Fm?2:r<Km?3:r<qm?4:r<Vm?5:r<zm?6:r<$m?7:r<Hm?8:r<Gm?9:10},jm={encode:Om,decode:Mm,encodingLength:Wm},Xm=jm,Fn=Xm;function Kn(r,e=0){return[Fn.decode(r,e),Fn.decode.bytes]}function $r(r,e,t=0){return Fn.encode(r,e,t),e}function Hr(r){return Fn.encodingLength(r)}function ut(r,e){let t=e.byteLength,n=Hr(r),o=n+Hr(t),s=new Uint8Array(o+t);return $r(r,s,0),$r(t,s,n),s.set(e,o),new Gr(r,t,e,s)}function bt(r){let e=yt(r),[t,n]=Kn(e),[o,s]=Kn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Gr(t,o,i,e)}function Sf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&pf(r.bytes,t.bytes)}}var Gr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function _f(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ym(t,Xa(r),e??Z.encoder);default:return Qm(t,Xa(r),e??We.encoder)}}var Af=new WeakMap;function Xa(r){let e=Af.get(r);if(e==null){let t=new Map;return Af.set(r,t),t}return e}var ne=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==qn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Jm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ut(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Sf(e.multihash,n.multihash)}toString(e){return _f(this,e)}toJSON(){return{"/":_f(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Cf(n,o,s.bytes))}else if(t[eg]===!0){let{version:n,multihash:o,code:s}=t,i=bt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==qn)throw new Error(`Version 0 CID must use dag-pb (code: ${qn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Cf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,qn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=yt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Gr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Kn(e.subarray(t));return t+=d,f},o=n(),s=qn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Zm(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Xa(s).set(n,e),s}};function Zm(r,e){switch(r[0]){case"Q":{let t=e??Z;return[Z.prefix,t.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let t=e??Z;return[Z.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Un.prefix:{let t=e??Un;return[Un.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ym(r,e,t){let{prefix:n}=t;if(n!==Z.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Qm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var qn=112,Jm=18;function Cf(r,e,t){let n=Hr(r),o=n+Hr(e),s=new Uint8Array(o+t.byteLength);return $r(r,s,0),$r(e,s,n),s.set(t,o),s}var eg=Symbol.for("@ipld/js-cid/CID");var Za={};Me(Za,{identity:()=>et});var If=0,tg="identity",Tf=yt;function rg(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ut(If,Tf(r))}var et={code:If,name:tg,encode:Tf,digest:rg};function X(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ce(r=0){return new Uint8Array(r)}function Ee(r=0){return new Uint8Array(r)}function tt(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Ee(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Lf=Symbol.for("@achingbrain/uint8arraylist");function Pf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ls(r){return!!r?.[Lf]}var Y=class r{bufs;length;[Lf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ls(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ls(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Pf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Pf(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ls(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return tt(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:tt(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ls(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ee(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ee(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!X(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Ya={};Me(Ya,{base10:()=>ng});var ng=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var Qa={};Me(Qa,{base16:()=>og,base16upper:()=>sg});var og=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sg=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ja={};Me(Ja,{base2:()=>ig});var ig=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ec={};Me(ec,{base256emoji:()=>fg});var Df=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),ag=Df.reduce((r,e,t)=>(r[t]=e,r),[]),cg=Df.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function lg(r){return r.reduce((e,t)=>(e+=ag[t],e),"")}function ug(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=cg[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var fg=zr({prefix:"\u{1F680}",name:"base256emoji",encode:lg,decode:ug});var nc={};Me(nc,{base64:()=>tc,base64pad:()=>dg,base64url:()=>rc,base64urlpad:()=>hg});var tc=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dg=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rc=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hg=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var oc={};Me(oc,{base8:()=>pg});var pg=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var sc={};Me(sc,{identity:()=>mg});var mg=zr({prefix:"\0",name:"identity",encode:r=>gf(r),decode:r=>mf(r)});var TE=new TextEncoder,PE=new TextDecoder;var cc={};Me(cc,{sha256:()=>Wr,sha512:()=>wg});var bg=20;function ac({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ic(r,e,t,n,o)}var ic=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??bg,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Of(n,this.code,t?.truncate):n.then(o=>Of(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Of(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ut(e,r)}function kf(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Wr=ac({name:"sha2-256",code:18,encode:kf("SHA-256")}),wg=ac({name:"sha2-512",code:19,encode:kf("SHA-512")});var Vn={...sc,...Ja,...oc,...Ya,...Qa,...Ga,...Wa,...Ha,...nc,...ec},qE={...cc,...Za};function Mf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Nf=Mf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),lc=Mf("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ee(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),xg={utf8:Nf,"utf-8":Nf,hex:Vn.base16,latin1:lc,ascii:lc,binary:lc,...Vn},us=xg;function C(r,e="utf8"){let t=us[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function U(r,e="utf8"){let t=us[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Eg=parseInt("11111",2),uc=parseInt("10000000",2),vg=parseInt("01111111",2),Bf={0:zn,1:zn,2:Sg,3:Cg,4:Ig,5:Ag,6:_g,16:zn,22:zn,48:zn};function wt(r,e={offset:0}){let t=r[e.offset]&Eg;if(e.offset++,Bf[t]!=null)return Bf[t](r,e);throw new Error("No decoder for tag "+t)}function $n(r,e){let t=0;if((r[e.offset]&uc)===uc){let n=r[e.offset]&vg,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function zn(r,e){$n(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=wt(r,e);if(n===null)break;t.push(n)}return t}function Sg(r,e){let t=$n(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function _g(r,e){let t=$n(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Ag(r,e){return e.offset++,null}function Cg(r,e){let t=$n(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Ig(r,e){let t=$n(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Tg(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function fs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Tg(r.byteLength);return new Y(Uint8Array.from([e.byteLength|uc]),e)}function Te(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),fs(e),e)}function Hn(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),fs(t),t)}function Uf(r){return new Y(Uint8Array.from([4]),fs(r),r)}function rt(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),fs(t),t)}async function Ff(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Kf(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function qf(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var Pg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Lg=Uint8Array.from([6,5,43,129,4,0,34]),Dg=Uint8Array.from([6,5,43,129,4,0,35]),Og={ext:!0,kty:"EC",crv:"P-256"},Rg={ext:!0,kty:"EC",crv:"P-384"},kg={ext:!0,kty:"EC",crv:"P-521"},fc=32,dc=48,hc=66;function pc(r){let e=wt(r);return Vf(e)}function Vf(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===fc*2+1)return n=U(e.subarray(t,t+fc),"base64url"),o=U(e.subarray(t+fc),"base64url"),new ir({...Og,key_ops:["verify"],x:n,y:o});if(e.byteLength===dc*2+1)return n=U(e.subarray(t,t+dc),"base64url"),o=U(e.subarray(t+dc),"base64url"),new ir({...Rg,key_ops:["verify"],x:n,y:o});if(e.byteLength===hc*2+1)return n=U(e.subarray(t,t+hc),"base64url"),o=U(e.subarray(t+hc),"base64url"),new ir({...kg,key_ops:["verify"],x:n,y:o});throw new O(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function zf(r){return rt([Te(Uint8Array.from([1])),Uf(C(r.d??"","base64url")),rt([Hf(r.crv)],160),rt([Hn(new Y(Uint8Array.from([4]),C(r.x??"","base64url"),C(r.y??"","base64url")))],161)]).subarray()}function $f(r){return rt([Te(Uint8Array.from([1])),rt([Hf(r.crv)],160),rt([Hn(new Y(Uint8Array.from([4]),C(r.x??"","base64url"),C(r.y??"","base64url")))],161)]).subarray()}function Hf(r){if(r==="P-256")return Pg;if(r==="P-384")return Lg;if(r==="P-521")return Dg;throw new O(`Invalid curve ${r}`)}async function Gf(r="P-256"){let e=await Ff(r);return new ds(e.privateKey)}var ir=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=$f(this.jwk)),this._raw}toMultihash(){return et.digest(je(this))}toCID(){return ne.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}async verify(e,t,n){return qf(this.jwk,t,e,n)}},ds=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new ir({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=zf(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}async sign(e,t){return Kf(this.jwk,e,t)}};var ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Et(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Gn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Be(r,...e){if(!Et(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function hs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Gn(r.outputLen),Gn(r.blockLen)}function Xr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function jf(r,e){Be(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function vt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ps(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function nt(r,e){return r<<32-e|r>>>e}var Xf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ng=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Xe(r){if(Be(r),Xf)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Ng[r[t]];return e}var xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wf(r){if(r>=xt._0&&r<=xt._9)return r-xt._0;if(r>=xt.A&&r<=xt.F)return r-(xt.A-10);if(r>=xt.a&&r<=xt.f)return r-(xt.a-10)}function cr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Xf)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Wf(r.charCodeAt(s)),a=Wf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function mc(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Wn(r){return typeof r=="string"&&(r=mc(r)),Be(r),r}function Pe(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Be(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var jr=class{};function gc(r){let e=n=>r().update(Wn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function zt(r=32){if(ar&&typeof ar.getRandomValues=="function")return ar.getRandomValues(new Uint8Array(r));if(ar&&typeof ar.randomBytes=="function")return Uint8Array.from(ar.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Mg(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function Zf(r,e,t){return r&e^~r&t}function Yf(r,e,t){return r&e^r&t^e&t}var jn=class extends jr{constructor(e,t,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ps(this.buffer)}update(e){Xr(this),e=Wn(e),Be(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ps(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xr(this),jf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,vt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;Mg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=ps(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},St=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var be=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ms=BigInt(4294967295),Qf=BigInt(32);function Bg(r,e=!1){return e?{h:Number(r&ms),l:Number(r>>Qf&ms)}:{h:Number(r>>Qf&ms)|0,l:Number(r&ms)|0}}function Jf(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Bg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var yc=(r,e,t)=>r>>>t,bc=(r,e,t)=>r<<32-t|e>>>t,lr=(r,e,t)=>r>>>t|e<<32-t,ur=(r,e,t)=>r<<32-t|e>>>t,Xn=(r,e,t)=>r<<64-t|e>>>t-32,Zn=(r,e,t)=>r>>>t-32|e<<64-t;function ft(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var ed=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),td=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,rd=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),nd=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,od=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),sd=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Fg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array(64),gs=class extends jn{constructor(e=32){super(64,e,8,!1),this.A=St[0]|0,this.B=St[1]|0,this.C=St[2]|0,this.D=St[3]|0,this.E=St[4]|0,this.F=St[5]|0,this.G=St[6]|0,this.H=St[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)$t[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=$t[f-15],h=$t[f-2],p=nt(d,7)^nt(d,18)^d>>>3,m=nt(h,17)^nt(h,19)^h>>>10;$t[f]=m+$t[f-7]+p+$t[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=nt(a,6)^nt(a,11)^nt(a,25),h=u+d+Zf(a,c,l)+Fg[f]+$t[f]|0,m=(nt(n,2)^nt(n,13)^nt(n,22))+Yf(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){vt($t)}destroy(){this.set(0,0,0,0,0,0,0,0),vt(this.buffer)}};var id=Jf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Kg=id[0],qg=id[1],Ht=new Uint32Array(80),Gt=new Uint32Array(80),wc=class extends jn{constructor(e=64){super(128,e,16,!1),this.Ah=be[0]|0,this.Al=be[1]|0,this.Bh=be[2]|0,this.Bl=be[3]|0,this.Ch=be[4]|0,this.Cl=be[5]|0,this.Dh=be[6]|0,this.Dl=be[7]|0,this.Eh=be[8]|0,this.El=be[9]|0,this.Fh=be[10]|0,this.Fl=be[11]|0,this.Gh=be[12]|0,this.Gl=be[13]|0,this.Hh=be[14]|0,this.Hl=be[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:p,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,p,m,w]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,p,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let E=0;E<16;E++,t+=4)Ht[E]=e.getUint32(t),Gt[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let I=Ht[E-15]|0,k=Gt[E-15]|0,q=lr(I,k,1)^lr(I,k,8)^yc(I,k,7),V=ur(I,k,1)^ur(I,k,8)^bc(I,k,7),N=Ht[E-2]|0,v=Gt[E-2]|0,L=lr(N,v,19)^Xn(N,v,61)^yc(N,v,6),F=ur(N,v,19)^Zn(N,v,61)^bc(N,v,6),D=rd(V,F,Gt[E-7],Gt[E-16]),x=nd(D,q,L,Ht[E-7],Ht[E-16]);Ht[E]=x|0,Gt[E]=D|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:p,Gh:m,Gl:w,Hh:g,Hl:_}=this;for(let E=0;E<80;E++){let I=lr(f,d,14)^lr(f,d,18)^Xn(f,d,41),k=ur(f,d,14)^ur(f,d,18)^Zn(f,d,41),q=f&h^~f&m,V=d&p^~d&w,N=od(_,k,V,qg[E],Gt[E]),v=sd(N,g,I,q,Kg[E],Ht[E]),L=N|0,F=lr(n,o,28)^Xn(n,o,34)^Xn(n,o,39),D=ur(n,o,28)^Zn(n,o,34)^Zn(n,o,39),x=n&s^n&a^s&a,y=o&i^o&c^i&c;g=m|0,_=w|0,m=h|0,w=p|0,h=f|0,p=d|0,{h:f,l:d}=ft(l|0,u|0,v|0,L|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=ed(L,D,y);n=td(b,v,F,x),o=b|0}({h:n,l:o}=ft(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ft(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ft(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ft(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ft(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ft(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:w}=ft(this.Gh|0,this.Gl|0,m|0,w|0),{h:g,l:_}=ft(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,l,u,f,d,h,p,m,w,g,_)}roundClean(){vt(Ht,Gt)}destroy(){vt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ys=gc(()=>new gs);var ad=gc(()=>new wc);var vc=BigInt(0),Ec=BigInt(1);function _t(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function qe(r,e,t=""){let n=Et(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Yn(r){let e=r.toString(16);return e.length&1?"0"+e:e}function cd(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?vc:BigInt("0x"+r)}function Zr(r){return cd(Xe(r))}function At(r){return Be(r),cd(Xe(Uint8Array.from(r).reverse()))}function bs(r,e){return cr(r.toString(16).padStart(e*2,"0"))}function Sc(r,e){return bs(r,e).reverse()}function Q(r,e,t){let n;if(typeof e=="string")try{n=cr(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Et(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function ld(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function _c(r){return Uint8Array.from(r)}var xc=r=>typeof r=="bigint"&&vc<=r;function ud(r,e,t){return xc(r)&&xc(e)&&xc(t)&&e<=r&&r<t}function Qn(r,e,t,n){if(!ud(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function ws(r){let e;for(e=0;r>vc;r>>=Ec,e+=1);return e}var Wt=r=>(Ec<<BigInt(r))-Ec;function fd(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>t(i,s,...h),u=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<e;){s=l();let m=s.slice();p.push(m),h+=s.length}return Pe(...p)};return(h,p)=>{c(),u(h);let m;for(;!(m=p(f()));)u();return c(),m}}function jt(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(t).forEach(([o,s])=>n(o,s,!0))}var Ac=()=>{throw new Error("not implemented")};function Yr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var Le=BigInt(0),he=BigInt(1),fr=BigInt(2),pd=BigInt(3),md=BigInt(4),gd=BigInt(5),Vg=BigInt(7),yd=BigInt(8),zg=BigInt(9),bd=BigInt(16);function le(r,e){let t=r%e;return t>=Le?t:e+t}function te(r,e,t){let n=r;for(;e-- >Le;)n*=n,n%=t;return n}function dd(r,e){if(r===Le)throw new Error("invert: expected non-zero number");if(e<=Le)throw new Error("invert: expected positive modulus, got "+e);let t=le(r,e),n=e,o=Le,s=he,i=he,a=Le;for(;t!==Le;){let l=n/t,u=n%t,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==he)throw new Error("invert: does not exist");return le(o,e)}function Cc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function wd(r,e){let t=(r.ORDER+he)/md,n=r.pow(e,t);return Cc(r,n,e),n}function $g(r,e){let t=(r.ORDER-gd)/yd,n=r.mul(e,fr),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,fr),o),a=r.mul(s,r.sub(i,r.ONE));return Cc(r,a,e),a}function Hg(r){let e=Ve(r),t=xd(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Vg)/bd;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let m=a.eql(a.sqr(u),c),w=a.cmov(l,u,m);return Cc(a,w,c),w}}function xd(r){if(r<pd)throw new Error("sqrt is not defined for small field");let e=r-he,t=0;for(;e%fr===Le;)e/=fr,t++;let n=fr,o=Ve(r);for(;hd(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return wd;let s=o.pow(n,e),i=(e+he)/fr;return function(c,l){if(c.is0(l))return l;if(hd(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let w=he<<BigInt(u-p-1),g=c.pow(f,w);u=p,f=c.sqr(g),d=c.mul(d,f),h=c.mul(h,g)}return h}}function Gg(r){return r%md===pd?wd:r%yd===gd?$g:r%bd===zg?Hg(r):xd(r)}var Ct=(r,e)=>(le(r,e)&he)===he,Wg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ic(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Wg.reduce((n,o)=>(n[o]="function",n),e);return jt(r,t),r}function jg(r,e,t){if(t<Le)throw new Error("invalid exponent, negatives unsupported");if(t===Le)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>Le;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function Jn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function hd(r,e){let t=(r.ORDER-he)/fr,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function xs(r,e){e!==void 0&&Gn(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Ve(r,e,t=!1,n={}){if(r<=Le)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(o=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:l}=xs(r,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Wt(c),ZERO:Le,ONE:he,allowedLengths:a,create:d=>le(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Le<=d&&d<r},is0:d=>d===Le,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&he)===he,neg:d=>le(-d,r),eql:(d,h)=>d===h,sqr:d=>le(d*d,r),add:(d,h)=>le(d+h,r),sub:(d,h)=>le(d-h,r),mul:(d,h)=>le(d*h,r),pow:(d,h)=>jg(f,d,h),div:(d,h)=>le(d*dd(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>dd(d,r),sqrt:s||(d=>(u||(u=Gg(r)),u(f,d))),toBytes:d=>t?Sc(d,l):bs(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?At(d):Zr(d);if(i&&(p=le(p,r)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>Jn(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function Ed(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Tc(r){let e=Ed(r);return e+Math.ceil(e/2)}function Pc(r,e,t=!1){let n=r.length,o=Ed(e),s=Tc(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?At(r):Zr(r),a=le(i,e-he)+he;return t?Sc(a,o):bs(a,o)}var Qr=BigInt(0),dr=BigInt(1);function eo(r,e){let t=e.negate();return r?t:e}function It(r,e){let t=Jn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Ad(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Lc(r,e){Ad(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Wt(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function vd(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=dr);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}function Xg(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Zg(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var Dc=new WeakMap,Cd=new WeakMap;function Oc(r){return Cd.get(r)||1}function Sd(r){if(r!==Qr)throw new Error("invalid wNAF")}var Jr=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Qr;)t&dr&&(n=n.add(o)),o=o.double(),t>>=dr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Lc(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Lc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=vd(n,a,i);n=c,u?s=s.add(eo(d,t[h])):o=o.add(eo(f,t[l]))}return Sd(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Lc(e,this.bits);for(let i=0;i<s.windows&&n!==Qr;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=vd(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return Sd(n),o}getPrecomputes(e,t,n){let o=Dc.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Dc.set(t,o))),o}cached(e,t,n){let o=Oc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Oc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){Ad(t,this.bits),Cd.set(e,t),Dc.delete(e)}hasCache(e){return Oc(e)!==1}};function Id(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Qr||n>Qr;)t&dr&&(s=s.add(o)),n&dr&&(i=i.add(o)),o=o.double(),t>>=dr,n>>=dr;return{p1:s,p2:i}}function en(r,e,t,n){Xg(t,r),Zg(n,e);let o=t.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=ws(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Wt(c),u=new Array(Number(l)+1).fill(i),f=Math.floor((e.BITS-1)/c)*c,d=i;for(let h=f;h>=0;h-=c){u.fill(i);for(let m=0;m<s;m++){let w=n[m],g=Number(w>>BigInt(h)&l);u[g]=u[g].add(t[m])}let p=i;for(let m=u.length-1,w=i;m>0;m--)w=w.add(u[m]),p=p.add(w);if(d=d.add(p),h!==0)for(let m=0;m<c;m++)d=d.double()}return d}function _d(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ic(e),e}else return Ve(r,{isLE:t})}function Es(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Qr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=_d(e.p,t.Fp,n),s=_d(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}var Xt=BigInt(0),pe=BigInt(1),Rc=BigInt(2),Yg=BigInt(8);function Qg(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Jg(r,e={}){let t=Es("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;jt(e,{},{uvRatio:"function"});let a=Rc<<BigInt(o.BYTES*8)-pe,c=w=>n.create(w),l=e.uvRatio||((w,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,g))}}catch{return{isValid:!1,value:Xt}}});if(!Qg(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(w,g,_=!1){let E=_?pe:Xt;return Qn("coordinate "+w,g,E,a),g}function f(w){if(!(w instanceof p))throw new Error("ExtendedPoint expected")}let d=Yr((w,g)=>{let{X:_,Y:E,Z:I}=w,k=w.is0();g==null&&(g=k?Yg:n.inv(I));let q=c(_*g),V=c(E*g),N=n.mul(I,g);if(k)return{x:Xt,y:pe};if(N!==pe)throw new Error("invZ was invalid");return{x:q,y:V}}),h=Yr(w=>{let{a:g,d:_}=s;if(w.is0())throw new Error("bad point: ZERO");let{X:E,Y:I,Z:k,T:q}=w,V=c(E*E),N=c(I*I),v=c(k*k),L=c(v*v),F=c(V*g),D=c(v*c(F+N)),x=c(L+c(_*c(V*N)));if(D!==x)throw new Error("bad point: equation left != right (1)");let y=c(E*I),b=c(k*q);if(y!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,E,I){this.X=u("x",g),this.Y=u("y",_),this.Z=u("z",E,!0),this.T=u("t",I),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:E}=g||{};return u("x",_),u("y",E),new p(_,E,pe,c(_*E))}static fromBytes(g,_=!1){let E=n.BYTES,{a:I,d:k}=s;g=_c(qe(g,E,"point")),_t(_,"zip215");let q=_c(g),V=g[E-1];q[E-1]=V&-129;let N=At(q),v=_?a:n.ORDER;Qn("point.y",N,Xt,v);let L=c(N*N),F=c(L-pe),D=c(k*L-I),{isValid:x,value:y}=l(F,D);if(!x)throw new Error("bad point: invalid y coordinate");let b=(y&pe)===pe,S=(V&128)!==0;if(!_&&y===Xt&&S)throw new Error("bad point: x=0 and x_0=1");return S!==b&&(y=c(-y)),p.fromAffine({x:y,y:N})}static fromHex(g,_=!1){return p.fromBytes(Q("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return m.createCache(this,g),_||this.multiply(Rc),this}assertValidity(){h(this)}equals(g){f(g);let{X:_,Y:E,Z:I}=this,{X:k,Y:q,Z:V}=g,N=c(_*V),v=c(k*I),L=c(E*V),F=c(q*I);return N===v&&L===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:_,Y:E,Z:I}=this,k=c(_*_),q=c(E*E),V=c(Rc*c(I*I)),N=c(g*k),v=_+E,L=c(c(v*v)-k-q),F=N+q,D=F-V,x=N-q,y=c(L*D),b=c(F*x),S=c(L*x),A=c(D*F);return new p(y,b,A,S)}add(g){f(g);let{a:_,d:E}=s,{X:I,Y:k,Z:q,T:V}=this,{X:N,Y:v,Z:L,T:F}=g,D=c(I*N),x=c(k*v),y=c(V*E*F),b=c(q*L),S=c((I+k)*(N+v)-D-x),A=b-y,R=b+y,T=c(x-_*D),P=c(S*A),B=c(R*T),K=c(S*T),oe=c(A*R);return new p(P,B,oe,K)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=m.cached(this,g,I=>It(p,I));return It(p,[_,E])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Xt?p.ZERO:this.is0()||g===pe?this:m.unsafe(this,g,E=>It(p,E),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),E=n.toBytes(_);return E[E.length-1]|=g&pe?128:0,E}toHex(){return Xe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return It(p,g)}static msm(g,_){return en(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,pe,c(s.Gx*s.Gy)),p.ZERO=new p(Xt,pe,pe,Xt),p.Fp=n,p.Fn=o;let m=new Jr(p,o.BITS);return p.BASE.precompute(8),p}var vs=class{constructor(e){this.ep=e}static fromBytes(e){Ac()}static fromHex(e){Ac()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Xe(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function e0(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');jt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||zt,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,L,F)=>{if(_t(F,"phflag"),L.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(At(v))}function f(v){let L=E.secretKey;v=Q("private key",v,L);let F=Q("hashed private key",e(v),2*L),D=c(F.slice(0,L)),x=F.slice(L,2*L),y=u(D);return{head:D,prefix:x,scalar:y}}function d(v){let{head:L,prefix:F,scalar:D}=f(v),x=o.multiply(D),y=x.toBytes();return{head:L,prefix:F,scalar:D,point:x,pointBytes:y}}function h(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...L){let F=Pe(...L);return u(e(l(F,Q("context",v),!!n)))}function m(v,L,F={}){v=Q("message",v),n&&(v=n(v));let{prefix:D,scalar:x,pointBytes:y}=d(L),b=p(F.context,D,v),S=o.multiply(b).toBytes(),A=p(F.context,S,y,v),R=i.create(b+A*x);if(!i.isValid(R))throw new Error("sign failed: invalid s");let T=Pe(S,i.toBytes(R));return qe(T,E.signature,"result")}let w={zip215:!0};function g(v,L,F,D=w){let{context:x,zip215:y}=D,b=E.signature;v=Q("signature",v,b),L=Q("message",L),F=Q("publicKey",F,E.publicKey),y!==void 0&&_t(y,"zip215"),n&&(L=n(L));let S=b/2,A=v.subarray(0,S),R=At(v.subarray(S,b)),T,P,B;try{T=r.fromBytes(F,y),P=r.fromBytes(A,y),B=o.multiplyUnsafe(R)}catch{return!1}if(!y&&T.isSmallOrder())return!1;let K=p(x,P.toBytes(),T.toBytes(),L);return P.add(T.multiplyUnsafe(K)).subtract(B).clearCofactor().is0()}let _=s.BYTES,E={secretKey:_,publicKey:_,signature:2*_,seed:_};function I(v=a(E.seed)){return qe(v,E.seed,"seed")}function k(v){let L=N.randomSecretKey(v);return{secretKey:L,publicKey:h(L)}}function q(v){return Et(v)&&v.length===i.BYTES}function V(v,L){try{return!!r.fromBytes(v,L)}catch{return!1}}let N={getExtendedPublicKey:d,randomSecretKey:I,isValidSecretKey:q,isValidPublicKey:V,toMontgomery(v){let{y:L}=r.fromBytes(v),F=E.publicKey,D=F===32;if(!D&&F!==57)throw new Error("only defined for 25519 and 448");let x=D?s.div(pe+L,pe-L):s.div(L-pe,L+pe);return s.toBytes(x)},toMontgomerySecret(v){let L=E.secretKey;qe(v,L);let F=e(v.subarray(0,L));return c(F).subarray(0,L)},randomPrivateKey:I,precompute(v=8,L=r.BASE){return L.precompute(v,!1)}};return Object.freeze({keygen:k,getPublicKey:h,sign:m,verify:g,utils:N,Point:r,lengths:E})}function t0(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=Ve(e.n,r.nBitLength,!0),o={Fp:t,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:o,hash:r.hash,eddsaOpts:s}}function r0(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function Td(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:o}=t0(r),s=Jg(e,t),i=e0(s,n,o);return r0(r,i)}var n0=BigInt(0),Tt=BigInt(1),Pd=BigInt(2),Gv=BigInt(3),o0=BigInt(5),s0=BigInt(8),tn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),to={p:tn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:s0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function i0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=tn,a=r*r%s*r%s,c=te(a,Pd,s)*a%s,l=te(c,Tt,s)*r%s,u=te(l,o0,s)*l%s,f=te(u,e,s)*u%s,d=te(f,t,s)*f%s,h=te(d,n,s)*d%s,p=te(h,o,s)*h%s,m=te(p,o,s)*h%s,w=te(m,e,s)*u%s;return{pow_p_5_8:te(w,Pd,s)*r%s,b2:a}}function a0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var kc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Bc(r,e){let t=tn,n=le(e*e*e,t),o=le(n*n*e,t),s=i0(r*o).pow_p_5_8,i=le(r*n*s,t),a=le(e*i*i,t),c=i,l=le(i*kc,t),u=a===r,f=a===le(-r,t),d=a===le(-r*kc,t);return u&&(i=c),(f||d)&&(i=l),Ct(i,t)&&(i=le(-i,t)),{isValid:u||f,value:i}}var Zt=Ve(to.p,{isLE:!0}),c0=Ve(to.n,{isLE:!0}),l0={...to,Fp:Zt,hash:ad,adjustScalarBytes:a0,uvRatio:Bc},Ze=Td(l0);var Nc=kc,u0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),f0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),d0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),h0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Ld=r=>Bc(Tt,r),p0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Mc=r=>Ze.Point.Fp.create(At(r)&p0);function Dd(r){let{d:e}=to,t=tn,n=g=>Zt.create(g),o=n(Nc*r*r),s=n((o+Tt)*d0),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=Bc(s,a),u=n(l*r);Ct(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Tt)*h0-a),d=l*l,h=n((l+l)*a),p=n(f*u0),m=n(Tt-d),w=n(Tt+d);return new Ze.Point(n(h*w),n(m*p),n(p*w),n(h*m))}function m0(r){Be(r,64);let e=Mc(r.subarray(0,32)),t=Dd(e),n=Mc(r.subarray(32,64)),o=Dd(n);return new Pt(t.add(o))}var Pt=class r extends vs{constructor(e){super(e)}static fromAffine(e){return new r(Ze.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return m0(Q("ristrettoHash",e,64))}static fromBytes(e){Be(e,32);let{a:t,d:n}=to,o=tn,s=I=>Zt.create(I),i=Mc(e);if(!ld(Zt.toBytes(i),e)||Ct(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Tt+t*a),l=s(Tt-t*a),u=s(c*c),f=s(l*l),d=s(t*n*u-f),{isValid:h,value:p}=Ld(s(d*f)),m=s(p*l),w=s(p*m*d),g=s((i+i)*m);Ct(g,o)&&(g=s(-g));let _=s(c*w),E=s(g*_);if(!h||Ct(E,o)||_===n0)throw new Error("invalid ristretto255 encoding 2");return new r(new Ze.Point(g,_,Tt,E))}static fromHex(e){return r.fromBytes(Q("ristrettoHex",e,32))}static msm(e,t){return en(r,Ze.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=tn,i=w=>Zt.create(w),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=Ld(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),p;if(Ct(o*h,s)){let w=i(t*Nc),g=i(e*Nc);e=w,t=g,p=i(f*f0)}else p=d;Ct(e*h,s)&&(t=i(-t));let m=i((n-t)*p);return Ct(m,s)&&(m=i(-m)),Zt.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>Zt.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Pt.BASE=new Pt(Ze.Point.BASE);Pt.ZERO=new Pt(Ze.Point.ZERO);Pt.Fp=Zt;Pt.Fn=c0;var ro=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},no=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ss=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Od={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Ss("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ue=Od;var _s=32,oo=64,Uc=32;var rn,Rd=(async()=>{try{return await Ue.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function kd(){let r=Ze.utils.randomPrivateKey(),e=Ze.getPublicKey(r);return{privateKey:x0(r,e),publicKey:e}}async function g0(r,e){let t;r.length===oo?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:U(r.subarray(32),"base64url"),d:U(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ue.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ue.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function y0(r,e){let t=r.subarray(0,Uc);return Ze.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Nd(r,e){return rn==null&&(rn=await Rd),rn?g0(r,e):y0(r,e)}async function b0(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ue.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ue.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function w0(r,e,t){return Ze.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Md(r,e,t){return rn==null&&(rn=await Rd),rn?b0(r,e,t):w0(r,e,t)}function x0(r,e){let t=new Uint8Array(oo);for(let n=0;n<Uc;n++)t[n]=r[n],t[Uc+n]=e[n];return t}function nn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var so=class{type="Ed25519";raw;constructor(e){this.raw=Cs(e,_s)}toMultihash(){return et.digest(je(this))}toCID(){return ne.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Md(this.raw,t,e);return nn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},As=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Cs(e,oo),this.publicKey=new so(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Nd(this.raw,e);return nn(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function Fc(r){return r=Cs(r,_s),new so(r)}async function Ud(){let{privateKey:r,publicKey:e}=kd();return new As(r,e)}function Cs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new O(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var E0=Math.pow(2,7),v0=Math.pow(2,14),S0=Math.pow(2,21),Kc=Math.pow(2,28),qc=Math.pow(2,35),Vc=Math.pow(2,42),zc=Math.pow(2,49),W=128,ve=127;function me(r){if(r<E0)return 1;if(r<v0)return 2;if(r<S0)return 3;if(r<Kc)return 4;if(r<qc)return 5;if(r<Vc)return 6;if(r<zc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function on(r,e,t=0){switch(me(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function _0(r,e,t=0){switch(me(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function $c(r,e){let t=r[e],n=0;if(n+=t&ve,t<W||(t=r[e+1],n+=(t&ve)<<7,t<W)||(t=r[e+2],n+=(t&ve)<<14,t<W)||(t=r[e+3],n+=(t&ve)<<21,t<W)||(t=r[e+4],n+=(t&ve)*Kc,t<W)||(t=r[e+5],n+=(t&ve)*qc,t<W)||(t=r[e+6],n+=(t&ve)*Vc,t<W)||(t=r[e+7],n+=(t&ve)*zc,t<W))return n;throw new RangeError("Could not decode varint")}function A0(r,e){let t=r.get(e),n=0;if(n+=t&ve,t<W||(t=r.get(e+1),n+=(t&ve)<<7,t<W)||(t=r.get(e+2),n+=(t&ve)<<14,t<W)||(t=r.get(e+3),n+=(t&ve)<<21,t<W)||(t=r.get(e+4),n+=(t&ve)*Kc,t<W)||(t=r.get(e+5),n+=(t&ve)*qc,t<W)||(t=r.get(e+6),n+=(t&ve)*Vc,t<W)||(t=r.get(e+7),n+=(t&ve)*zc,t<W))return n;throw new RangeError("Could not decode varint")}function Yt(r,e,t=0){return e==null&&(e=Ee(me(r))),e instanceof Uint8Array?on(r,e,t):_0(r,e,t)}function hr(r,e=0){return r instanceof Uint8Array?$c(r,e):A0(r,e)}var Hc=new Float32Array([-0]),Qt=new Uint8Array(Hc.buffer);function Fd(r,e,t){Hc[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3]}function Kd(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],Hc[0]}var Gc=new Float64Array([-0]),Se=new Uint8Array(Gc.buffer);function qd(r,e,t){Gc[0]=r,e[t]=Se[0],e[t+1]=Se[1],e[t+2]=Se[2],e[t+3]=Se[3],e[t+4]=Se[4],e[t+5]=Se[5],e[t+6]=Se[6],e[t+7]=Se[7]}function Vd(r,e){return Se[0]=r[e],Se[1]=r[e+1],Se[2]=r[e+2],Se[3]=r[e+3],Se[4]=r[e+4],Se[5]=r[e+5],Se[6]=r[e+6],Se[7]=r[e+7],Gc[0]}var C0=BigInt(Number.MAX_SAFE_INTEGER),I0=BigInt(Number.MIN_SAFE_INTEGER),ze=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return pr;if(e<C0&&e>I0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>zd&&(o=0n,++n>zd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return pr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):pr}},pr=new ze(0,0);pr.toBigInt=function(){return 0n};pr.zzEncode=pr.zzDecode=function(){return this};pr.length=function(){return 1};var zd=4294967296n;function $d(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Hd(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Wc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ot(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Is(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var jc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ot(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ot(this,4);return Is(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return Is(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=Kd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=Vd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ot(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Hd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ze(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ot(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ot(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ot(this,8);let e=Is(this.buf,this.pos+=4),t=Is(this.buf,this.pos+=4);return new ze(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=$c(this.buf,this.pos);return this.pos+=me(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Xc(r){return new jc(r instanceof Uint8Array?r:r.subarray())}function De(r,e,t){let n=Xc(r);return e.decode(n,void 0,t)}function Zc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Ee(i);o+i>e&&(n=Ee(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Yc(){}var Jc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},T0=Zc();function P0(r){return globalThis.Buffer!=null?Ee(r):T0(r)}var co=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(Yc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new mr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new el((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ts,10,ze.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ze.fromBigInt(e);return this._push(Ts,t.length(),t)}uint64Number(e){return this._push(on,me(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ze.fromBigInt(e).zzEncode();return this._push(Ts,t.length(),t)}sint64Number(e){let t=ze.fromNumber(e).zzEncode();return this._push(Ts,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Qc,1,e?1:0)}fixed32(e){return this._push(ao,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ze.fromBigInt(e);return this._push(ao,4,t.lo)._push(ao,4,t.hi)}fixed64Number(e){let t=ze.fromNumber(e);return this._push(ao,4,t.lo)._push(ao,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Fd,4,e)}double(e){return this._push(qd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Qc,1,0):this.uint32(t)._push(D0,t,e)}string(e){let t=$d(e);return t!==0?this.uint32(t)._push(Wc,t,e):this._push(Qc,1,0)}fork(){return this.states=new Jc(this),this.head=this.tail=new mr(Yc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new mr(Yc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=P0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Qc(r,e,t){e[t]=r&255}function L0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var el=class extends mr{next;constructor(e,t){super(L0,e,t),this.next=void 0}};function Ts(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ao(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function D0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(co.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(O0,e,r),this},co.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(R0,e,r),this});function O0(r,e,t){e.set(r,t)}function R0(r,e,t){r.length<40?Wc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(C(r),t)}function tl(){return new co}function Oe(r,e){let t=tl();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var sn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(sn||(sn={}));function Ps(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function rl(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Ps("enum",sn.VARINT,t,n)}function Re(r,e){return Ps("message",sn.LENGTH_DELIMITED,r,e)}var gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},lo=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ue;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ue||(ue={}));var nl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(nl||(nl={}));(function(r){r.codec=()=>rl(nl)})(ue||(ue={}));var dt;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(dt||(dt={}));var ol;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(ol||(ol={}));function an(r){if(isNaN(r)||r<=0)throw new O("random bytes length must be a Number bigger than 0");return zt(r)}var fo={};Me(fo,{MAX_RSA_KEY_SIZE:()=>sl,generateRSAKeyPair:()=>pl,jwkToJWKKeyPair:()=>Yd,jwkToPkcs1:()=>B0,jwkToPkix:()=>ll,jwkToRSAPrivateKey:()=>hl,pkcs1MessageToJwk:()=>al,pkcs1MessageToRSAPrivateKey:()=>ul,pkcs1ToJwk:()=>M0,pkcs1ToRSAPrivateKey:()=>Zd,pkixMessageToJwk:()=>cl,pkixMessageToRSAPublicKey:()=>dl,pkixToJwk:()=>U0,pkixToRSAPublicKey:()=>fl});var Ls=ys;var cn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=fo.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ne.createV1(114,this._multihash)}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){return Xd(this.jwk,t,e,n)}},uo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=fo.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){return jd(this.jwk,e,t)}};var sl=8192,il=18,k0=1062,N0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function M0(r){let e=wt(r);return al(e)}function al(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function B0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new O("JWK was missing components");return rt([Te(Uint8Array.from([0])),Te(C(r.n,"base64url")),Te(C(r.e,"base64url")),Te(C(r.d,"base64url")),Te(C(r.p,"base64url")),Te(C(r.q,"base64url")),Te(C(r.dp,"base64url")),Te(C(r.dq,"base64url")),Te(C(r.qi,"base64url"))]).subarray()}function U0(r){let e=wt(r,{offset:0});return cl(e)}function cl(r){let e=wt(r[1],{offset:0});return{kty:"RSA",n:U(e[0],"base64url"),e:U(e[1],"base64url")}}function ll(r){if(r.n==null||r.e==null)throw new O("JWK was missing components");return rt([N0,Hn(rt([Te(C(r.n,"base64url")),Te(C(r.e,"base64url"))]))]).subarray()}function Zd(r){let e=wt(r);return ul(e)}function ul(r){let e=al(r);return hl(e)}function fl(r,e){if(r.byteLength>=k0)throw new Kr("Key size is too large");let t=wt(r,{offset:0});return dl(t,r,e)}function dl(r,e,t){let n=cl(r);if(t==null){let o=Ls(dt.encode({Type:ue.RSA,Data:e}));t=ut(il,o)}return new cn(n,t)}function hl(r){if(Jd(r)>sl)throw new O("Key size is too large");let e=Yd(r),t=Ls(dt.encode({Type:ue.RSA,Data:ll(e.publicKey)})),n=ut(il,t);return new uo(e.privateKey,new cn(e.publicKey,n))}async function pl(r){if(r>sl)throw new O("Key size is too large");let e=await Qd(r),t=Ls(dt.encode({Type:ue.RSA,Data:ll(e.publicKey)})),n=ut(il,t);return new uo(e.privateKey,new cn(e.publicKey,n))}function Yd(r){if(r==null)throw new O("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Qd(r,e){let t=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await F0(t,e);return{privateKey:n[0],publicKey:n[1]}}async function jd(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Xd(r,e,t,n){let o=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function F0(r,e){if(r.privateKey==null||r.publicKey==null)throw new O("Private and public key are required");let t=await Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Jd(r){if(r.kty!=="RSA")throw new O("invalid key type");if(r.n==null)throw new O("invalid key modulus");return C(r.n,"base64url").length*8}var Ds=class extends jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,hs(e);let n=Wn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),vt(s)}update(e){return Xr(this),this.iHash.update(e),this}digestInto(e){Xr(this),Be(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ml=(r,e,t)=>new Ds(r,e).update(t).digest();ml.create=(r,e)=>new Ds(r,e);var eh=(r,e)=>(r+(r>=0?e:-e)/th)/e;function K0(r,e,t){let[[n,o],[s,i]]=e,a=eh(i*r,t),c=eh(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<Dt,d=u<Dt;f&&(l=-l),d&&(u=-u);let h=Wt(Math.ceil(ws(t)/2))+un;if(l<Dt||l>=h||u<Dt||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function yl(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function gl(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return _t(t.lowS,"lowS"),_t(t.prehash,"prehash"),t.format!==void 0&&yl(t.format),t}var bl=class extends Error{constructor(e=""){super(e)}},Lt={Err:bl,_tlv:{encode:(r,e)=>{let{Err:t}=Lt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Yn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Yn(o.length/2|128):"";return Yn(r)+s+o+e},decode(r,e){let{Err:t}=Lt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Lt;if(r<Dt)throw new e("integer: negative integers are not allowed");let t=Yn(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Lt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Lt,o=Q("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Lt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Dt=BigInt(0),un=BigInt(1),th=BigInt(2),Os=BigInt(3),q0=BigInt(4);function ln(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let o=Q("private key",e);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function V0(r,e={}){let t=Es("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;jt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=nh(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(D,x,y){let{x:b,y:S}=x.toAffine(),A=n.toBytes(b);if(_t(y,"isCompressed"),y){u();let R=!n.isOdd(S);return Pe(rh(R),A)}else return Pe(Uint8Array.of(4),A,n.toBytes(S))}function d(D){qe(D,void 0,"Point");let{publicKey:x,publicKeyUncompressed:y}=l,b=D.length,S=D[0],A=D.subarray(1);if(b===x&&(S===2||S===3)){let R=n.fromBytes(A);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");let T=m(R),P;try{P=n.sqrt(T)}catch(oe){let J=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+J)}u();let B=n.isOdd(P);return(S&1)===1!==B&&(P=n.neg(P)),{x:R,y:P}}else if(b===y&&S===4){let R=n.BYTES,T=n.fromBytes(A.subarray(0,R)),P=n.fromBytes(A.subarray(R,R*2));if(!w(T,P))throw new Error("bad point: is not on curve");return{x:T,y:P}}else throw new Error(`bad point: got length ${b}, expected compressed=${x} or uncompressed=${y}`)}let h=e.toBytes||f,p=e.fromBytes||d;function m(D){let x=n.sqr(D),y=n.mul(x,D);return n.add(n.add(y,n.mul(D,s.a)),s.b)}function w(D,x){let y=n.sqr(x),b=m(D);return n.eql(y,b)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,Os),q0),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function E(D,x,y=!1){if(!n.isValid(x)||y&&n.is0(x))throw new Error(`bad point coordinate ${D}`);return x}function I(D){if(!(D instanceof v))throw new Error("ProjectivePoint expected")}function k(D){if(!c||!c.basises)throw new Error("no endo");return K0(D,c.basises,o.ORDER)}let q=Yr((D,x)=>{let{X:y,Y:b,Z:S}=D;if(n.eql(S,n.ONE))return{x:y,y:b};let A=D.is0();x==null&&(x=A?n.ONE:n.inv(S));let R=n.mul(y,x),T=n.mul(b,x),P=n.mul(S,x);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:R,y:T}}),V=Yr(D=>{if(D.is0()){if(e.allowInfinityPoint&&!n.is0(D.Y))return;throw new Error("bad point: ZERO")}let{x,y}=D.toAffine();if(!n.isValid(x)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!w(x,y))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(D,x,y,b,S){return y=new v(n.mul(y.X,D),y.Y,y.Z),x=eo(b,x),y=eo(S,y),x.add(y)}class v{constructor(x,y,b){this.X=E("x",x),this.Y=E("y",y,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:y,y:b}=x||{};if(!x||!n.isValid(y)||!n.isValid(b))throw new Error("invalid affine point");if(x instanceof v)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(b)?v.ZERO:new v(y,b,n.ONE)}static fromBytes(x){let y=v.fromAffine(p(qe(x,void 0,"point")));return y.assertValidity(),y}static fromHex(x){return v.fromBytes(Q("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,y=!0){return F.createCache(this,x),y||this.multiply(Os),this}assertValidity(){V(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){I(x);let{X:y,Y:b,Z:S}=this,{X:A,Y:R,Z:T}=x,P=n.eql(n.mul(y,T),n.mul(A,S)),B=n.eql(n.mul(b,T),n.mul(R,S));return P&&B}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:y}=s,b=n.mul(y,Os),{X:S,Y:A,Z:R}=this,T=n.ZERO,P=n.ZERO,B=n.ZERO,K=n.mul(S,S),oe=n.mul(A,A),J=n.mul(R,R),G=n.mul(S,A);return G=n.add(G,G),B=n.mul(S,R),B=n.add(B,B),T=n.mul(x,B),P=n.mul(b,J),P=n.add(T,P),T=n.sub(oe,P),P=n.add(oe,P),P=n.mul(T,P),T=n.mul(G,T),B=n.mul(b,B),J=n.mul(x,J),G=n.sub(K,J),G=n.mul(x,G),G=n.add(G,B),B=n.add(K,K),K=n.add(B,K),K=n.add(K,J),K=n.mul(K,G),P=n.add(P,K),J=n.mul(A,R),J=n.add(J,J),K=n.mul(J,G),T=n.sub(T,K),B=n.mul(J,oe),B=n.add(B,B),B=n.add(B,B),new v(T,P,B)}add(x){I(x);let{X:y,Y:b,Z:S}=this,{X:A,Y:R,Z:T}=x,P=n.ZERO,B=n.ZERO,K=n.ZERO,oe=s.a,J=n.mul(s.b,Os),G=n.mul(y,A),se=n.mul(b,R),de=n.mul(S,T),Ne=n.add(y,b),ie=n.add(A,R);Ne=n.mul(Ne,ie),ie=n.add(G,se),Ne=n.sub(Ne,ie),ie=n.add(y,S);let xe=n.add(A,T);return ie=n.mul(ie,xe),xe=n.add(G,de),ie=n.sub(ie,xe),xe=n.add(b,S),P=n.add(R,T),xe=n.mul(xe,P),P=n.add(se,de),xe=n.sub(xe,P),K=n.mul(oe,ie),P=n.mul(J,de),K=n.add(P,K),P=n.sub(se,K),K=n.add(se,K),B=n.mul(P,K),se=n.add(G,G),se=n.add(se,G),de=n.mul(oe,de),ie=n.mul(J,ie),se=n.add(se,de),de=n.sub(G,de),de=n.mul(oe,de),ie=n.add(ie,de),G=n.mul(se,ie),B=n.add(B,G),G=n.mul(xe,ie),P=n.mul(Ne,P),P=n.sub(P,G),G=n.mul(Ne,se),K=n.mul(xe,K),K=n.add(K,G),new v(P,B,K)}subtract(x){return this.add(x.negate())}is0(){return this.equals(v.ZERO)}multiply(x){let{endo:y}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let b,S,A=R=>F.cached(this,R,T=>It(v,T));if(y){let{k1neg:R,k1:T,k2neg:P,k2:B}=k(x),{p:K,f:oe}=A(T),{p:J,f:G}=A(B);S=oe.add(G),b=N(y.beta,K,J,R,P)}else{let{p:R,f:T}=A(x);b=R,S=T}return It(v,[b,S])[0]}multiplyUnsafe(x){let{endo:y}=e,b=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Dt||b.is0())return v.ZERO;if(x===un)return b;if(F.hasCache(this))return this.multiply(x);if(y){let{k1neg:S,k1:A,k2neg:R,k2:T}=k(x),{p1:P,p2:B}=Id(v,b,A,T);return N(y.beta,P,B,S,R)}else return F.unsafe(b,x)}multiplyAndAddUnsafe(x,y,b){let S=this.multiplyUnsafe(y).add(x.multiplyUnsafe(b));return S.is0()?void 0:S}toAffine(x){return q(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===un?!0:x?x(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===un?this:x?x(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return _t(x,"isCompressed"),this.assertValidity(),h(v,this,x)}toHex(x=!0){return Xe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return It(v,x)}static msm(x,y){return en(v,o,x,y)}static fromPrivateKey(x){return v.BASE.multiply(ln(o,x))}}v.BASE=new v(s.Gx,s.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO),v.Fp=n,v.Fn=o;let L=o.BITS,F=new Jr(v,e.endo?Math.ceil(L/2):L);return v.BASE.precompute(8),v}function rh(r){return Uint8Array.of(r?2:3)}function nh(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function z0(r,e={}){let{Fn:t}=r,n=e.randomBytes||zt,o=Object.assign(nh(r.Fp,t),{seed:Tc(t.ORDER)});function s(h){try{return!!ln(t,h)}catch{return!1}}function i(h,p){let{publicKey:m,publicKeyUncompressed:w}=o;try{let g=h.length;return p===!0&&g!==m||p===!1&&g!==w?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Pc(qe(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(ln(t,h)).toBytes(p)}function l(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:m,publicKeyUncompressed:w}=o;if(t.allowedLengths||p===m)return;let g=Q("key",h).length;return g===m||g===w}function f(h,p,m=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let w=ln(t,h);return r.fromHex(p).multiply(w).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>ln(t,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function $0(r,e,t={}){hs(e),jt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||zt,o=t.hmac||((y,...b)=>ml(e,y,Pe(...b))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=z0(r,t),p={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function w(y){let b=a>>un;return y>b}function g(y,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function _(y,b){yl(b);let S=h.signature,A=b==="compact"?S:b==="recovered"?S+1:void 0;return qe(y,A,`${b} signature`)}class E{constructor(b,S,A){this.r=g("r",b),this.s=g("s",S),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(b,S=m){_(b,S);let A;if(S==="der"){let{r:B,s:K}=Lt.toSig(qe(b));return new E(B,K)}S==="recovered"&&(A=b[0],S="compact",b=b.subarray(1));let R=i.BYTES,T=b.subarray(0,R),P=b.subarray(R,R*2);return new E(i.fromBytes(T),i.fromBytes(P),A)}static fromHex(b,S){return this.fromBytes(cr(b),S)}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){let S=s.ORDER,{r:A,s:R,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*th<S&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=T===2||T===3?A+a:A;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");let K=s.toBytes(B),oe=r.fromBytes(Pe(rh((T&1)===0),K)),J=i.inv(B),G=k(Q("msgHash",b)),se=i.create(-G*J),de=i.create(R*J),Ne=r.BASE.multiplyUnsafe(se).add(oe.multiplyUnsafe(de));if(Ne.is0())throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return w(this.s)}toBytes(b=m){if(yl(b),b==="der")return cr(Lt.hexFromSig(this));let S=i.toBytes(this.r),A=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Pe(Uint8Array.of(this.recovery),S,A)}return Pe(S,A)}toHex(b){return Xe(this.toBytes(b))}assertValidity(){}static fromCompact(b){return E.fromBytes(Q("sig",b),"compact")}static fromDER(b){return E.fromBytes(Q("sig",b),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Xe(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Xe(this.toBytes("compact"))}}let I=t.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let S=Zr(b),A=b.length*8-c;return A>0?S>>BigInt(A):S},k=t.bits2int_modN||function(b){return i.create(I(b))},q=Wt(c);function V(y){return Qn("num < 2^"+c,y,Dt,q),i.toBytes(y)}function N(y,b){return qe(y,void 0,"message"),b?qe(e(y),void 0,"prehashed message"):y}function v(y,b,S){if(["recovered","canonical"].some(se=>se in S))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:R,extraEntropy:T}=gl(S,p);y=N(y,R);let P=k(y),B=ln(i,b),K=[V(B),V(P)];if(T!=null&&T!==!1){let se=T===!0?n(h.secretKey):T;K.push(Q("extraEntropy",se))}let oe=Pe(...K),J=P;function G(se){let de=I(se);if(!i.isValidNot0(de))return;let Ne=i.inv(de),ie=r.BASE.multiply(de).toAffine(),xe=i.create(ie.x);if(xe===Dt)return;let Zo=i.create(Ne*i.create(J+xe*B));if(Zo===Dt)return;let cf=(ie.x===xe?0:2)|Number(ie.y&un),lf=Zo;return A&&w(Zo)&&(lf=i.neg(Zo),cf^=1),new E(xe,lf,cf)}return{seed:oe,k2sig:G}}function L(y,b,S={}){y=Q("message",y);let{seed:A,k2sig:R}=v(y,b,S);return fd(e.outputLen,i.BYTES,o)(A,R)}function F(y){let b,S=typeof y=="string"||Et(y),A=!S&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!S&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)b=new E(y.r,y.s);else if(S){try{b=E.fromBytes(Q("sig",y),"der")}catch(R){if(!(R instanceof Lt.Err))throw R}if(!b)try{b=E.fromBytes(Q("sig",y),"compact")}catch{return!1}}return b||!1}function D(y,b,S,A={}){let{lowS:R,prehash:T,format:P}=gl(A,p);if(S=Q("publicKey",S),b=N(Q("message",b),T),"strict"in A)throw new Error("options.strict was renamed to lowS");let B=P===void 0?F(y):E.fromBytes(Q("sig",y),P);if(B===!1)return!1;try{let K=r.fromBytes(S);if(R&&B.hasHighS())return!1;let{r:oe,s:J}=B,G=k(b),se=i.inv(J),de=i.create(G*se),Ne=i.create(oe*se),ie=r.BASE.multiplyUnsafe(de).add(K.multiplyUnsafe(Ne));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function x(y,b,S={}){let{prehash:A}=gl(S,p);return b=N(b,A),E.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:L,verify:D,recoverPublicKey:x,Signature:E,hash:e})}function H0(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Ve(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:t,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:s}}function G0(r){let{CURVE:e,curveOpts:t}=H0(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function W0(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,xs(t.Fn.ORDER,t.Fn.BITS))})}function oh(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:o}=G0(r),s=V0(e,t),i=$0(s,n,o);return W0(r,i)}function sh(r,e){let t=n=>oh({...r,hash:n});return{...t(e),create:t}}var xl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},j0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ih=BigInt(2);function X0(r){let e=xl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=te(u,t,e)*u%e,d=te(f,t,e)*u%e,h=te(d,ih,e)*l%e,p=te(h,o,e)*h%e,m=te(p,s,e)*p%e,w=te(m,a,e)*m%e,g=te(w,c,e)*w%e,_=te(g,a,e)*m%e,E=te(_,t,e)*u%e,I=te(E,i,e)*p%e,k=te(I,n,e)*l%e,q=te(k,ih,e);if(!wl.eql(wl.sqr(q),r))throw new Error("Cannot find square root");return q}var wl=Ve(xl.p,{sqrt:X0}),st=sh({...xl,Fp:wl,lowS:!0,endo:j0},ys);function ah(r,e,t){let n=Wr.digest(e instanceof Uint8Array?e:e.subarray());if(nn(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),st.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new ro(String(o))});try{return st.sign(n.digest,r).toDERRawBytes()}catch(o){throw new ro(String(o))}}function ch(r,e,t,n){let o=Wr.digest(t instanceof Uint8Array?t:t.subarray());if(nn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),st.verify(e,s,r))).catch(s=>{throw s.name==="AbortError"?s:new no(String(s))});try{return n?.signal?.throwIfAborted(),st.verify(e,o.digest,r)}catch(s){throw new no(String(s))}}var ho=class{type="secp256k1";raw;_key;constructor(e){this._key=fh(e),this.raw=lh(this._key)}toMultihash(){return et.digest(je(this))}toCID(){return ne.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){return ch(this._key,t,e,n)}},Rs=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=uh(e),this.publicKey=new ho(t??dh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){return ah(this.raw,e,t)}};function El(r){return new ho(r)}async function hh(){let r=Z0();return new Rs(r)}function lh(r){return st.ProjectivePoint.fromHex(r).toRawBytes(!0)}function uh(r){try{return st.getPublicKey(r,!0),r}catch(e){throw new Nn(String(e))}}function fh(r){try{return st.ProjectivePoint.fromHex(r),r}catch(e){throw new Kr(String(e))}}function dh(r){try{return st.getPublicKey(r,!0)}catch(e){throw new Nn(String(e))}}function Z0(){return st.utils.randomPrivateKey()}async function ph(r,e){if(r==="Ed25519")return Ud();if(r==="secp256k1")return hh();if(r==="RSA")return pl(Y0(e));if(r==="ECDSA")return Gf(Q0(e));throw new Ft}function fn(r,e){let{Type:t,Data:n}=dt.decode(r),o=n??new Uint8Array;switch(t){case ue.RSA:return fl(o,e);case ue.Ed25519:return Fc(o);case ue.secp256k1:return El(o);case ue.ECDSA:return pc(o);default:throw new Ft}}function mh(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case ue.Ed25519:return Fc(n);case ue.secp256k1:return El(n);case ue.ECDSA:return pc(n);default:throw new Ft}}function je(r){return dt.encode({Type:ue[r.type],Data:r.raw})}function Y0(r){return r==null?2048:parseInt(r,10)}function Q0(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new O("Unsupported curve, should be P-256, P-384 or P-521")}var gh=Symbol.for("nodejs.util.inspect.custom"),J0=114,po=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[is]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ne.createV1(J0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return X(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return X(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[gh](){return`PeerId(${this.toString()})`}},mo=class extends po{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},go=class extends po{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},yo=class extends po{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},ey=2336,bo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=et.digest(C(this.url))}[gh](){return`PeerId(${this.url})`}[is]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ne.createV1(ey,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=U(e)),e.toString()===this.toString())}};var ty=114,yh=2336;function ht(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=bt(Z.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return wo(ne.parse(r));if(e==null)throw new O('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=bt(e.decode(r))}return dn(t)}function vl(r){if(r.type==="Ed25519")return new go({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new yo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new mo({multihash:r.toCID().multihash,publicKey:r});throw new Ft}function bh(r){return vl(r.publicKey)}function dn(r){if(ny(r))return new mo({multihash:r});if(ry(r))try{let e=mh(r);if(e.type==="Ed25519")return new go({multihash:r,publicKey:e});if(e.type==="secp256k1")return new yo({multihash:r,publicKey:e})}catch{let t=U(r.digest);return new bo(new URL(t))}throw new Jo("Supplied PeerID Multihash is invalid")}function wo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ty&&r.code!==yh)throw new Qo("Supplied PeerID CID is invalid");if(r.code===yh){let e=U(r.multihash.digest);return new bo(new URL(e))}return dn(r.multihash)}function ry(r){return r.code===et.code}function ny(r){return r.code===Wr.code}var Sl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},wh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},xh=new globalThis.TextEncoder;function oy(r,e){let t=Sl[e],n=wh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function sy(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Sl[e],o=wh[e],s=r;for(;s.length>0;){let i=xh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function _l(r,{size:e=32,utf8Buffer:t}={}){if(!Sl[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return sy(r,e,t);r=xh.encode(r)}return oy(r,e)}var xo={hash:r=>Number(_l(r,{size:32})),hashV:(r,e)=>iy(xo.hash(r,e))};function iy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),C(e,"base16")}var Al=64,it=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Al)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?X(this.fp,e.fp):!1}};function yr(r,e){return Math.floor(Math.random()*(e-r))+r}var br=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof it))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof it))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof it))throw new TypeError("Invalid Fingerprint");let t=yr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof it))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var ay=500,Eo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??xo,this.seed=e.seed??yr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=C(e));let t=new it(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new br(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new br(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[yr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new br(this.bucketSize));for(let a=0;a<ay;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new br(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=C(e));let t=new it(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=C(e));let t=new it(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},cy={1:.5,2:.84,4:.95,8:.98};function ly(r=.001){return r>.002?2:r>1e-5?4:8}function Eh(r,e=.001){let t=ly(e),n=cy[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Al);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ks=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??xo,this.seed=e.seed??yr(0,Math.pow(2,10)),this.filterSeries=[new Eo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=C(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Eo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=C(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=C(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function vo(r,e=.001,t){return new ks({...Eh(r,e),...t??{}})}var Ns=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var vh=45,uy=15,hn=new Ns;function Ms(r){if(!(r.length>uy))return hn.new(r).parseWith(()=>hn.readIPv4Addr())}function Bs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>vh))return hn.new(r).parseWith(()=>hn.readIPv6Addr())}function pn(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>vh)return;let t=hn.new(r).parseWith(()=>hn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Sh(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function _h(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Cl(r){switch(r.length){case wr:return r.join(".");case xr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Ah(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Ch(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var wr=4,xr=16,o_=parseInt("0xFFFF",16),fy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function So(r,e){e.length===xr&&r.length===wr&&Sh(e,0,11)&&(e=e.slice(12)),e.length===wr&&r.length===xr&&_h(r,fy,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Ih(r,e){if(typeof e=="string"&&(e=pn(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Il(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=wr,o=Ms(e);if(o==null&&(n=xr,o=Bs(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Tl(s,8*n);return{network:So(o,i),mask:i}}function Tl(r,e){if(e!==8*wr&&e!==8*xr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var mn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Il(e));else{let n=pn(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=pn(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Tl(o,8*n.length);this.network=So(n,this.mask)}}contains(e){return Ih({network:this.network,mask:this.mask},e)}toString(){let e=Ah(this.mask),t=e!==-1?String(e):Ch(this.mask);return Cl(this.network)+"/"+t}};var we=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ot=class extends Error{static name="ValidationError";name="ValidationError"},_o=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Us=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function at(r){return!!Ms(r)}function Fs(r){return!!Bs(r)}function Ll(r){return e=>U(e,r)}function Dl(r){return e=>C(e,r)}function gn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Er(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Th(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=C(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Er(n);return tt([t,o],t.length+o.length)}function Ph(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=We.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Er(n);return tt([t,o],t.length+o.length)}function Ol(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=U(e,"base32"),o=gn(t);return`${n}:${o}`}var Rl=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new we("Invalid byte value in IP address");e[n]=o}),e},Lh=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=at(t[n]),i;s&&(i=Rl(t[n]),t[n]=U(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,U(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new we("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Dh=function(r){if(r.byteLength!==4)throw new we("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Oh=function(r){if(r.byteLength!==16)throw new we("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${t}"`)}};function Rh(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new we(`Invalid IPv6 address "${r}"`)}}var Pl=Object.values(Vn).map(r=>r.decoder),dy=(function(){let r=Pl[0].or(Pl[1]);return Pl.slice(2).forEach(e=>r=r.or(e)),r})();function kh(r){return dy.decode(r)}function Nh(r){return e=>r.encoder.encode(e)}function hy(r){if(parseInt(r).toString()!==r)throw new Ot("Value must be an integer")}function py(r){if(r<0)throw new Ot("Value must be a positive integer, or zero")}function my(r){return e=>{if(e>r)throw new Ot(`Value must be smaller than or equal to ${r}`)}}function gy(...r){return e=>{for(let t of r)t(e)}}var Ao=gy(hy,py,my(65535));var ge=-1,kl=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Us(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Fe=new kl,Dy=[{code:4,name:"ip4",size:32,valueToBytes:Rl,bytesToValue:Dh,validate:r=>{if(!at(r))throw new Ot(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Er,bytesToValue:gn,validate:Ao},{code:273,name:"udp",size:16,valueToBytes:Er,bytesToValue:gn,validate:Ao},{code:33,name:"dccp",size:16,valueToBytes:Er,bytesToValue:gn,validate:Ao},{code:41,name:"ip6",size:128,valueToBytes:Lh,bytesToValue:Oh,stringToValue:Rh,validate:r=>{if(!Fs(r))throw new Ot(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ge},{code:43,name:"ipcidr",size:8,bytesToValue:Ll("base10"),valueToBytes:Dl("base10")},{code:53,name:"dns",size:ge,resolvable:!0},{code:54,name:"dns4",size:ge,resolvable:!0},{code:55,name:"dns6",size:ge,resolvable:!0},{code:56,name:"dnsaddr",size:ge,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Er,bytesToValue:gn,validate:Ao},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ge,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ge,bytesToValue:Ll("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Dl("base58btc")(r):ne.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ol,valueToBytes:Th},{code:445,name:"onion3",size:296,bytesToValue:Ol,valueToBytes:Ph},{code:446,name:"garlic64",size:ge},{code:447,name:"garlic32",size:ge},{code:448,name:"tls"},{code:449,name:"sni",size:ge},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ge,bytesToValue:Nh(rc),valueToBytes:kh},{code:480,name:"http"},{code:481,name:"http-path",size:ge,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ge}];Dy.forEach(r=>{Fe.addProtocol(r)});function Mh(r){let e=[],t=0;for(;t<r.length;){let n=hr(r,t),o=Fe.getProtocol(n),s=me(n),i=Oy(o,r,t+s),a=0;i>0&&o.size===ge&&(a=me(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??U(f)}e.push(l),t+=c}return e}function Bh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Fe.getProtocol(n.code),s=me(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??C(n.value),a=i.byteLength,o.size===ge&&(c=me(a)));let l=new Uint8Array(s+c+a),u=0;on(n.code,l,u),u+=s,i!=null&&(o.size===ge&&(on(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return tt(t,e)}function Uh(r){if(r.charAt(0)!=="/")throw new we('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Fe.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new we(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new we(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new we("Incomplete multiaddr");return e}function Fh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Fe.getProtocol(e.code);if(t==null)throw new we(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Oy(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:hr(e,t)}var Ry=Symbol.for("nodejs.util.inspect.custom"),$l=Symbol.for("@multiformats/multiaddr"),ky=[53,54,55,56],zl=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function Ny(r){if(r==null&&(r="/"),er(r))return r.getComponents();if(r instanceof Uint8Array)return Mh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Uh(r);if(Array.isArray(r))return r;throw new we("Must be a string, Uint8Array, Component[], or another Multiaddr")}var zs=class r{[$l]=!0;#e;#n;#t;constructor(e="/",t={}){this.#e=Ny(e),t.validate!==!1&&My(this)}get bytes(){return this.#t==null&&(this.#t=Bh(this.#e)),this.#t}toString(){return this.#n==null&&(this.#n=Fh(this.#e)),this.#n}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(s=`%${l??""}`),ky.includes(a)&&(t="tcp",o=443,n=`${l??""}${s}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${s}`,e=a===41?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=Fe.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=Fe.getProtocol(e),o=[e];return t!=null&&o.push(n.valueToBytes?.(t)??C(t)),o})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new _o(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:o})=>{n===421&&e.push([n,o]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?U(Z.decode(`z${n}`),"base58btc"):U(ne.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(Fe.getProtocol(e.code).path)return e.value??null;return null}equals(e){return X(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Kh.get(t.name);if(n==null)throw new zl(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>$(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[Ry](){return`Multiaddr(${this.toString()})`}};function My(r){r.getComponents().forEach(e=>{let t=Fe.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Hl(r){let e,t;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(t=n.value),n.name==="ipcidr"&&(e=n.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new mn(t,e)}var Kh=new Map;function er(r){return!!r?.[$l]}function $(r){return new zs(r)}function $s(r){let e=Fe.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}function Hs(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function qh(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function Vh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Gl(r){if(!Hs(r))return!1;let{address:e}=r.nodeAddress();return Vh(e)}var By=[4,41,53,54,55,56];function Wl(r){try{for(let{code:e}of r.getComponents())if(e!==42)return By.includes(e)}catch{}return!1}var $h=Na(zh(),1),Uy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Fy=Uy.map(r=>new $h.Netmask(r));function jl(r){for(let e of Fy)if(e.contains(r))return!0;return!1}function Ky(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function qy(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return jl(o)}function Vy(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function zy(r){let e=r.split(":"),t=e[e.length-1];return jl(t)}function $y(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function tr(r){if(at(r))return jl(r);if(Ky(r))return qy(r);if(Vy(r))return zy(r);if(Fs(r))return $y(r)}function Cr(r){try{if(!Hs(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:tr(e)??!1}catch{}return!0}function ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Gs=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},En=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Gs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Gs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Xl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function vn(r={}){return Hy(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Hy(r,e){e=e??{};let t=e.onEnd,n=new En,o,s,i,a=ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,g)=>{s=_=>{s=null,n.push(_);try{w(r(n))}catch(E){g(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ye()})}},l=w=>s!=null?s(w):(n.push(w),o),u=w=>(n=new En,s!=null?s({error:w}):(n.push({error:w}),o)),f=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},d=w=>i?o:(i=!0,w!=null?u(w):l({done:!0})),h=()=>(n=new En,d(),{done:!0}),p=w=>(d(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,E;g!=null&&(_=new Promise((I,k)=>{E=()=>{k(new Xl)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,_])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var To=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Zl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Hh=r=>globalThis.DOMException===void 0?new Zl(r):new DOMException(r),Gh=r=>{let e=r.reason===void 0?Hh("This operation was aborted."):r.reason;return e instanceof Error?e:Hh(e)};function Po(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(Gh(h)),a=()=>{f(Gh(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new To;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Gy=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function Wy(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=Gy(r),f=(...h)=>{let p=t.multiArgs?h:h[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},d=h=>{n(),i(h)};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Po(o,{milliseconds:t.timeout});return s.cancel=n,s}return o}function lt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Wy(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Lo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ws=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},js=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Ir=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function jy(r){return r.reason}async function Rt(r,e,t){if(e==null)return r;let n=t?.translateError??jy;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Xs=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ye(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Zs=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Xy(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e={}){let t=new Xs(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Rt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Sn=class extends Ie{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Lo(this.emitEmpty.bind(this),1),this.emitIdle=Lo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new js;let n=new Zs(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await lt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await lt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lt(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=vn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function kt(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var _n=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Zy=1.2,Yy=2,Qy=5e3,Jy=6e4,eb=5e3,Ys=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??eb;this.success=new _n(t),this.failure=new _n(t),this.next=new _n(t),this.failureMultiplier=e.failureMultiplier??Yy,this.timeoutMultiplier=e.timeoutMultiplier??Zy,this.minTimeout=e.minTimeout??Qy,this.maxTimeout=e.maxTimeout??Jy,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=kt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Qs=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Wh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Qs(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Qs(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Yl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ye(),this.haveNext=ye()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ye(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ye(),await Wh(this.readNext.promise,t?.signal,t)}};function jh(){return new Yl}function tb(r){return r[Symbol.asyncIterator]!=null}async function rb(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*nb(r){let e=new AbortController,t=jh();rb(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*ob(r){for(let e of r)yield*e}function sb(...r){let e=[];for(let t of r)tb(t)||e.push(t);return e.length===r.length?ob(e):nb(r)}var An=sb;var ib=4194304,Js=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Jl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},eu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},tu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ab(r){return typeof r?.closeRead=="function"}function cb(r){return typeof r?.close=="function"}function Ql(r){return ab(r)?r.readStatus==="closing"||r.readStatus==="closed":cb(r)?r.status!=="open":!1}function lb(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function ru(r,e){let t=e?.maxBufferSize??ib,n=new Y,o=Promise.withResolvers(),s=!1;if(!lb(r))throw new O("Argument should be a Stream or a Multiaddr");let i=u=>{if(e?.stopPropagation,n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o.reject(u.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new Js("Stream was unwrapped");if(Ql(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw new Ir(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(;;){if(n.byteLength>=f){o.resolve();break}if(await Rt(o.promise,u?.signal),Ql(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(Ql(r))throw new Ir(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let h=n.sublist(0,d);return n.consume(d),h},async write(u,f){if(s===!0)throw new Js("Stream was unwrapped");r.send(u)||await lt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function ei(r,e={}){let t=ru(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=me(e.maxDataLength));let n=e?.lengthDecoder??hr,o=e?.lengthEncoder??Yt;return{async read(i){let a=-1,c=new Y;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Jl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new tu(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new eu(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw new Ir(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw new Ir(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Cn(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:Zh}=Object.prototype,{propertyIsEnumerable:ub}=Object,In=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},fb=void 0,Xh={concatArrays:!1,ignoreUndefined:!1},ti=r=>{let e=[];for(let t in r)Zh.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)ub.call(r,n)&&e.push(n)}return e};function Tn(r){return Array.isArray(r)?db(r):Cn(r)?hb(r):r}function db(r){let e=r.slice(0,0);return ti(r).forEach(t=>{In(e,t,Tn(r[t]))}),e}function hb(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return ti(r).forEach(t=>{In(e,t,Tn(r[t]))}),e}var Yh=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?In(r,o,nu(r[o],e[o],n)):In(r,o,Tn(e[o])))}),r),pb=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Zh.call(s,a)&&(i.push(String(a)),s===r?In(n,o++,s[a]):In(n,o++,Tn(s[a])));n=Yh(n,s,ti(s).filter(a=>!i.includes(a)),t)}),n};function nu(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?pb(r,e,t):!Cn(e)||!Cn(r)?Tn(e):Yh(r,e,ti(e),t)}function ri(...r){let e=nu(Tn(Xh),this!==fb&&this||{},Xh),t={_:{}};for(let n of r)if(n!==void 0){if(!Cn(n))throw new TypeError("`"+n+"` is not an Option Object");t=nu(t,{_:n},e)}return t._}var ni=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},oi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function si(r){return r[Symbol.asyncIterator]!=null}function Qh(r,e){if(r.byteLength>e)throw new Pn("Message length too long")}var ai=r=>{let e=me(r),t=Ee(e);return Yt(r,t),ai.bytes=e,t};ai.bytes=0;function ci(r,e){e=e??{};let t=e.lengthEncoder??ai,n=e?.maxDataLength??4194304;function*o(s){Qh(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return si(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}ci.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ai,n=e?.maxDataLength??4194304;return Qh(r,n),new Y(t(r.byteLength),r)};var Tr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Tr||(Tr={}));var su=r=>{let e=hr(r);return su.bytes=me(e),e};su.bytes=0;function ou(r,e){let t=new Y,n=Tr.LENGTH,o=-1,s=e?.lengthDecoder??su,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Tr.LENGTH)try{if(o=s(t),o<0)throw new ni("Invalid message length");if(o>a)throw new Pn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Tr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new oi("Message length length too long");break}throw l}if(n===Tr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Tr.LENGTH}}}return si(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Do("Unexpected end of input")})()}ou.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return ou(n,{...e??{},onLength:s=>{t=s}})};function gb(r,e){if(typeof r=="string")return yb(r);if(typeof r=="number")return xb(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var li=gb;function yb(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function bb(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function wb(r){let e=Math.abs(r);return e>=315576e5?Pr(r,e,315576e5,"year"):e>=26298e5?Pr(r,e,26298e5,"month"):e>=6048e5?Pr(r,e,6048e5,"week"):e>=864e5?Pr(r,e,864e5,"day"):e>=36e5?Pr(r,e,36e5,"hour"):e>=6e4?Pr(r,e,6e4,"minute"):e>=1e3?Pr(r,e,1e3,"second"):`${r} ms`}function xb(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?wb(r):bb(r)}function Pr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function iu(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=li,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,p;function m(...w){if(!m.enabled)return;let g=m,_=Number(new Date),E=_-(f||_);g.diff=E,g.prev=f,g.curr=_,f=_,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let I=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(q,V)=>{if(q==="%%")return"%";I++;let N=t.formatters[V];if(typeof N=="function"){let v=w[I];q=N.call(g,v),w.splice(I,1),I--}return q}),t.formatArgs.call(g,w),(g.log||t.log).apply(g,w)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(u)),p),set:w=>{d=w}}),typeof t.init=="function"&&t.init(m),m}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var ui=Ib(),Eb=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function vb(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Sb(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+li(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var _b=console.debug??console.log??(()=>{});function Ab(r){try{r?ui?.setItem("debug",r):ui?.removeItem("debug")}catch{}}function Cb(){let r;try{r=ui?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Ib(){try{return localStorage}catch{}}function Tb(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Jh=iu({formatArgs:Sb,save:Ab,load:Cb,useColors:vb,setupFormatters:Tb,colors:Eb,storage:ui,log:_b});var Ke=Jh;Ke.formatters.b=r=>r==null?"undefined":Z.baseEncode(r);Ke.formatters.t=r=>r==null?"undefined":We.baseEncode(r);Ke.formatters.m=r=>r==null?"undefined":tc.baseEncode(r);Ke.formatters.p=r=>r==null?"undefined":r.toString();Ke.formatters.c=r=>r==null?"undefined":r.toString();Ke.formatters.k=r=>r==null?"undefined":r.toString();Ke.formatters.a=r=>r==null?"undefined":r.toString();Ke.formatters.e=r=>r==null?"undefined":ep(r.stack)??ep(r.message)??r.toString();function Pb(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function fi(){return{forComponent(r){return tp(r)}}}function tp(r){let e=Pb(`${r}:trace`);return Ke.enabled(`${r}:trace`)&&Ke.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Ke(`${r}:trace`)),Object.assign(Ke(r),{error:Ke(`${r}:error`),trace:e,newScope:t=>tp(`${r}:${t}`)})}function ep(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var di=class extends Sn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var hi=class extends Sn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var pi=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new au}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Ws("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},au=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var cu=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function _e(r){let{name:e,metrics:t}=r,n;return t!=null?n=new cu({name:e,metrics:t}):n=new Map,n}var fe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var uu=Na(np(),1);function fu(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ro=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=fu(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var ko=class extends uu.default{#e;#n;#t=0;#h;#a;#p=0;#o;#c;#r;#m;#s=0;#l;#i;#g;#w=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ro,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#n=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#n||this.#t<this.#h}get#E(){return this.#s<this.#l}#v(){this.#s--,this.#u(),this.emit("next")}#S(){this.#b(),this.#y(),this.#c=void 0}get#_(){let e=Date.now();if(this.#o===void 0){let t=this.#p-e;if(t<0)this.#t=this.#e?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#S()},t)),!0}return!1}#u(){if(this.#r.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#x&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#n||this.#o!==void 0||(this.#o=setInterval(()=>{this.#b()},this.#a),this.#p=Date.now()+this.#a)}#b(){this.#t===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#t=this.#e?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#r.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#w++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#s++,this.#t++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=Po(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof To&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},t),this.emit("add"),this.#u()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function gi(r){let e=[He.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var du=60;function yi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:He[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:He[e.type],TTL:e.TTL??e.ttl??du,data:e.data instanceof Uint8Array?U(e.data):e.data}))}}var Ob=4;function hu(r,e={}){let t=new ko({concurrency:e.queryConcurrency??Ob});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),gi(o.types).forEach(a=>{s.append("type",He[a])}),o.onProgress?.(new fe("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=yi(await a.json());return o.onProgress?.(new fe("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function op(){return[hu("https://cloudflare-dns.com/dns-query"),hu("https://dns.google/resolve")]}var ap=Na(ip(),1);var pu=class{lru;constructor(e){this.lru=(0,ap.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return yi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:He[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??du)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function cp(r){return new pu(r)}var Rb=1e3,bi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=cp(e.cacheSize??Rb),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=op())}async query(e,t={}){let n=gi(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new fe("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new fe("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var He;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(He||(He={}));function lp(r={}){return new bi(r)}var mu=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[He.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push($(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=lp()),this.dns)}},Nt=new mu;var kb={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Nt}},transportManager:{faultTolerance:sr.FATAL_ALL}};async function up(r){let e=ri(kb,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new O("Private network is enforced, but no protector was provided");return e}function Lr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function wi(r){let e=bt(Z.decode(`z${r}`));return dn(e)}var Qe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Lr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Lr(this.map.values(),e=>e.key)}values(){return Lr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Dr=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Lr(this.set.entries(),e=>{let t=wi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=wi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Lr(this.set.values(),e=>wi(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var gu=class extends Qe{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function yu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new gu({name:e,metrics:t}):n=new Qe,n}var No;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(No||(No={}));var xi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Ln=class r{static createFromProtobuf=e=>{let t=No.decode(e),n=fn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=fp(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new xi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=No.encode({publicKey:je(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:X(this.marshal(),e.marshal())}async validate(e,t){let n=fp(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},fp=(r,e,t)=>{let n=C(r),o=Yt(n.byteLength),s=Yt(e.length),i=Yt(t.length);return new Y(o,n,s,e,i,t)};var dp="libp2p-peer-record",hp=Uint8Array.from([3,1]);var Mo;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Re((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Oe(s,n.codec()),n.decode=(s,i)=>De(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Re((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new gr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Oe(n,r.codec()),r.decode=(n,o)=>De(n,r.codec(),o)})(Mo||(Mo={}));function pp(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Or=class r{static createFromProtobuf=e=>{let t=Mo.decode(e),n=dn(bt(t.peerId)),o=(t.addresses??[]).map(i=>$(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=dp;static CODEC=hp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Mo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!pp(this.multiaddrs,e.multiaddrs))}};function Nb(r){return r[Symbol.asyncIterator]!=null}function Mb(r){if(Nb(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Bo=Mb;var Ge=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Ei(r,e,t,n){let o=new Ge(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){wu(t,"abort",f),wu(r,e,l),wu(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};bu(t,"abort",f),bu(r,e,l),bu(r,s,u)})}function bu(r,e,t){r!=null&&(mp(r)?r.addEventListener(e,t):r.addListener(e,t))}function wu(r,e,t){r!=null&&(mp(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function mp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var vi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Si=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function gp(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Si(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Si(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var _i=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Bb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ai=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Bb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ge),this.cleanup())}async join(e={}){let t=new _i(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await gp(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function xu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Uo=class extends Ie{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=xu(this.emitEmpty.bind(this),1),this.emitIdle=xu(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new vi;let n=new Ai(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ge)}),this.clear()}async onEmpty(e){this.size!==0&&await Ei(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ei(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ei(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=vn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ge("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ci="lock:worker:request-read",Ii="lock:worker:abort-read-request",Ti="lock:worker:release-read",Pi="lock:master:grant-read",Li="lock:master:error-read",Di="lock:worker:request-write",Oi="lock:worker:abort-write-request",Ri="lock:worker:release-write",ki="lock:master:grant-write",Ni="lock:master:error-write",Mi="lock:worker:finalize",Bi="mortice",yp={singleProcess:!1};var Eu=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Mi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var bp=(r=10)=>Math.random().toString().substring(2,r+2);var Ui=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Bi)}readLock(e){return this.sendRequest(Ci,Ii,Pi,Li,Ti,e)}writeLock(e){return this.sendRequest(Di,Oi,ki,Ni,Ri,e)}finalize(){this.channel.postMessage({type:Mi,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=bp();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var wp=r=>{if(r=Object.assign({},yp,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Bi),n=new Ie;return t.addEventListener("message",Eu(n,t,"requestReadLock","abortReadLockRequest",Ci,Ii,Li,Ti,Pi)),t.addEventListener("message",Eu(n,t,"requestWriteLock","abortWriteLockRequest",Di,Oi,Ni,Ri,ki)),n}return new Ui(r.name)};var Rr=new Map,Fo;function xp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Ub(r){if(Fo==null&&(Fo=wp(r),!xp(Fo))){let e=Fo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Rr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Rr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Rr.get(n);o?.finalize()})}return Fo}async function vu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ge)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Ep=(r,e)=>{let t=Rr.get(r);if(t!=null)return t;let n=Ub(e);if(xp(n))return t=n,Rr.set(r,t),t;let o=new Uo({concurrency:1}),s;return t={async readLock(i){if(s!=null)return vu(s,i);s=new Uo({concurrency:e.concurrency,autoStart:!1});let a=s,c=vu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,vu(o,i)},finalize:()=>{Rr.delete(r)},queue:o},Rr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Fb={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Su(r){let e=Object.assign({},Fb,r);return Ep(e.name,e)}var Mt;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Re((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ce(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Oe(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Re((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ki.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Ki.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Oe(i,o.codec()),o.decode=(i,a)=>De(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Re((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Fi.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new gr('Decode error - map field "addresses" had too many elements');a.addresses.push(Fi.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new gr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new lo('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new lo('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Oe(o,r.codec()),r.decode=(o,s)=>De(o,r.codec(),s)})(Mt||(Mt={}));var Fi;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Fi||(Fi={}));var Ki;(function(r){let e;r.codec=()=>(e==null&&(e=Re((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>De(t,r.codec(),n)})(Ki||(Ki={}));function Kb(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=fn(e.publicKey,t);return vl(n)}function vp(r,e,t){let n=Mt.decode(e);return Dn(r,n,t)}function Dn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:Kb(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:$(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Sp(r,e){return qb(r.addresses,e.addresses)&&Vb(r.protocols,e.protocols)&&zb(r.publicKey,e.publicKey)&&$b(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Hb(r.metadata,e.metadata)&&Gb(r.tags,e.tags)}function qb(r,e){return Ap(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!X(t.multiaddr,n.multiaddr)))}function Vb(r,e){return Ap(r,e,(t,n)=>t===n)}function zb(r,e){return _p(r,e)}function $b(r,e){return _p(r,e)}function Hb(r,e){return Cp(r,e,(t,n)=>X(t,n))}function Gb(r,e){return Cp(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function _p(r,e){return r==null&&e==null?!0:r!=null&&e!=null?X(r,e):!1}function Ap(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function Cp(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Bt="/",Ip=new TextEncoder().encode(Bt),qi=Ip[0],kr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=C(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==qi)throw new Error("Invalid key")}toString(e="utf8"){return U(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Bt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Ip),this._buf[0]!==qi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(qi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===qi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Bt).slice(1)}type(){return Wb(this.baseNamespace())}name(){return jb(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Bt)||(e+=Bt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Bt):new r(e.slice(0,-1).join(Bt))}child(e){return this.toString()===Bt?e:e.toString()===Bt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Xb(e.map(t=>t.namespaces()))])}};function Wb(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function jb(r){let e=r.split(":");return e[e.length-1]}function Xb(r){return[].concat(...r)}var _u="/peers/";function Ko(r){if(!Kt(r)||r.type==null)throw new O("Invalid PeerId");let e=r.toCID().toString();return new kr(`${_u}${e}`)}async function Tp(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=$(i.multiaddr)),!er(i.multiaddr))throw new O("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate($(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function zi(r,e,t,n){if(e==null)throw new O("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new O("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new O("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Vi(d,{validate:Pp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Vi(d,{validate:Lp,map:Dp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Vi([...a.entries()],{validate:Pp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Vi([...h.entries()],{validate:Lp,map:Dp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=je(o.id.publicKey):e.publicKey!=null?u=je(e.publicKey):r.publicKey!=null&&(u=je(r.publicKey));let f={addresses:await Tp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>X(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Vi(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Pp(r,e){if(typeof r!="string")throw new O("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new O("Metadata value must be a Uint8Array")}function Lp(r,e){if(typeof r!="string")throw new O("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new O("Tag value must be an integer");if(e.value<0||e.value>100)throw new O("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new O("Tag ttl must be an integer");if(e.ttl<0)throw new O("Tag ttl must be between greater than 0")}}function Dp(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function Op(r){let e=r.toString().split("/")[2],t=ne.parse(e,We);return wo(t)}function Au(r,e,t){let n=Op(r);return vp(n,e,t)}function Zb(r,e){return{prefix:_u,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Au(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Au(n.key,n.value,e),Au(o.key,o.value,e)))}}var $i=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=yu({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Su({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Ko(e),t)}async load(e,t){let n=Ko(e),o=await this.datastore.get(n,t),s=Mt.decode(o);if(this.#t(e,s))throw await this.datastore.delete(n,t),new or;return Dn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#n(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#n(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await zi(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#n(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Zb(e??{},this.maxAddressAge),e)){let o=Op(t);if(o.equals(this.peerId))continue;let s=Mt.decode(n);if(this.#t(o,s)){await this.datastore.delete(t,e);continue}yield Dn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Ko(e),o=await this.datastore.get(n,t),s=Mt.decode(o);if(this.#t(e,s))throw await this.datastore.delete(n,t),new or;return{peerPB:s,peer:Dn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#n(e,t,n,o){t.updated=Date.now();let s=Mt.encode(t);return await this.datastore.put(Ko(e),s,o),{peer:Dn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Sp(t,n.peerPB)}}#t(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Cu=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new $i(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Bo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Kt(t)?t:Kt(t?.expectedPeer)?t.expectedPeer:void 0,s=Kt(t)||t===void 0?n:t,i=await Ln.openAndCertify(e,Or.DOMAIN,s),a=wo(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Or.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=Ln.createFromProtobuf(l.peerRecordEnvelope),f=Or.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Rp(r,e={}){return new Cu(r,e)}var Hi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Yb(r){return r[Symbol.asyncIterator]!=null}function Qb(r){if(Yb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Iu=Qb;function Jb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var kp=Jb;function ew(r){return r[Symbol.asyncIterator]!=null}function tw(r,e){let t=0;if(ew(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=kp(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Nr=tw;function rw(r){return r[Symbol.asyncIterator]!=null}function nw(r,e){return rw(r)?(async function*(){yield*(await Bo(r)).sort(e)})():(function*(){yield*Bo(r).sort(e)})()}var Tu=nw;function ow(r){return r[Symbol.asyncIterator]!=null}function sw(r,e){return ow(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Pu=sw;var Gi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Iu(this.putMany(e,n)),e=[],await Iu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Nr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Nr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Tu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Nr(n,()=>o++>=s)}return e.limit!=null&&(n=Pu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Nr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Nr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Tu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Nr(n,()=>s++>=o)}return e.limit!=null&&(n=Pu(n,e.limit)),n}};var Wi=class extends Gi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Hi;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new kr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new kr(n),t?.signal?.throwIfAborted()}};var re=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),M=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ce=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),j=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function ee(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var iw=M(421),Np=ee(iw),Xi=M(54),Zi=M(55),Yi=M(56),Du=M(53),X4=ee(Xi,H(M(421))),Z4=ee(Zi,H(M(421))),Y4=ee(Yi,H(M(421))),Q4=ee(Ce(Du,Yi,Xi,Zi),H(M(421))),Mp=j(M(4),H(M(43))),Bp=j(H(M(42)),M(41),H(M(43))),Ou=Ce(Mp,Bp),Mr=Ce(Ou,Du,Xi,Zi,Yi),J4=ee(Ce(Ou,j(Ce(Du,Yi,Xi,Zi),H(M(421))))),Ru=ee(Mp),ku=ee(Bp),eP=ee(Ou),Nu=j(Mr,M(6)),qo=j(Mr,M(273)),Vo=ee(j(Nu,H(M(421)))),tP=ee(qo),Mu=j(qo,re(460),H(M(421))),Qi=j(qo,re(461),H(M(421))),aw=Ce(Mu,Qi),rP=ee(Mu),Up=ee(Qi),Lu=Ce(Mr,Nu,qo,Mu,Qi),Fp=Ce(j(Lu,re(477),H(M(421)))),Br=ee(Fp),Kp=Ce(j(Lu,re(478),H(M(421))),j(Lu,re(448),H(M(449)),re(477),H(M(421)))),zo=ee(Kp),qp=j(qo,re(280),H(M(466)),H(M(466)),H(M(421))),Bu=ee(qp),Vp=j(Qi,re(465),H(M(466)),H(M(466)),H(M(421))),Uu=ee(Vp),ji=Ce(Fp,Kp,j(Nu,H(M(421))),j(aw,H(M(421))),j(Mr,H(M(421))),qp,Vp,M(421)),nP=ee(ji),cw=j(ji,re(290),M(421)),Ur=ee(cw),lw=Ce(j(ji,re(290),re(281),H(M(421))),j(ji,re(281),H(M(421))),j(re(281),H(M(421)))),Fu=ee(lw),uw=Ce(j(Mr,M(6),re(480),H(M(421))),j(Mr,re(480),H(M(421)))),oP=ee(uw),fw=j(Mr,Ce(j(M(6,"443"),re(480)),j(M(6),re(443)),j(M(6),re(448),re(480)),j(re(448),re(480)),re(448),re(443)),H(M(421))),sP=ee(fw),dw=Ce(j(M(777),H(M(421)))),iP=ee(dw),hw=Ce(j(M(400),H(M(421)))),aP=ee(hw);var zp=864e13;var pw=448,Ku=449,mw=53,gw=54,yw=55,bw=56,Ji=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=_e({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=tr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?zp-Date.now():0,lastVerified:o?zp-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[o,s]of this.mappings.entries())s.domain===t&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr.stringTuples(),i=s[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(s,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:$(`/${s.map(u=>[$s(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===pw&&e[n+1]?.[0]!==Ku)return e.splice(n+1,0,[Ku,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",s,i.domain),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){let n=this.findHost(e),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",s,i.domain),o=o||i.verified,i.verified=!1,i.expires=Date.now()+t);return o}findHost(e){for(let t of e.stringTuples())if(t[0]===Ku||t[0]===mw||t[0]===gw||t[0]===yw||t[0]===bw)return t[1]}};var qu=4,Vu=41,zu=6,ww=273,ea=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=_e({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t[0][1])return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:at(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",o=t[1][0]===zu?"tcp":"udp",s=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===s&&u.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,s,o),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:n}of e){let o=n.stringTuples(),s;if((o[0][0]===qu||o[0][0]===Vu)&&o[1][0]===zu?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===qu||o[0][0]===Vu)&&o[1][0]===ww&&(s=`${o[0][1]}-${o[1][1]}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)o[0][0]=a.externalFamily===4?qu:Vu,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,t.push({multiaddr:$(`/${o.map(c=>[$s(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let o=e.stringTuples()[0][1],s=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=e.stringTuples(),o=n[0][1]??"",s=n[1][0]===zu?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===o&&u.externalPort===i&&u.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,o,i,s),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};var xw={maxObservedAddresses:10},ta=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_e({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??xw.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Cr(e)||qh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:$(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Ew={maxObservedAddresses:10},ra=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_e({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Ew.maxObservedAddresses}get(e,t){if(Cr(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Wl(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(Wl(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var $p=6e4,Hp={maxObservedAddresses:10,addressVerificationTTL:$p*10,addressVerificationRetry:$p*5},vw=r=>r;function $u(r,e){let t=r.getPeerId();return t!=null&&ht(t).equals(e)&&(r=r.decapsulate($(`/p2p/${e.toString()}`))),r}var na=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new ta(e,t),this.dnsMappings=new Ji(e,t),this.ipMappings=new ea(e,t),this.transportAddresses=new ra(e,t),this.announceFilter=t.announceFilter??vw,this.observedAddressFilter=vo(1024),this.addressVerificationTTL=t.addressVerificationTTL??Hp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Hp.addressVerificationRetry,this._updatePeerStoreAddresses=Lo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>$(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>$(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>$(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=$u(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=$u(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=$u(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=$(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove($(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${at(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove($(`/ip${at(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||tr(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Br.exactMatch(s)||zo.exactMatch(s),s=>Vo.exactMatch(s),s=>Up.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var Gp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Gp||(Gp={}));var oa=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},sa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},On=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},$o=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ia=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},aa=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},ca=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ho=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},la=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},ua=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},fa=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},da=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ha=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},rr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Fr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},pa=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},ma=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Hu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=fi())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>as(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Sw=["metrics","connectionProtector","dns"],_w=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Wp(r={}){let e=new Hu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!_w.includes(o)){let i=e.components[o];if(i==null&&!Sw.includes(o))throw new oa(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function jp(r){let e={};for(let t of Object.values(r.components))for(let n of Aw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Cw(t))if(e[n]!==!0)throw new sa(`Service "${Iw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Aw(r){return Array.isArray(r?.[Bn])?r[Bn]:[]}function Cw(r){return Array.isArray(r?.[Ka])?r[Ka]:[]}function Iw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Tw=4,Pw=41;function Xp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Br.matches(e))return!1;let t=e.stringTuples();return t[0][0]===Tw||t[0][0]===Pw?!!tr(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function ga(r){if(Kt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getPeerId();t=n==null?void 0:ht(n),e.forEach(o=>{if(!er(o))throw new Ut("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(t!=null)throw new O("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ht(s);if(t?.equals(i)!==!0)throw new O("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Np.exactMatch(n)),{peerId:t,multiaddrs:e}}var Lw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Zp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Lw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Go(r){try{let e;typeof r=="string"?e=$(r):e=r;let t=new Set([...e.getComponents().map(n=>n.name)]);if(!t.has("ipcidr")){let o=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(o)}return Hl(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}function Gu(r){return!Ur.exactMatch(r)}function ya(r,e,t){if(r==null||e==null)return;let n=e.sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Gu(s)))return n}var ba=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Go(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Qe;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Zp(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Yp="last-dial-failure",Qp="last-dial-success";var Jp=100,wa=50;function Dw(r,e){let t=Vo.exactMatch(r.multiaddr),n=Vo.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=zo.exactMatch(r.multiaddr),s=zo.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Br.exactMatch(r.multiaddr),a=Br.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Fu.exactMatch(r.multiaddr),l=Fu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Bu.exactMatch(r.multiaddr),f=Bu.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Uu.exactMatch(r.multiaddr),h=Uu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Ow(r,e){let t=Gl(r.multiaddr),n=Gl(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rw(r,e){let t=Cr(r.multiaddr),n=Cr(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function kw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Nw(r,e){let t=Ur.exactMatch(r.multiaddr),n=Ur.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function em(r){return r.sort(Dw).sort(kw).sort(Nw).sort(Rw).sort(Ow)}async function Wu(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new ma("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Wu(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Wo={maxParallelDials:wa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Nt}},xa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Wo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Wo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Wo.dialTimeout,this.connections=t.connections??new Qe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Wo.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new hi({concurrency:t.maxParallelDials??Wo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Je.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=ga(e);if(n!=null&&t.force!==!0){let i=ya(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new fe("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Vr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new fe("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new fe("dial-queue:start-dial"));let a=kt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Yu,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new fe("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Vr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Qp]:C(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Yp]:C(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}if(t.aborted)throw new rs(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:$(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Vr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ho("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Wu(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new fa("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?em(l):l.sort(this.addressSorter);if(u.length===0)throw new Ho("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Ur.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Mw=Object.prototype.toString,Bw=r=>Mw.call(r)==="[object Error]",Uw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Qu(r){return r&&Bw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Uw.has(r.message):!1}function Fw(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Ea(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Ju=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Kw=(r,e,t)=>{let n=t.retries-(e-1);return Object.freeze({error:r,attemptNumber:e,retriesLeft:n})};function qw(r,e){let t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*e.factor**(r-1));return n=Math.min(n,e.maxTimeout),n}async function Vw(r,e,t,n,o){let s=r;if(s instanceof Error||(s=new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`)),s instanceof Ju)throw s.originalError;if(s instanceof TypeError&&!Qu(s))throw s;let i=Kw(s,e,t);await t.onFailedAttempt(i);let a=Date.now();if(a-n>=o||e>=t.retries+1||!await t.shouldRetry(i))throw s;let c=qw(e,t),l=o-(a-n);if(l<=0)throw s;let u=Math.min(c,l);u>0&&await new Promise((f,d)=>{let h=()=>{clearTimeout(p),t.signal?.removeEventListener("abort",h),d(t.signal.reason)},p=setTimeout(()=>{t.signal?.removeEventListener("abort",h),f()},u);t.unref&&p.unref?.(),t.signal?.addEventListener("abort",h,{once:!0})}),t.signal?.throwIfAborted()}async function ef(r,e={}){if(e={...e},Fw(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,Ea("factor",e.factor,{min:0,allowInfinity:!1}),Ea("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Ea("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0});let t=e.maxRetryTime??Number.POSITIVE_INFINITY;Ea("maxRetryTime",t,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,o=Date.now(),s=t;for(;n<e.retries+1;){n++;try{e.signal?.throwIfAborted();let i=await r(n);return e.signal?.throwIfAborted(),i}catch(i){await Vw(i,n,e,o,s)}}throw new Error("Retry attempts exhausted without throwing an error.")}var va=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new di({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);tm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await ef(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Fa)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>tm(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function tm(r){for(let e of r.tags.keys())if(e.startsWith(Fa))return!0;return!1}var Yu=50,tf={maxConnections:Jp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Sa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??tf.maxConnections,this.maxConnections<1)throw new O("Connection Manager maxConnections must be greater than 0");this.connections=new Qe,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Go(n)),this.deny=(t.deny??[]).map(n=>Go(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??tf.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new pi({points:t.inboundConnectionThreshold??tf.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ba({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>$(n))}),this.dialQueue=new xa(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??wa,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Nt},connections:this.connections}),this.reconnectQueue=new va({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await df(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await hf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([lt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new O("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new gt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=ga(e);if(this.peerId.equals(n))throw new qr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=ya(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Yu});if(s.status!=="open")throw new nr("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Ut("Duplicate multiaddr connection")),c;return a||i.push(s),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([lt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>$(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Hw=1e4,Gw="1.0.0",Ww="ping",jw="ipfs",rm=32,Xw=!0,_a=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??jw}/${Ww}/${Gw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Hw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Xw,this.timeout=new Ys({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Bn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ru(o);t=Date.now(),await Promise.all([s.write(an(rm),{signal:n}),s.read({bytes:rm,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Aa=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new On("No content routers available");let n=this,o=new Dr;for await(let s of An(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new On("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new On("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new gt;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new gt;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Ca=globalThis.CustomEvent??Event;async function*rf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ye(),a=ye(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ye(),await i.promise),u)break;let m={done:!1};s.push(m),p().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new Ca("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new Ca("task-complete"))})}c=!0,o.dispatchEvent(new Ca("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ca("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(f()||(a=ye(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var Ia=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:U(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new $o("No peer routers available");if(e.toString()===this.peerId.toString())throw new ia("Should not try to find self");let n=this,o=An(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new or}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new $o("No peer routers available");let n=this,o=vo(1024);for await(let s of rf((async function*(){let i=An(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Ta=class extends Ie{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=kt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ye(),yield(await lt(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=kt([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=an(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Rt(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var nf=32,of=64,Pa=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=_e({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new aa(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new ca(`Handler already registered for protocol ${e}`);let o=ri.bind({ignoreUndefined:!0})({maxInboundStreams:nf,maxOutboundStreams:of},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new O("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var La=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=_e({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=_e({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??sr.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new O("Transport must have a valid tag");if(this.transports.has(t))throw new O(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new pa(`No transport available for address ${String(e)}`);return t?.onProgress?.(new fe("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new gt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new la)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Ru.matches(c)?t.ipv4.attempts++:ku.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Ru.matches(c)&&t.ipv4.success++,ku.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===sr.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new ua(`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:
|
|
2
|
+
"use strict";var Libp2P=(()=>{var jp=Object.create;var zo=Object.defineProperty;var Xp=Object.getOwnPropertyDescriptor;var Yp=Object.getOwnPropertyNames;var Zp=Object.getPrototypeOf,Qp=Object.prototype.hasOwnProperty;var Aa=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Fe=(r,e)=>{for(var t in e)zo(r,t,{get:e[t],enumerable:!0})},Yu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yp(e))!Qp.call(r,o)&&o!==t&&zo(r,o,{get:()=>e[o],enumerable:!(n=Xp(e,o))||n.enumerable});return r};var Ca=(r,e,t)=>(t=r!=null?jp(Zp(r)):{},Yu(e||!r||!r.__esModule?zo(t,"default",{value:r,enumerable:!0}):t,r)),Jp=r=>Yu(zo({},"__esModule",{value:!0}),r);var Eh=Aa(wo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,f,u,d;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,d=c&255,[l,f,u,d].join(".")},i=function(c){var l,f,u,d,h,p;for(l=[],u=d=0;d<=3&&c.length!==0;u=++d){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,f,u,d,h;for(d=0,l=10,f="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,f="7")),h=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)d=d*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")d=d*l+(10+t(c[u])-s)>>>0;else if("A"<=c[u]&&c[u]<="F")d=d*l+(10+t(c[u])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");u++}if(u===h)throw new Error("empty octet");return[d,u]},r=(function(){function c(l,f){var u,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(p=l.split("/",2),l=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw u=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw u=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,u,d;for(d=i(this.first),u=i(this.last),f=0;d<=u;)l(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),wo.ip2long=i,wo.long2ip=a,wo.Netmask=r}).call(wo)});var Rp=Aa((v4,Iu)=>{"use strict";var ew=Object.prototype.hasOwnProperty,Me="~";function Bo(){}Object.create&&(Bo.prototype=Object.create(null),new Bo().__proto__||(Me=!1));function tw(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Dp(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new tw(t,n||r,o),i=Me?Me+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function aa(r,e){--r._eventsCount===0?r._events=new Bo:delete r._events[e]}function Te(){this._events=new Bo,this._eventsCount=0}Te.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ew.call(t,n)&&e.push(Me?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Te.prototype.listeners=function(e){var t=Me?Me+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Te.prototype.listenerCount=function(e){var t=Me?Me+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Te.prototype.emit=function(e,t,n,o,s,i){var a=Me?Me+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(u=1,f=new Array(l-1);u<l;u++)f[u-1]=arguments[u];c.fn.apply(c.context,f)}else{var d=c.length,h;for(u=0;u<d;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(l-1);h<l;h++)f[h-1]=arguments[h];c[u].fn.apply(c[u].context,f)}}return!0};Te.prototype.on=function(e,t,n){return Dp(this,e,t,n,!1)};Te.prototype.once=function(e,t,n){return Dp(this,e,t,n,!0)};Te.prototype.removeListener=function(e,t,n,o){var s=Me?Me+e:e;if(!this._events[s])return this;if(!t)return aa(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&aa(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:aa(this,s)}return this};Te.prototype.removeAllListeners=function(e){var t;return e?(t=Me?Me+e:e,this._events[t]&&aa(this,t)):(this._events=new Bo,this._eventsCount=0),this};Te.prototype.off=Te.prototype.removeListener;Te.prototype.addListener=Te.prototype.on;Te.prefixed=Me;Te.EventEmitter=Te;typeof Iu<"u"&&(Iu.exports=Te)});var Np=Aa((z4,Op)=>{Op.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Iw={};Fe(Iw,{createLibp2p:()=>_w,dnsaddrResolver:()=>kr,isLibp2p:()=>Cw});var Zu=Symbol.for("@libp2p/connection");var Ia=Symbol.for("@libp2p/content-routing");var Qe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var I=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Or=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Tn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var er=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var tr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Nr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Mt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ho=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Go=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Wo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},jo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Xo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ht=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Mr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Pn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Yo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Zo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Bt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Qo=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Ta=Symbol.for("@libp2p/peer-discovery");var Jo=Symbol.for("@libp2p/peer-id");function Ft(r){return!!r?.[Jo]}var Pa=Symbol.for("@libp2p/peer-routing");var La="keep-alive";function es(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Qu(...r){let e=[];for(let t of r)es(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Ju(...r){let e=[];for(let t of r)es(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Fw=Symbol.for("@libp2p/transport");var Ln;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ln||(Ln={}));var Pe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Dn=Symbol.for("@libp2p/service-capabilities"),Da=Symbol.for("@libp2p/service-dependencies");var Ma={};Fe(Ma,{base58btc:()=>ee,base58flickr:()=>im});var dx=new Uint8Array(0);function ef(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function tf(r){return new TextEncoder().encode(r)}function rf(r){return new TextDecoder().decode(r)}function em(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,w=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,m++;for(var E=(_-g)*f+1>>>0,C=new Uint8Array(E);g!==_;){for(var O=p[g],V=0,$=E-1;(O!==0||V<w)&&$!==-1;$--,V++)O+=256*C[$]>>>0,C[$]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");w=V,g++}for(var N=E-w;N!==E&&C[N]===0;)N++;for(var v=c.repeat(m);N<E;++N)v+=r.charAt(C[N]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var w=0,g=0;p[m]===c;)w++,m++;for(var _=(p.length-m)*l+1>>>0,E=new Uint8Array(_);p[m];){var C=t[p.charCodeAt(m)];if(C===255)return;for(var O=0,V=_-1;(C!==0||O<g)&&V!==-1;V--,O++)C+=a*E[V]>>>0,E[V]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=O,m++}if(p[m]!==" "){for(var $=_-g;$!==_&&E[$]===0;)$++;for(var N=new Uint8Array(w+(_-$)),v=w;$!==_;)N[v++]=E[$++];return N}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:h}}var tm=em,rm=tm,of=rm;var Ra=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ka=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return sf(this,e)}},Oa=class{decoders;constructor(e){this.decoders=e}or(e){return sf(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function sf(r,e){return new Oa({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Na=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ra(e,t,n),this.decoder=new ka(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Br({name:r,prefix:e,encode:t,decode:n}){return new Na(r,e,t,n)}function Ut({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=of(t,r);return Br({prefix:e,name:r,encode:n,decode:s=>pt(o(s))})}function nm(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function om(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function sm(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=sm(n);return Br({prefix:e,name:r,encode(s){return om(s,n,t)},decode(s){return nm(s,o,t,r)}})}var ee=Ut({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),im=Ut({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ba={};Fe(Ba,{base32:()=>We,base32hex:()=>um,base32hexpad:()=>dm,base32hexpadupper:()=>hm,base32hexupper:()=>fm,base32pad:()=>cm,base32padupper:()=>lm,base32upper:()=>am,base32z:()=>pm});var We=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),am=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cm=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lm=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),um=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fm=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dm=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hm=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pm=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Fa={};Fe(Fa,{base36:()=>Rn,base36upper:()=>mm});var Rn=Ut({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mm=Ut({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gm=lf,af=128,ym=127,bm=~ym,wm=Math.pow(2,31);function lf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=wm;)e[t++]=r&255|af,r/=128;for(;r&bm;)e[t++]=r&255|af,r>>>=7;return e[t]=r|0,lf.bytes=t-n+1,e}var xm=Ua,Em=128,cf=127;function Ua(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ua.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&cf)<<o:(i&cf)*Math.pow(2,o),o+=7}while(i>=Em);return Ua.bytes=s-n,t}var vm=Math.pow(2,7),Sm=Math.pow(2,14),_m=Math.pow(2,21),Am=Math.pow(2,28),Cm=Math.pow(2,35),Im=Math.pow(2,42),Tm=Math.pow(2,49),Pm=Math.pow(2,56),Lm=Math.pow(2,63),Dm=function(r){return r<vm?1:r<Sm?2:r<_m?3:r<Am?4:r<Cm?5:r<Im?6:r<Tm?7:r<Pm?8:r<Lm?9:10},Rm={encode:gm,decode:xm,encodingLength:Dm},km=Rm,kn=km;function On(r,e=0){return[kn.decode(r,e),kn.decode.bytes]}function Fr(r,e,t=0){return kn.encode(r,e,t),e}function Ur(r){return kn.encodingLength(r)}function ct(r,e){let t=e.byteLength,n=Ur(r),o=n+Ur(t),s=new Uint8Array(o+t);return Fr(r,s,0),Fr(t,s,n),s.set(e,o),new Kr(r,t,e,s)}function mt(r){let e=pt(r),[t,n]=On(e),[o,s]=On(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Kr(t,o,i,e)}function uf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ef(r.bytes,t.bytes)}}var Kr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function ff(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Nm(t,Ka(r),e??ee.encoder);default:return Mm(t,Ka(r),e??We.encoder)}}var df=new WeakMap;function Ka(r){let e=df.get(r);if(e==null){let t=new Map;return df.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Nn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Bm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ct(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&uf(e.multihash,n.multihash)}toString(e){return ff(this,e)}toJSON(){return{"/":ff(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??hf(n,o,s.bytes))}else if(t[Fm]===!0){let{version:n,multihash:o,code:s}=t,i=mt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Nn)throw new Error(`Version 0 CID must use dag-pb (code: ${Nn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=hf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Nn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=pt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Kr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,d]=On(e.subarray(t));return t+=d,u},o=n(),s=Nn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Om(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ka(s).set(n,e),s}};function Om(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Rn.prefix:{let t=e??Rn;return[Rn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Nm(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Mm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Nn=112,Bm=18;function hf(r,e,t){let n=Ur(r),o=n+Ur(e),s=new Uint8Array(o+t.byteLength);return Fr(r,s,0),Fr(e,s,n),s.set(t,o),s}var Fm=Symbol.for("@ipld/js-cid/CID");var qa={};Fe(qa,{identity:()=>Je});var pf=0,Um="identity",mf=pt;function Km(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ct(pf,mf(r))}var Je={code:pf,name:Um,encode:mf,digest:Km};function Y(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ce(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function et(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var yf=Symbol.for("@achingbrain/uint8arraylist");function gf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function rs(r){return!!r?.[yf]}var Z=class r{bufs;length;[yf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(rs(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(rs(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=gf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=gf(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(rs(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return et(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:et(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!rs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let d=l;d>=0;d--){let h=this.get(u+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Y(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Va={};Fe(Va,{base10:()=>qm});var qm=Ut({prefix:"9",name:"base10",alphabet:"0123456789"});var $a={};Fe($a,{base16:()=>Vm,base16upper:()=>$m});var Vm=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$m=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var za={};Fe(za,{base2:()=>zm});var zm=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ha={};Fe(Ha,{base256emoji:()=>Xm});var bf=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Hm=bf.reduce((r,e,t)=>(r[t]=e,r),[]),Gm=bf.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wm(r){return r.reduce((e,t)=>(e+=Hm[t],e),"")}function jm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Gm[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Xm=Br({prefix:"\u{1F680}",name:"base256emoji",encode:Wm,decode:jm});var ja={};Fe(ja,{base64:()=>Ga,base64pad:()=>Ym,base64url:()=>Wa,base64urlpad:()=>Zm});var Ga=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ym=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wa=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zm=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xa={};Fe(Xa,{base8:()=>Qm});var Qm=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ya={};Fe(Ya,{identity:()=>Jm});var Jm=Br({prefix:"\0",name:"identity",encode:r=>rf(r),decode:r=>tf(r)});var Xx=new TextEncoder,Yx=new TextDecoder;var Ja={};Fe(Ja,{sha256:()=>qr,sha512:()=>ng});var rg=20;function Qa({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Za(r,e,t,n,o)}var Za=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??rg,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?wf(n,this.code,t?.truncate):n.then(o=>wf(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function wf(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ct(e,r)}function Ef(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var qr=Qa({name:"sha2-256",code:18,encode:Ef("SHA-256")}),ng=Qa({name:"sha2-512",code:19,encode:Ef("SHA-512")});var Mn={...Ya,...za,...Xa,...Va,...$a,...Ba,...Fa,...Ma,...ja,...Ha},cE={...Ja,...qa};function Sf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vf=Sf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ec=Sf("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),og={utf8:vf,"utf-8":vf,hex:Mn.base16,latin1:ec,ascii:ec,binary:ec,...Mn},ns=og;function T(r,e="utf8"){let t=ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function K(r,e="utf8"){let t=ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var sg=parseInt("11111",2),tc=parseInt("10000000",2),ig=parseInt("01111111",2),_f={0:Bn,1:Bn,2:ag,3:ug,4:fg,5:lg,6:cg,16:Bn,22:Bn,48:Bn};function gt(r,e={offset:0}){let t=r[e.offset]&sg;if(e.offset++,_f[t]!=null)return _f[t](r,e);throw new Error("No decoder for tag "+t)}function Fn(r,e){let t=0;if((r[e.offset]&tc)===tc){let n=r[e.offset]&ig,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Bn(r,e){Fn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=gt(r,e);if(n===null)break;t.push(n)}return t}function ag(r,e){let t=Fn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function cg(r,e){let t=Fn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let f=0;for(let u=0;u<c.length;u++)f+=c[u]<<u*7;a+=`.${f}`,c=[]}}return a}function lg(r,e){return e.offset++,null}function ug(r,e){let t=Fn(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function fg(r,e){let t=Fn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function dg(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Z;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function os(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=dg(r.byteLength);return new Z(Uint8Array.from([e.byteLength|tc]),e)}function Le(r){let e=new Z,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Z(Uint8Array.from([2]),os(e),e)}function Un(r){let e=Uint8Array.from([0]),t=new Z(e,r);return new Z(Uint8Array.from([3]),os(t),t)}function Af(r){return new Z(Uint8Array.from([4]),os(r),r)}function tt(r,e=48){let t=new Z;for(let n of r)t.append(n);return new Z(Uint8Array.from([e]),os(t),t)}async function Cf(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function If(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Tf(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var hg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),pg=Uint8Array.from([6,5,43,129,4,0,34]),mg=Uint8Array.from([6,5,43,129,4,0,35]),gg={ext:!0,kty:"EC",crv:"P-256"},yg={ext:!0,kty:"EC",crv:"P-384"},bg={ext:!0,kty:"EC",crv:"P-521"},rc=32,nc=48,oc=66;function sc(r){let e=gt(r);return Pf(e)}function Pf(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===rc*2+1)return n=K(e.subarray(t,t+rc),"base64url"),o=K(e.subarray(t+rc),"base64url"),new rr({...gg,key_ops:["verify"],x:n,y:o});if(e.byteLength===nc*2+1)return n=K(e.subarray(t,t+nc),"base64url"),o=K(e.subarray(t+nc),"base64url"),new rr({...yg,key_ops:["verify"],x:n,y:o});if(e.byteLength===oc*2+1)return n=K(e.subarray(t,t+oc),"base64url"),o=K(e.subarray(t+oc),"base64url"),new rr({...bg,key_ops:["verify"],x:n,y:o});throw new I(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Lf(r){return tt([Le(Uint8Array.from([1])),Af(T(r.d??"","base64url")),tt([Rf(r.crv)],160),tt([Un(new Z(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function Df(r){return tt([Le(Uint8Array.from([1])),tt([Rf(r.crv)],160),tt([Un(new Z(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function Rf(r){if(r==="P-256")return hg;if(r==="P-384")return pg;if(r==="P-521")return mg;throw new I(`Invalid curve ${r}`)}async function kf(r="P-256"){let e=await Cf(r);return new ss(e.privateKey)}var rr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Df(this.jwk)),this._raw}toMultihash(){return Je.digest(je(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}async verify(e,t,n){return Tf(this.jwk,t,e,n)}},ss=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new rr({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Lf(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}async sign(e,t){return If(this.jwk,e,t)}};var nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function bt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Kn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ue(r,...e){if(!bt(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function is(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Kn(r.outputLen),Kn(r.blockLen)}function $r(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Nf(r,e){Ue(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function wt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function as(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function rt(r,e){return r<<32-e|r>>>e}var Mf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Xe(r){if(Ue(r),Mf)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=wg[r[t]];return e}var yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Of(r){if(r>=yt._0&&r<=yt._9)return r-yt._0;if(r>=yt.A&&r<=yt.F)return r-(yt.A-10);if(r>=yt.a&&r<=yt.f)return r-(yt.a-10)}function or(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Mf)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Of(r.charCodeAt(s)),a=Of(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ic(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function qn(r){return typeof r=="string"&&(r=ic(r)),Ue(r),r}function De(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ue(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Vr=class{};function ac(r){let e=n=>r().update(qn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function qt(r=32){if(nr&&typeof nr.getRandomValues=="function")return nr.getRandomValues(new Uint8Array(r));if(nr&&typeof nr.randomBytes=="function")return Uint8Array.from(nr.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function xg(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function Bf(r,e,t){return r&e^~r&t}function Ff(r,e,t){return r&e^r&t^e&t}var Vn=class extends Vr{constructor(e,t,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=as(this.buffer)}update(e){$r(this),e=qn(e),Ue(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=as(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$r(this),Nf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,wt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)t[u]=0;xg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=as(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var cs=BigInt(4294967295),Uf=BigInt(32);function Eg(r,e=!1){return e?{h:Number(r&cs),l:Number(r>>Uf&cs)}:{h:Number(r>>Uf&cs)|0,l:Number(r&cs)|0}}function Kf(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Eg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var cc=(r,e,t)=>r>>>t,lc=(r,e,t)=>r<<32-t|e>>>t,sr=(r,e,t)=>r>>>t|e<<32-t,ir=(r,e,t)=>r<<32-t|e>>>t,$n=(r,e,t)=>r<<64-t|e>>>t-32,zn=(r,e,t)=>r>>>t-32|e<<64-t;function lt(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var qf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Vf=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,$f=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),zf=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Hf=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Gf=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Sg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Vt=new Uint32Array(64),ls=class extends Vn{constructor(e=32){super(64,e,8,!1),this.A=xt[0]|0,this.B=xt[1]|0,this.C=xt[2]|0,this.D=xt[3]|0,this.E=xt[4]|0,this.F=xt[5]|0,this.G=xt[6]|0,this.H=xt[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Vt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Vt[u-15],h=Vt[u-2],p=rt(d,7)^rt(d,18)^d>>>3,m=rt(h,17)^rt(h,19)^h>>>10;Vt[u]=m+Vt[u-7]+p+Vt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let d=rt(a,6)^rt(a,11)^rt(a,25),h=f+d+Bf(a,c,l)+Sg[u]+Vt[u]|0,m=(rt(n,2)^rt(n,13)^rt(n,22))+Ff(n,o,s)|0;f=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,l,f)}roundClean(){wt(Vt)}destroy(){this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}};var Wf=Kf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),_g=Wf[0],Ag=Wf[1],$t=new Uint32Array(80),zt=new Uint32Array(80),uc=class extends Vn{constructor(e=64){super(128,e,16,!1),this.Ah=we[0]|0,this.Al=we[1]|0,this.Bh=we[2]|0,this.Bl=we[3]|0,this.Ch=we[4]|0,this.Cl=we[5]|0,this.Dh=we[6]|0,this.Dl=we[7]|0,this.Eh=we[8]|0,this.El=we[9]|0,this.Fh=we[10]|0,this.Fl=we[11]|0,this.Gh=we[12]|0,this.Gl=we[13]|0,this.Hh=we[14]|0,this.Hl=we[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:d,Gh:h,Gl:p,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,l,f,u,d,h,p,m,w]}set(e,t,n,o,s,i,a,c,l,f,u,d,h,p,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let E=0;E<16;E++,t+=4)$t[E]=e.getUint32(t),zt[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let C=$t[E-15]|0,O=zt[E-15]|0,V=sr(C,O,1)^sr(C,O,8)^cc(C,O,7),$=ir(C,O,1)^ir(C,O,8)^lc(C,O,7),N=$t[E-2]|0,v=zt[E-2]|0,D=sr(N,v,19)^$n(N,v,61)^cc(N,v,6),F=ir(N,v,19)^zn(N,v,61)^lc(N,v,6),R=$f($,F,zt[E-7],zt[E-16]),x=zf(R,V,D,$t[E-7],$t[E-16]);$t[E]=x|0,zt[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:p,Gh:m,Gl:w,Hh:g,Hl:_}=this;for(let E=0;E<80;E++){let C=sr(u,d,14)^sr(u,d,18)^$n(u,d,41),O=ir(u,d,14)^ir(u,d,18)^zn(u,d,41),V=u&h^~u&m,$=d&p^~d&w,N=Hf(_,O,$,Ag[E],zt[E]),v=Gf(N,g,C,V,_g[E],$t[E]),D=N|0,F=sr(n,o,28)^$n(n,o,34)^$n(n,o,39),R=ir(n,o,28)^zn(n,o,34)^zn(n,o,39),x=n&s^n&a^s&a,y=o&i^o&c^i&c;g=m|0,_=w|0,m=h|0,w=p|0,h=u|0,p=d|0,{h:u,l:d}=lt(l|0,f|0,v|0,D|0),l=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=qf(D,R,y);n=Vf(b,v,F,x),o=b|0}({h:n,l:o}=lt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=lt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=lt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=lt(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=lt(this.Eh|0,this.El|0,u|0,d|0),{h,l:p}=lt(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:w}=lt(this.Gh|0,this.Gl|0,m|0,w|0),{h:g,l:_}=lt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,l,f,u,d,h,p,m,w,g,_)}roundClean(){wt($t,zt)}destroy(){wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var us=ac(()=>new ls);var jf=ac(()=>new uc);var hc=BigInt(0),dc=BigInt(1);function Et(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Ve(r,e,t=""){let n=bt(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Hn(r){let e=r.toString(16);return e.length&1?"0"+e:e}function Xf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?hc:BigInt("0x"+r)}function zr(r){return Xf(Xe(r))}function vt(r){return Ue(r),Xf(Xe(Uint8Array.from(r).reverse()))}function fs(r,e){return or(r.toString(16).padStart(e*2,"0"))}function pc(r,e){return fs(r,e).reverse()}function Q(r,e,t){let n;if(typeof e=="string")try{n=or(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(bt(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function Yf(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function mc(r){return Uint8Array.from(r)}var fc=r=>typeof r=="bigint"&&hc<=r;function Zf(r,e,t){return fc(r)&&fc(e)&&fc(t)&&e<=r&&r<t}function Gn(r,e,t,n){if(!Zf(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function ds(r){let e;for(e=0;r>hc;r>>=dc,e+=1);return e}var Ht=r=>(dc<<BigInt(r))-dc;function Qf(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>t(i,s,...h),f=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<e;){s=l();let m=s.slice();p.push(m),h+=s.length}return De(...p)};return(h,p)=>{c(),f(h);let m;for(;!(m=p(u()));)f();return c(),m}}function Gt(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(t).forEach(([o,s])=>n(o,s,!0))}var gc=()=>{throw new Error("not implemented")};function Hr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var Re=BigInt(0),pe=BigInt(1),ar=BigInt(2),td=BigInt(3),rd=BigInt(4),nd=BigInt(5),Cg=BigInt(7),od=BigInt(8),Ig=BigInt(9),sd=BigInt(16);function le(r,e){let t=r%e;return t>=Re?t:e+t}function ne(r,e,t){let n=r;for(;e-- >Re;)n*=n,n%=t;return n}function Jf(r,e){if(r===Re)throw new Error("invert: expected non-zero number");if(e<=Re)throw new Error("invert: expected positive modulus, got "+e);let t=le(r,e),n=e,o=Re,s=pe,i=pe,a=Re;for(;t!==Re;){let l=n/t,f=n%t,u=o-i*l,d=s-a*l;n=t,t=f,o=i,s=a,i=u,a=d}if(n!==pe)throw new Error("invert: does not exist");return le(o,e)}function yc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function id(r,e){let t=(r.ORDER+pe)/rd,n=r.pow(e,t);return yc(r,n,e),n}function Tg(r,e){let t=(r.ORDER-nd)/od,n=r.mul(e,ar),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,ar),o),a=r.mul(s,r.sub(i,r.ONE));return yc(r,a,e),a}function Pg(r){let e=$e(r),t=ad(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Cg)/sd;return(a,c)=>{let l=a.pow(c,i),f=a.mul(l,n),u=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(f),c),p=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,p);let m=a.eql(a.sqr(f),c),w=a.cmov(l,f,m);return yc(a,w,c),w}}function ad(r){if(r<td)throw new Error("sqrt is not defined for small field");let e=r-pe,t=0;for(;e%ar===Re;)e/=ar,t++;let n=ar,o=$e(r);for(;ed(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return id;let s=o.pow(n,e),i=(e+pe)/ar;return function(c,l){if(c.is0(l))return l;if(ed(c,l)!==1)throw new Error("Cannot find square root");let f=t,u=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===f)throw new Error("Cannot find square root");let w=pe<<BigInt(f-p-1),g=c.pow(u,w);f=p,u=c.sqr(g),d=c.mul(d,u),h=c.mul(h,g)}return h}}function Lg(r){return r%rd===td?id:r%od===nd?Tg:r%sd===Ig?Pg(r):ad(r)}var St=(r,e)=>(le(r,e)&pe)===pe,Dg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function bc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Dg.reduce((n,o)=>(n[o]="function",n),e);return Gt(r,t),r}function Rg(r,e,t){if(t<Re)throw new Error("invalid exponent, negatives unsupported");if(t===Re)return r.ONE;if(t===pe)return e;let n=r.ONE,o=e;for(;t>Re;)t&pe&&(n=r.mul(n,o)),o=r.sqr(o),t>>=pe;return n}function Wn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ed(r,e){let t=(r.ORDER-pe)/ar,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function hs(r,e){e!==void 0&&Kn(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function $e(r,e,t=!1,n={}){if(r<=Re)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(o=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:l}=hs(r,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let f,u=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Ht(c),ZERO:Re,ONE:pe,allowedLengths:a,create:d=>le(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Re<=d&&d<r},is0:d=>d===Re,isValidNot0:d=>!u.is0(d)&&u.isValid(d),isOdd:d=>(d&pe)===pe,neg:d=>le(-d,r),eql:(d,h)=>d===h,sqr:d=>le(d*d,r),add:(d,h)=>le(d+h,r),sub:(d,h)=>le(d-h,r),mul:(d,h)=>le(d*h,r),pow:(d,h)=>Rg(u,d,h),div:(d,h)=>le(d*Jf(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Jf(d,r),sqrt:s||(d=>(f||(f=Lg(r)),f(u,d))),toBytes:d=>t?pc(d,l):fs(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?vt(d):zr(d);if(i&&(p=le(p,r)),!h&&!u.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>Wn(u,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(u)}function cd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function wc(r){let e=cd(r);return e+Math.ceil(e/2)}function xc(r,e,t=!1){let n=r.length,o=cd(e),s=wc(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?vt(r):zr(r),a=le(i,e-pe)+pe;return t?pc(a,o):fs(a,o)}var Gr=BigInt(0),cr=BigInt(1);function jn(r,e){let t=e.negate();return r?t:e}function _t(r,e){let t=Wn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function dd(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ec(r,e){dd(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Ht(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ld(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=cr);let l=e*n,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}function kg(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Og(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var vc=new WeakMap,hd=new WeakMap;function Sc(r){return hd.get(r)||1}function ud(r){if(r!==Gr)throw new Error("invalid wNAF")}var Wr=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Gr;)t&cr&&(n=n.add(o)),o=o.double(),t>>=cr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Ec(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ec(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:f,isNeg:u,isNegF:d,offsetF:h}=ld(n,a,i);n=c,f?s=s.add(jn(d,t[h])):o=o.add(jn(u,t[l]))}return ud(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Ec(e,this.bits);for(let i=0;i<s.windows&&n!==Gr;i++){let{nextN:a,offset:c,isZero:l,isNeg:f}=ld(n,i,s);if(n=a,!l){let u=t[c];o=o.add(f?u.negate():u)}}return ud(n),o}getPrecomputes(e,t,n){let o=vc.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),vc.set(t,o))),o}cached(e,t,n){let o=Sc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Sc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){dd(t,this.bits),hd.set(e,t),vc.delete(e)}hasCache(e){return Sc(e)!==1}};function pd(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Gr||n>Gr;)t&cr&&(s=s.add(o)),n&cr&&(i=i.add(o)),o=o.double(),t>>=cr,n>>=cr;return{p1:s,p2:i}}function jr(r,e,t,n){kg(t,r),Og(n,e);let o=t.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=ds(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ht(c),f=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c,d=i;for(let h=u;h>=0;h-=c){f.fill(i);for(let m=0;m<s;m++){let w=n[m],g=Number(w>>BigInt(h)&l);f[g]=f[g].add(t[m])}let p=i;for(let m=f.length-1,w=i;m>0;m--)w=w.add(f[m]),p=p.add(w);if(d=d.add(p),h!==0)for(let m=0;m<c;m++)d=d.double()}return d}function fd(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return bc(e),e}else return $e(r,{isLE:t})}function ps(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Gr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=fd(e.p,t.Fp,n),s=fd(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}var Wt=BigInt(0),me=BigInt(1),_c=BigInt(2),Ng=BigInt(8);function Mg(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Bg(r,e={}){let t=ps("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Gt(e,{},{uvRatio:"function"});let a=_c<<BigInt(o.BYTES*8)-me,c=w=>n.create(w),l=e.uvRatio||((w,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,g))}}catch{return{isValid:!1,value:Wt}}});if(!Mg(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(w,g,_=!1){let E=_?me:Wt;return Gn("coordinate "+w,g,E,a),g}function u(w){if(!(w instanceof p))throw new Error("ExtendedPoint expected")}let d=Hr((w,g)=>{let{X:_,Y:E,Z:C}=w,O=w.is0();g==null&&(g=O?Ng:n.inv(C));let V=c(_*g),$=c(E*g),N=n.mul(C,g);if(O)return{x:Wt,y:me};if(N!==me)throw new Error("invZ was invalid");return{x:V,y:$}}),h=Hr(w=>{let{a:g,d:_}=s;if(w.is0())throw new Error("bad point: ZERO");let{X:E,Y:C,Z:O,T:V}=w,$=c(E*E),N=c(C*C),v=c(O*O),D=c(v*v),F=c($*g),R=c(v*c(F+N)),x=c(D+c(_*c($*N)));if(R!==x)throw new Error("bad point: equation left != right (1)");let y=c(E*C),b=c(O*V);if(y!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,E,C){this.X=f("x",g),this.Y=f("y",_),this.Z=f("z",E,!0),this.T=f("t",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:E}=g||{};return f("x",_),f("y",E),new p(_,E,me,c(_*E))}static fromBytes(g,_=!1){let E=n.BYTES,{a:C,d:O}=s;g=mc(Ve(g,E,"point")),Et(_,"zip215");let V=mc(g),$=g[E-1];V[E-1]=$&-129;let N=vt(V),v=_?a:n.ORDER;Gn("point.y",N,Wt,v);let D=c(N*N),F=c(D-me),R=c(O*D-C),{isValid:x,value:y}=l(F,R);if(!x)throw new Error("bad point: invalid y coordinate");let b=(y&me)===me,S=($&128)!==0;if(!_&&y===Wt&&S)throw new Error("bad point: x=0 and x_0=1");return S!==b&&(y=c(-y)),p.fromAffine({x:y,y:N})}static fromHex(g,_=!1){return p.fromBytes(Q("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return m.createCache(this,g),_||this.multiply(_c),this}assertValidity(){h(this)}equals(g){u(g);let{X:_,Y:E,Z:C}=this,{X:O,Y:V,Z:$}=g,N=c(_*$),v=c(O*C),D=c(E*$),F=c(V*C);return N===v&&D===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:_,Y:E,Z:C}=this,O=c(_*_),V=c(E*E),$=c(_c*c(C*C)),N=c(g*O),v=_+E,D=c(c(v*v)-O-V),F=N+V,R=F-$,x=N-V,y=c(D*R),b=c(F*x),S=c(D*x),A=c(R*F);return new p(y,b,A,S)}add(g){u(g);let{a:_,d:E}=s,{X:C,Y:O,Z:V,T:$}=this,{X:N,Y:v,Z:D,T:F}=g,R=c(C*N),x=c(O*v),y=c($*E*F),b=c(V*D),S=c((C+O)*(N+v)-R-x),A=b-y,k=b+y,P=c(x-_*R),L=c(S*A),B=c(k*P),q=c(S*P),oe=c(A*k);return new p(L,B,oe,q)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=m.cached(this,g,C=>_t(p,C));return _t(p,[_,E])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Wt?p.ZERO:this.is0()||g===me?this:m.unsafe(this,g,E=>_t(p,E),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===me?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),E=n.toBytes(_);return E[E.length-1]|=g&me?128:0,E}toHex(){return Xe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return _t(p,g)}static msm(g,_){return jr(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,me,c(s.Gx*s.Gy)),p.ZERO=new p(Wt,me,me,Wt),p.Fp=n,p.Fn=o;let m=new Wr(p,o.BITS);return p.BASE.precompute(8),p}var ms=class{constructor(e){this.ep=e}static fromBytes(e){gc()}static fromHex(e){gc()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Xe(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function Fg(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Gt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||qt,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,D,F)=>{if(Et(F,"phflag"),D.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function f(v){return i.create(vt(v))}function u(v){let D=E.secretKey;v=Q("private key",v,D);let F=Q("hashed private key",e(v),2*D),R=c(F.slice(0,D)),x=F.slice(D,2*D),y=f(R);return{head:R,prefix:x,scalar:y}}function d(v){let{head:D,prefix:F,scalar:R}=u(v),x=o.multiply(R),y=x.toBytes();return{head:D,prefix:F,scalar:R,point:x,pointBytes:y}}function h(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...D){let F=De(...D);return f(e(l(F,Q("context",v),!!n)))}function m(v,D,F={}){v=Q("message",v),n&&(v=n(v));let{prefix:R,scalar:x,pointBytes:y}=d(D),b=p(F.context,R,v),S=o.multiply(b).toBytes(),A=p(F.context,S,y,v),k=i.create(b+A*x);if(!i.isValid(k))throw new Error("sign failed: invalid s");let P=De(S,i.toBytes(k));return Ve(P,E.signature,"result")}let w={zip215:!0};function g(v,D,F,R=w){let{context:x,zip215:y}=R,b=E.signature;v=Q("signature",v,b),D=Q("message",D),F=Q("publicKey",F,E.publicKey),y!==void 0&&Et(y,"zip215"),n&&(D=n(D));let S=b/2,A=v.subarray(0,S),k=vt(v.subarray(S,b)),P,L,B;try{P=r.fromBytes(F,y),L=r.fromBytes(A,y),B=o.multiplyUnsafe(k)}catch{return!1}if(!y&&P.isSmallOrder())return!1;let q=p(x,L.toBytes(),P.toBytes(),D);return L.add(P.multiplyUnsafe(q)).subtract(B).clearCofactor().is0()}let _=s.BYTES,E={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(v=a(E.seed)){return Ve(v,E.seed,"seed")}function O(v){let D=N.randomSecretKey(v);return{secretKey:D,publicKey:h(D)}}function V(v){return bt(v)&&v.length===i.BYTES}function $(v,D){try{return!!r.fromBytes(v,D)}catch{return!1}}let N={getExtendedPublicKey:d,randomSecretKey:C,isValidSecretKey:V,isValidPublicKey:$,toMontgomery(v){let{y:D}=r.fromBytes(v),F=E.publicKey,R=F===32;if(!R&&F!==57)throw new Error("only defined for 25519 and 448");let x=R?s.div(me+D,me-D):s.div(D-me,D+me);return s.toBytes(x)},toMontgomerySecret(v){let D=E.secretKey;Ve(v,D);let F=e(v.subarray(0,D));return c(F).subarray(0,D)},randomPrivateKey:C,precompute(v=8,D=r.BASE){return D.precompute(v,!1)}};return Object.freeze({keygen:O,getPublicKey:h,sign:m,verify:g,utils:N,Point:r,lengths:E})}function Ug(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=$e(e.n,r.nBitLength,!0),o={Fp:t,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:o,hash:r.hash,eddsaOpts:s}}function Kg(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function md(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:o}=Ug(r),s=Bg(e,t),i=Fg(s,n,o);return Kg(r,i)}var qg=BigInt(0),At=BigInt(1),gd=BigInt(2),hv=BigInt(3),Vg=BigInt(5),$g=BigInt(8),Xr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Xn={p:Xr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$g,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function zg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Xr,a=r*r%s*r%s,c=ne(a,gd,s)*a%s,l=ne(c,At,s)*r%s,f=ne(l,Vg,s)*l%s,u=ne(f,e,s)*f%s,d=ne(u,t,s)*u%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,m=ne(p,o,s)*h%s,w=ne(m,e,s)*f%s;return{pow_p_5_8:ne(w,gd,s)*r%s,b2:a}}function Hg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Ac=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Tc(r,e){let t=Xr,n=le(e*e*e,t),o=le(n*n*e,t),s=zg(r*o).pow_p_5_8,i=le(r*n*s,t),a=le(e*i*i,t),c=i,l=le(i*Ac,t),f=a===r,u=a===le(-r,t),d=a===le(-r*Ac,t);return f&&(i=c),(u||d)&&(i=l),St(i,t)&&(i=le(-i,t)),{isValid:f||u,value:i}}var jt=$e(Xn.p,{isLE:!0}),Gg=$e(Xn.n,{isLE:!0}),Wg={...Xn,Fp:jt,hash:jf,adjustScalarBytes:Hg,uvRatio:Tc},Ye=md(Wg);var Cc=Ac,jg=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Xg=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Yg=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Zg=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),yd=r=>Tc(At,r),Qg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ic=r=>Ye.Point.Fp.create(vt(r)&Qg);function bd(r){let{d:e}=Xn,t=Xr,n=g=>jt.create(g),o=n(Cc*r*r),s=n((o+At)*Yg),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=Tc(s,a),f=n(l*r);St(f,t)||(f=n(-f)),c||(l=f),c||(i=o);let u=n(i*(o-At)*Zg-a),d=l*l,h=n((l+l)*a),p=n(u*jg),m=n(At-d),w=n(At+d);return new Ye.Point(n(h*w),n(m*p),n(p*w),n(h*m))}function Jg(r){Ue(r,64);let e=Ic(r.subarray(0,32)),t=bd(e),n=Ic(r.subarray(32,64)),o=bd(n);return new Ct(t.add(o))}var Ct=class r extends ms{constructor(e){super(e)}static fromAffine(e){return new r(Ye.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return Jg(Q("ristrettoHash",e,64))}static fromBytes(e){Ue(e,32);let{a:t,d:n}=Xn,o=Xr,s=C=>jt.create(C),i=Ic(e);if(!Yf(jt.toBytes(i),e)||St(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(At+t*a),l=s(At-t*a),f=s(c*c),u=s(l*l),d=s(t*n*f-u),{isValid:h,value:p}=yd(s(d*u)),m=s(p*l),w=s(p*m*d),g=s((i+i)*m);St(g,o)&&(g=s(-g));let _=s(c*w),E=s(g*_);if(!h||St(E,o)||_===qg)throw new Error("invalid ristretto255 encoding 2");return new r(new Ye.Point(g,_,At,E))}static fromHex(e){return r.fromBytes(Q("ristrettoHex",e,32))}static msm(e,t){return jr(r,Ye.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=Xr,i=w=>jt.create(w),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:f}=yd(i(a*l)),u=i(f*a),d=i(f*c),h=i(u*d*o),p;if(St(o*h,s)){let w=i(t*Cc),g=i(e*Cc);e=w,t=g,p=i(u*Xg)}else p=d;St(e*h,s)&&(t=i(-t));let m=i((n-t)*p);return St(m,s)&&(m=i(-m)),jt.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>jt.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Ct.BASE=new Ct(Ye.Point.BASE);Ct.ZERO=new Ct(Ye.Point.ZERO);Ct.Fp=jt;Ct.Fn=Gg;var Yn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Zn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},gs=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var wd={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new gs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ke=wd;var ys=32,Qn=64,Pc=32;var Yr,xd=(async()=>{try{return await Ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ed(){let r=Ye.utils.randomPrivateKey(),e=Ye.getPublicKey(r);return{privateKey:oy(r,e),publicKey:e}}async function ey(r,e){let t;r.length===Qn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:K(r.subarray(32),"base64url"),d:K(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ke.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ke.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function ty(r,e){let t=r.subarray(0,Pc);return Ye.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function vd(r,e){return Yr==null&&(Yr=await xd),Yr?ey(r,e):ty(r,e)}async function ry(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ke.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ke.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ny(r,e,t){return Ye.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Sd(r,e,t){return Yr==null&&(Yr=await xd),Yr?ry(r,e,t):ny(r,e,t)}function oy(r,e){let t=new Uint8Array(Qn);for(let n=0;n<Pc;n++)t[n]=r[n],t[Pc+n]=e[n];return t}function Zr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Jn=class{type="Ed25519";raw;constructor(e){this.raw=ws(e,ys)}toMultihash(){return Je.digest(je(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Sd(this.raw,t,e);return Zr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},bs=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ws(e,Qn),this.publicKey=new Jn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=vd(this.raw,e);return Zr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function Lc(r){return r=ws(r,ys),new Jn(r)}async function Ad(){let{privateKey:r,publicKey:e}=Ed();return new bs(r,e)}function ws(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new I(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var sy=Math.pow(2,7),iy=Math.pow(2,14),ay=Math.pow(2,21),Dc=Math.pow(2,28),Rc=Math.pow(2,35),kc=Math.pow(2,42),Oc=Math.pow(2,49),W=128,_e=127;function ge(r){if(r<sy)return 1;if(r<iy)return 2;if(r<ay)return 3;if(r<Dc)return 4;if(r<Rc)return 5;if(r<kc)return 6;if(r<Oc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Qr(r,e,t=0){switch(ge(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function cy(r,e,t=0){switch(ge(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Nc(r,e){let t=r[e],n=0;if(n+=t&_e,t<W||(t=r[e+1],n+=(t&_e)<<7,t<W)||(t=r[e+2],n+=(t&_e)<<14,t<W)||(t=r[e+3],n+=(t&_e)<<21,t<W)||(t=r[e+4],n+=(t&_e)*Dc,t<W)||(t=r[e+5],n+=(t&_e)*Rc,t<W)||(t=r[e+6],n+=(t&_e)*kc,t<W)||(t=r[e+7],n+=(t&_e)*Oc,t<W))return n;throw new RangeError("Could not decode varint")}function ly(r,e){let t=r.get(e),n=0;if(n+=t&_e,t<W||(t=r.get(e+1),n+=(t&_e)<<7,t<W)||(t=r.get(e+2),n+=(t&_e)<<14,t<W)||(t=r.get(e+3),n+=(t&_e)<<21,t<W)||(t=r.get(e+4),n+=(t&_e)*Dc,t<W)||(t=r.get(e+5),n+=(t&_e)*Rc,t<W)||(t=r.get(e+6),n+=(t&_e)*kc,t<W)||(t=r.get(e+7),n+=(t&_e)*Oc,t<W))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=Se(ge(r))),e instanceof Uint8Array?Qr(r,e,t):cy(r,e,t)}function lr(r,e=0){return r instanceof Uint8Array?Nc(r,e):ly(r,e)}var Mc=new Float32Array([-0]),Yt=new Uint8Array(Mc.buffer);function Cd(r,e,t){Mc[0]=r,e[t]=Yt[0],e[t+1]=Yt[1],e[t+2]=Yt[2],e[t+3]=Yt[3]}function Id(r,e){return Yt[0]=r[e],Yt[1]=r[e+1],Yt[2]=r[e+2],Yt[3]=r[e+3],Mc[0]}var Bc=new Float64Array([-0]),Ae=new Uint8Array(Bc.buffer);function Td(r,e,t){Bc[0]=r,e[t]=Ae[0],e[t+1]=Ae[1],e[t+2]=Ae[2],e[t+3]=Ae[3],e[t+4]=Ae[4],e[t+5]=Ae[5],e[t+6]=Ae[6],e[t+7]=Ae[7]}function Pd(r,e){return Ae[0]=r[e],Ae[1]=r[e+1],Ae[2]=r[e+2],Ae[3]=r[e+3],Ae[4]=r[e+4],Ae[5]=r[e+5],Ae[6]=r[e+6],Ae[7]=r[e+7],Bc[0]}var uy=BigInt(Number.MAX_SAFE_INTEGER),fy=BigInt(Number.MIN_SAFE_INTEGER),ze=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ur;if(e<uy&&e>fy)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Ld&&(o=0n,++n>Ld&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ur;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ur}},ur=new ze(0,0);ur.toBigInt=function(){return 0n};ur.zzEncode=ur.zzDecode=function(){return this};ur.length=function(){return 1};var Ld=4294967296n;function Dd(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Rd(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Fc(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function nt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function xs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Uc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,nt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw nt(this,4);return xs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw nt(this,4);return xs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw nt(this,4);let e=Id(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw nt(this,4);let e=Pd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw nt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Rd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw nt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw nt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ze(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw nt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw nt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw nt(this,8);let e=xs(this.buf,this.pos+=4),t=xs(this.buf,this.pos+=4);return new ze(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Nc(this.buf,this.pos);return this.pos+=ge(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Kc(r){return new Uc(r instanceof Uint8Array?r:r.subarray())}function ke(r,e,t){let n=Kc(r);return e.decode(n,void 0,t)}function qc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var fr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Vc(){}var zc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},dy=qc();function hy(r){return globalThis.Buffer!=null?Se(r):dy(r)}var ro=class{len;head;tail;states;constructor(){this.len=0,this.head=new fr(Vc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new fr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Hc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Es,10,ze.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ze.fromBigInt(e);return this._push(Es,t.length(),t)}uint64Number(e){return this._push(Qr,ge(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ze.fromBigInt(e).zzEncode();return this._push(Es,t.length(),t)}sint64Number(e){let t=ze.fromNumber(e).zzEncode();return this._push(Es,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push($c,1,e?1:0)}fixed32(e){return this._push(to,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ze.fromBigInt(e);return this._push(to,4,t.lo)._push(to,4,t.hi)}fixed64Number(e){let t=ze.fromNumber(e);return this._push(to,4,t.lo)._push(to,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Cd,4,e)}double(e){return this._push(Td,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push($c,1,0):this.uint32(t)._push(my,t,e)}string(e){let t=Dd(e);return t!==0?this.uint32(t)._push(Fc,t,e):this._push($c,1,0)}fork(){return this.states=new zc(this),this.head=this.tail=new fr(Vc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new fr(Vc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=hy(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function $c(r,e,t){e[t]=r&255}function py(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Hc=class extends fr{next;constructor(e,t){super(py,e,t),this.next=void 0}};function Es(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function to(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function my(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ro.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(gy,e,r),this},ro.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(yy,e,r),this});function gy(r,e,t){e.set(r,t)}function yy(r,e,t){r.length<40?Fc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function Gc(){return new ro}function Oe(r,e){let t=Gc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Jr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Jr||(Jr={}));function vs(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Wc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return vs("enum",Jr.VARINT,t,n)}function Ne(r,e){return vs("message",Jr.LENGTH_DELIMITED,r,e)}var dr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},no=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));var jc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(jc||(jc={}));(function(r){r.codec=()=>Wc(jc)})(fe||(fe={}));var ut;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>ke(t,r.codec(),n)})(ut||(ut={}));var Xc;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>ke(t,r.codec(),n)})(Xc||(Xc={}));function en(r){if(isNaN(r)||r<=0)throw new I("random bytes length must be a Number bigger than 0");return qt(r)}var so={};Fe(so,{MAX_RSA_KEY_SIZE:()=>Yc,generateRSAKeyPair:()=>sl,jwkToJWKKeyPair:()=>Fd,jwkToPkcs1:()=>Ey,jwkToPkix:()=>el,jwkToRSAPrivateKey:()=>ol,pkcs1MessageToJwk:()=>Qc,pkcs1MessageToRSAPrivateKey:()=>tl,pkcs1ToJwk:()=>xy,pkcs1ToRSAPrivateKey:()=>Bd,pkixMessageToJwk:()=>Jc,pkixMessageToRSAPublicKey:()=>nl,pkixToJwk:()=>vy,pkixToRSAPublicKey:()=>rl});var Ss=us;var tn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=so.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}verify(e,t,n){return Md(this.jwk,t,e,n)}},oo=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=so.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}sign(e,t){return Nd(this.jwk,e,t)}};var Yc=8192,Zc=18,by=1062,wy=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function xy(r){let e=gt(r);return Qc(e)}function Qc(r){return{n:K(r[1],"base64url"),e:K(r[2],"base64url"),d:K(r[3],"base64url"),p:K(r[4],"base64url"),q:K(r[5],"base64url"),dp:K(r[6],"base64url"),dq:K(r[7],"base64url"),qi:K(r[8],"base64url"),kty:"RSA"}}function Ey(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new I("JWK was missing components");return tt([Le(Uint8Array.from([0])),Le(T(r.n,"base64url")),Le(T(r.e,"base64url")),Le(T(r.d,"base64url")),Le(T(r.p,"base64url")),Le(T(r.q,"base64url")),Le(T(r.dp,"base64url")),Le(T(r.dq,"base64url")),Le(T(r.qi,"base64url"))]).subarray()}function vy(r){let e=gt(r,{offset:0});return Jc(e)}function Jc(r){let e=gt(r[1],{offset:0});return{kty:"RSA",n:K(e[0],"base64url"),e:K(e[1],"base64url")}}function el(r){if(r.n==null||r.e==null)throw new I("JWK was missing components");return tt([wy,Un(tt([Le(T(r.n,"base64url")),Le(T(r.e,"base64url"))]))]).subarray()}function Bd(r){let e=gt(r);return tl(e)}function tl(r){let e=Qc(r);return ol(e)}function rl(r,e){if(r.byteLength>=by)throw new Or("Key size is too large");let t=gt(r,{offset:0});return nl(t,r,e)}function nl(r,e,t){let n=Jc(r);if(t==null){let o=Ss(ut.encode({Type:fe.RSA,Data:e}));t=ct(Zc,o)}return new tn(n,t)}function ol(r){if(Kd(r)>Yc)throw new I("Key size is too large");let e=Fd(r),t=Ss(ut.encode({Type:fe.RSA,Data:el(e.publicKey)})),n=ct(Zc,t);return new oo(e.privateKey,new tn(e.publicKey,n))}async function sl(r){if(r>Yc)throw new I("Key size is too large");let e=await Ud(r),t=Ss(ut.encode({Type:fe.RSA,Data:el(e.publicKey)})),n=ct(Zc,t);return new oo(e.privateKey,new tn(e.publicKey,n))}function Fd(r){if(r==null)throw new I("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ud(r,e){let t=await Ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Sy(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Nd(r,e,t){let n=await Ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Md(r,e,t,n){let o=await Ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function Sy(r,e){if(r.privateKey==null||r.publicKey==null)throw new I("Private and public key are required");let t=await Promise.all([Ke.get().subtle.exportKey("jwk",r.privateKey),Ke.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Kd(r){if(r.kty!=="RSA")throw new I("invalid key type");if(r.n==null)throw new I("invalid key modulus");return T(r.n,"base64url").length*8}var _s=class extends Vr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,is(e);let n=qn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),wt(s)}update(e){return $r(this),this.iHash.update(e),this}digestInto(e){$r(this),Ue(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},il=(r,e,t)=>new _s(r,e).update(t).digest();il.create=(r,e)=>new _s(r,e);var qd=(r,e)=>(r+(r>=0?e:-e)/Vd)/e;function _y(r,e,t){let[[n,o],[s,i]]=e,a=qd(i*r,t),c=qd(-o*r,t),l=r-a*n-c*s,f=-a*o-c*i,u=l<Tt,d=f<Tt;u&&(l=-l),d&&(f=-f);let h=Ht(Math.ceil(ds(t)/2))+nn;if(l<Tt||l>=h||f<Tt||f>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:d,k2:f}}function cl(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function al(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Et(t.lowS,"lowS"),Et(t.prehash,"prehash"),t.format!==void 0&&cl(t.format),t}var ll=class extends Error{constructor(e=""){super(e)}},It={Err:ll,_tlv:{encode:(r,e)=>{let{Err:t}=It;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Hn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Hn(o.length/2|128):"";return Hn(r)+s+o+e},decode(r,e){let{Err:t}=It,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of l)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=It;if(r<Tt)throw new e("integer: negative integers are not allowed");let t=Hn(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=It;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return zr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=It,o=Q("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=It,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Tt=BigInt(0),nn=BigInt(1),Vd=BigInt(2),As=BigInt(3),Ay=BigInt(4);function rn(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let o=Q("private key",e);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Cy(r,e={}){let t=ps("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Gt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=zd(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,x,y){let{x:b,y:S}=x.toAffine(),A=n.toBytes(b);if(Et(y,"isCompressed"),y){f();let k=!n.isOdd(S);return De($d(k),A)}else return De(Uint8Array.of(4),A,n.toBytes(S))}function d(R){Ve(R,void 0,"Point");let{publicKey:x,publicKeyUncompressed:y}=l,b=R.length,S=R[0],A=R.subarray(1);if(b===x&&(S===2||S===3)){let k=n.fromBytes(A);if(!n.isValid(k))throw new Error("bad point: is not on curve, wrong x");let P=m(k),L;try{L=n.sqrt(P)}catch(oe){let J=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+J)}f();let B=n.isOdd(L);return(S&1)===1!==B&&(L=n.neg(L)),{x:k,y:L}}else if(b===y&&S===4){let k=n.BYTES,P=n.fromBytes(A.subarray(0,k)),L=n.fromBytes(A.subarray(k,k*2));if(!w(P,L))throw new Error("bad point: is not on curve");return{x:P,y:L}}else throw new Error(`bad point: got length ${b}, expected compressed=${x} or uncompressed=${y}`)}let h=e.toBytes||u,p=e.fromBytes||d;function m(R){let x=n.sqr(R),y=n.mul(x,R);return n.add(n.add(y,n.mul(R,s.a)),s.b)}function w(R,x){let y=n.sqr(x),b=m(R);return n.eql(y,b)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,As),Ay),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function E(R,x,y=!1){if(!n.isValid(x)||y&&n.is0(x))throw new Error(`bad point coordinate ${R}`);return x}function C(R){if(!(R instanceof v))throw new Error("ProjectivePoint expected")}function O(R){if(!c||!c.basises)throw new Error("no endo");return _y(R,c.basises,o.ORDER)}let V=Hr((R,x)=>{let{X:y,Y:b,Z:S}=R;if(n.eql(S,n.ONE))return{x:y,y:b};let A=R.is0();x==null&&(x=A?n.ONE:n.inv(S));let k=n.mul(y,x),P=n.mul(b,x),L=n.mul(S,x);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(L,n.ONE))throw new Error("invZ was invalid");return{x:k,y:P}}),$=Hr(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x,y}=R.toAffine();if(!n.isValid(x)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!w(x,y))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(R,x,y,b,S){return y=new v(n.mul(y.X,R),y.Y,y.Z),x=jn(b,x),y=jn(S,y),x.add(y)}class v{constructor(x,y,b){this.X=E("x",x),this.Y=E("y",y,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:y,y:b}=x||{};if(!x||!n.isValid(y)||!n.isValid(b))throw new Error("invalid affine point");if(x instanceof v)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(b)?v.ZERO:new v(y,b,n.ONE)}static fromBytes(x){let y=v.fromAffine(p(Ve(x,void 0,"point")));return y.assertValidity(),y}static fromHex(x){return v.fromBytes(Q("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,y=!0){return F.createCache(this,x),y||this.multiply(As),this}assertValidity(){$(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){C(x);let{X:y,Y:b,Z:S}=this,{X:A,Y:k,Z:P}=x,L=n.eql(n.mul(y,P),n.mul(A,S)),B=n.eql(n.mul(b,P),n.mul(k,S));return L&&B}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:y}=s,b=n.mul(y,As),{X:S,Y:A,Z:k}=this,P=n.ZERO,L=n.ZERO,B=n.ZERO,q=n.mul(S,S),oe=n.mul(A,A),J=n.mul(k,k),G=n.mul(S,A);return G=n.add(G,G),B=n.mul(S,k),B=n.add(B,B),P=n.mul(x,B),L=n.mul(b,J),L=n.add(P,L),P=n.sub(oe,L),L=n.add(oe,L),L=n.mul(P,L),P=n.mul(G,P),B=n.mul(b,B),J=n.mul(x,J),G=n.sub(q,J),G=n.mul(x,G),G=n.add(G,B),B=n.add(q,q),q=n.add(B,q),q=n.add(q,J),q=n.mul(q,G),L=n.add(L,q),J=n.mul(A,k),J=n.add(J,J),q=n.mul(J,G),P=n.sub(P,q),B=n.mul(J,oe),B=n.add(B,B),B=n.add(B,B),new v(P,L,B)}add(x){C(x);let{X:y,Y:b,Z:S}=this,{X:A,Y:k,Z:P}=x,L=n.ZERO,B=n.ZERO,q=n.ZERO,oe=s.a,J=n.mul(s.b,As),G=n.mul(y,A),se=n.mul(b,k),he=n.mul(S,P),Be=n.add(y,b),ie=n.add(A,k);Be=n.mul(Be,ie),ie=n.add(G,se),Be=n.sub(Be,ie),ie=n.add(y,S);let ve=n.add(A,P);return ie=n.mul(ie,ve),ve=n.add(G,he),ie=n.sub(ie,ve),ve=n.add(b,S),L=n.add(k,P),ve=n.mul(ve,L),L=n.add(se,he),ve=n.sub(ve,L),q=n.mul(oe,ie),L=n.mul(J,he),q=n.add(L,q),L=n.sub(se,q),q=n.add(se,q),B=n.mul(L,q),se=n.add(G,G),se=n.add(se,G),he=n.mul(oe,he),ie=n.mul(J,ie),se=n.add(se,he),he=n.sub(G,he),he=n.mul(oe,he),ie=n.add(ie,he),G=n.mul(se,ie),B=n.add(B,G),G=n.mul(ve,ie),L=n.mul(Be,L),L=n.sub(L,G),G=n.mul(Be,se),q=n.mul(ve,q),q=n.add(q,G),new v(L,B,q)}subtract(x){return this.add(x.negate())}is0(){return this.equals(v.ZERO)}multiply(x){let{endo:y}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let b,S,A=k=>F.cached(this,k,P=>_t(v,P));if(y){let{k1neg:k,k1:P,k2neg:L,k2:B}=O(x),{p:q,f:oe}=A(P),{p:J,f:G}=A(B);S=oe.add(G),b=N(y.beta,q,J,k,L)}else{let{p:k,f:P}=A(x);b=k,S=P}return _t(v,[b,S])[0]}multiplyUnsafe(x){let{endo:y}=e,b=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Tt||b.is0())return v.ZERO;if(x===nn)return b;if(F.hasCache(this))return this.multiply(x);if(y){let{k1neg:S,k1:A,k2neg:k,k2:P}=O(x),{p1:L,p2:B}=pd(v,b,A,P);return N(y.beta,L,B,S,k)}else return F.unsafe(b,x)}multiplyAndAddUnsafe(x,y,b){let S=this.multiplyUnsafe(y).add(x.multiplyUnsafe(b));return S.is0()?void 0:S}toAffine(x){return V(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===nn?!0:x?x(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===nn?this:x?x(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return Et(x,"isCompressed"),this.assertValidity(),h(v,this,x)}toHex(x=!0){return Xe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return _t(v,x)}static msm(x,y){return jr(v,o,x,y)}static fromPrivateKey(x){return v.BASE.multiply(rn(o,x))}}v.BASE=new v(s.Gx,s.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO),v.Fp=n,v.Fn=o;let D=o.BITS,F=new Wr(v,e.endo?Math.ceil(D/2):D);return v.BASE.precompute(8),v}function $d(r){return Uint8Array.of(r?2:3)}function zd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Iy(r,e={}){let{Fn:t}=r,n=e.randomBytes||qt,o=Object.assign(zd(r.Fp,t),{seed:wc(t.ORDER)});function s(h){try{return!!rn(t,h)}catch{return!1}}function i(h,p){let{publicKey:m,publicKeyUncompressed:w}=o;try{let g=h.length;return p===!0&&g!==m||p===!1&&g!==w?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return xc(Ve(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(rn(t,h)).toBytes(p)}function l(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function f(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:m,publicKeyUncompressed:w}=o;if(t.allowedLengths||p===m)return;let g=Q("key",h).length;return g===m||g===w}function u(h,p,m=!0){if(f(h)===!0)throw new Error("first arg must be private key");if(f(p)===!1)throw new Error("second arg must be public key");let w=rn(t,h);return r.fromHex(p).multiply(w).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>rn(t,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function Ty(r,e,t={}){is(e),Gt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||qt,o=t.hmac||((y,...b)=>il(e,y,De(...b))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=Iy(r,t),p={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function w(y){let b=a>>nn;return y>b}function g(y,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function _(y,b){cl(b);let S=h.signature,A=b==="compact"?S:b==="recovered"?S+1:void 0;return Ve(y,A,`${b} signature`)}class E{constructor(b,S,A){this.r=g("r",b),this.s=g("s",S),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(b,S=m){_(b,S);let A;if(S==="der"){let{r:B,s:q}=It.toSig(Ve(b));return new E(B,q)}S==="recovered"&&(A=b[0],S="compact",b=b.subarray(1));let k=i.BYTES,P=b.subarray(0,k),L=b.subarray(k,k*2);return new E(i.fromBytes(P),i.fromBytes(L),A)}static fromHex(b,S){return this.fromBytes(or(b),S)}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){let S=s.ORDER,{r:A,s:k,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*Vd<S&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=P===2||P===3?A+a:A;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");let q=s.toBytes(B),oe=r.fromBytes(De($d((P&1)===0),q)),J=i.inv(B),G=O(Q("msgHash",b)),se=i.create(-G*J),he=i.create(k*J),Be=r.BASE.multiplyUnsafe(se).add(oe.multiplyUnsafe(he));if(Be.is0())throw new Error("point at infinify");return Be.assertValidity(),Be}hasHighS(){return w(this.s)}toBytes(b=m){if(cl(b),b==="der")return or(It.hexFromSig(this));let S=i.toBytes(this.r),A=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return De(Uint8Array.of(this.recovery),S,A)}return De(S,A)}toHex(b){return Xe(this.toBytes(b))}assertValidity(){}static fromCompact(b){return E.fromBytes(Q("sig",b),"compact")}static fromDER(b){return E.fromBytes(Q("sig",b),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Xe(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Xe(this.toBytes("compact"))}}let C=t.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let S=zr(b),A=b.length*8-c;return A>0?S>>BigInt(A):S},O=t.bits2int_modN||function(b){return i.create(C(b))},V=Ht(c);function $(y){return Gn("num < 2^"+c,y,Tt,V),i.toBytes(y)}function N(y,b){return Ve(y,void 0,"message"),b?Ve(e(y),void 0,"prehashed message"):y}function v(y,b,S){if(["recovered","canonical"].some(se=>se in S))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:k,extraEntropy:P}=al(S,p);y=N(y,k);let L=O(y),B=rn(i,b),q=[$(B),$(L)];if(P!=null&&P!==!1){let se=P===!0?n(h.secretKey):P;q.push(Q("extraEntropy",se))}let oe=De(...q),J=L;function G(se){let he=C(se);if(!i.isValidNot0(he))return;let Be=i.inv(he),ie=r.BASE.multiply(he).toAffine(),ve=i.create(ie.x);if(ve===Tt)return;let $o=i.create(Be*i.create(J+ve*B));if($o===Tt)return;let ju=(ie.x===ve?0:2)|Number(ie.y&nn),Xu=$o;return A&&w($o)&&(Xu=i.neg($o),ju^=1),new E(ve,Xu,ju)}return{seed:oe,k2sig:G}}function D(y,b,S={}){y=Q("message",y);let{seed:A,k2sig:k}=v(y,b,S);return Qf(e.outputLen,i.BYTES,o)(A,k)}function F(y){let b,S=typeof y=="string"||bt(y),A=!S&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!S&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)b=new E(y.r,y.s);else if(S){try{b=E.fromBytes(Q("sig",y),"der")}catch(k){if(!(k instanceof It.Err))throw k}if(!b)try{b=E.fromBytes(Q("sig",y),"compact")}catch{return!1}}return b||!1}function R(y,b,S,A={}){let{lowS:k,prehash:P,format:L}=al(A,p);if(S=Q("publicKey",S),b=N(Q("message",b),P),"strict"in A)throw new Error("options.strict was renamed to lowS");let B=L===void 0?F(y):E.fromBytes(Q("sig",y),L);if(B===!1)return!1;try{let q=r.fromBytes(S);if(k&&B.hasHighS())return!1;let{r:oe,s:J}=B,G=O(b),se=i.inv(J),he=i.create(G*se),Be=i.create(oe*se),ie=r.BASE.multiplyUnsafe(he).add(q.multiplyUnsafe(Be));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function x(y,b,S={}){let{prehash:A}=al(S,p);return b=N(b,A),E.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:r,sign:D,verify:R,recoverPublicKey:x,Signature:E,hash:e})}function Py(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$e(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:t,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:s}}function Ly(r){let{CURVE:e,curveOpts:t}=Py(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function Dy(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,hs(t.Fn.ORDER,t.Fn.BITS))})}function Hd(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:o}=Ly(r),s=Cy(e,t),i=Ty(s,n,o);return Dy(r,i)}function Gd(r,e){let t=n=>Hd({...r,hash:n});return{...t(e),create:t}}var fl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ry={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Wd=BigInt(2);function ky(r){let e=fl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,f=l*l*r%e,u=ne(f,t,e)*f%e,d=ne(u,t,e)*f%e,h=ne(d,Wd,e)*l%e,p=ne(h,o,e)*h%e,m=ne(p,s,e)*p%e,w=ne(m,a,e)*m%e,g=ne(w,c,e)*w%e,_=ne(g,a,e)*m%e,E=ne(_,t,e)*f%e,C=ne(E,i,e)*p%e,O=ne(C,n,e)*l%e,V=ne(O,Wd,e);if(!ul.eql(ul.sqr(V),r))throw new Error("Cannot find square root");return V}var ul=$e(fl.p,{sqrt:ky}),ot=Gd({...fl,Fp:ul,lowS:!0,endo:Ry},us);function jd(r,e,t){let n=qr.digest(e instanceof Uint8Array?e:e.subarray());if(Zr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),ot.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Yn(String(o))});try{return ot.sign(n.digest,r).toDERRawBytes()}catch(o){throw new Yn(String(o))}}function Xd(r,e,t,n){let o=qr.digest(t instanceof Uint8Array?t:t.subarray());if(Zr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ot.verify(e,s,r))).catch(s=>{throw s.name==="AbortError"?s:new Zn(String(s))});try{return n?.signal?.throwIfAborted(),ot.verify(e,o.digest,r)}catch(s){throw new Zn(String(s))}}var io=class{type="secp256k1";raw;_key;constructor(e){this._key=Qd(e),this.raw=Yd(this._key)}toMultihash(){return Je.digest(je(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}verify(e,t,n){return Xd(this._key,t,e,n)}},Cs=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Zd(e),this.publicKey=new io(t??Jd(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}sign(e,t){return jd(this.raw,e,t)}};function dl(r){return new io(r)}async function eh(){let r=Oy();return new Cs(r)}function Yd(r){return ot.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Zd(r){try{return ot.getPublicKey(r,!0),r}catch(e){throw new Tn(String(e))}}function Qd(r){try{return ot.ProjectivePoint.fromHex(r),r}catch(e){throw new Or(String(e))}}function Jd(r){try{return ot.getPublicKey(r,!0)}catch(e){throw new Tn(String(e))}}function Oy(){return ot.utils.randomPrivateKey()}async function th(r,e){if(r==="Ed25519")return Ad();if(r==="secp256k1")return eh();if(r==="RSA")return sl(Ny(e));if(r==="ECDSA")return kf(My(e));throw new Bt}function on(r,e){let{Type:t,Data:n}=ut.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return rl(o,e);case fe.Ed25519:return Lc(o);case fe.secp256k1:return dl(o);case fe.ECDSA:return sc(o);default:throw new Bt}}function rh(r){let{Type:e,Data:t}=ut.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return Lc(n);case fe.secp256k1:return dl(n);case fe.ECDSA:return sc(n);default:throw new Bt}}function je(r){return ut.encode({Type:fe[r.type],Data:r.raw})}function Ny(r){return r==null?2048:parseInt(r,10)}function My(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new I("Unsupported curve, should be P-256, P-384 or P-521")}var nh=Symbol.for("nodejs.util.inspect.custom"),By=114,ao=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Jo]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(By,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Y(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Y(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[nh](){return`PeerId(${this.toString()})`}},co=class extends ao{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},lo=class extends ao{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},uo=class extends ao{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Fy=2336,fo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Je.digest(T(this.url))}[nh](){return`PeerId(${this.url})`}[Jo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(Fy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}};var Uy=114,oh=2336;function ft(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=mt(ee.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return ho(ue.parse(r));if(e==null)throw new I('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=mt(e.decode(r))}return sn(t)}function hl(r){if(r.type==="Ed25519")return new lo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new uo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new co({multihash:r.toCID().multihash,publicKey:r});throw new Bt}function sh(r){return hl(r.publicKey)}function sn(r){if(qy(r))return new co({multihash:r});if(Ky(r))try{let e=rh(r);if(e.type==="Ed25519")return new lo({multihash:r,publicKey:e});if(e.type==="secp256k1")return new uo({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new fo(new URL(t))}throw new Go("Supplied PeerID Multihash is invalid")}function ho(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Uy&&r.code!==oh)throw new Ho("Supplied PeerID CID is invalid");if(r.code===oh){let e=K(r.multihash.digest);return new fo(new URL(e))}return sn(r.multihash)}function Ky(r){return r.code===Je.code}function qy(r){return r.code===qr.code}async function ih(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new I("Private network is enforced, but no protector was provided");return r}function Vy(r,e){if(typeof r=="string")return $y(r);if(typeof r=="number")return Gy(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var Is=Vy;function $y(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function zy(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Hy(r){let e=Math.abs(r);return e>=315576e5?hr(r,e,315576e5,"year"):e>=26298e5?hr(r,e,26298e5,"month"):e>=6048e5?hr(r,e,6048e5,"week"):e>=864e5?hr(r,e,864e5,"day"):e>=36e5?hr(r,e,36e5,"hour"):e>=6e4?hr(r,e,6e4,"minute"):e>=1e3?hr(r,e,1e3,"second"):`${r} ms`}function Gy(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Hy(r):zy(r)}function hr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function pl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Is,t.destroy=l,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let u=0;for(let d=0;d<f.length;d++)u=(u<<5)-u+f.charCodeAt(d),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(f){let u,d=null,h,p;function m(...w){if(!m.enabled)return;let g=m,_=Number(new Date),E=_-(u||_);g.diff=E,g.prev=u,g.curr=_,u=_,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let C=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(V,$)=>{if(V==="%%")return"%";C++;let N=t.formatters[$];if(typeof N=="function"){let v=w[C];V=N.call(g,v),w.splice(C,1),C--}return V}),t.formatArgs.call(g,w),(g.log||t.log).apply(g,w)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:w=>{d=w}}),typeof t.init=="function"&&t.init(m),m}function n(f,u){let d=t(this.namespace+(typeof u>"u"?":":u)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let u,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(u=0;u<h;u++)d[u]&&(f=d[u].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let u,d;for(u=0,d=t.skips.length;u<d;u++)if(t.skips[u].test(f))return!1;for(u=0,d=t.names.length;u<d;u++)if(t.names[u].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Ts=Jy(),Wy=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function jy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Xy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Is(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Yy=console.debug??console.log??(()=>{});function Zy(r){try{r?Ts?.setItem("debug",r):Ts?.removeItem("debug")}catch{}}function Qy(){let r;try{r=Ts?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Jy(){try{return localStorage}catch{}}function e0(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var ah=pl({formatArgs:Xy,save:Zy,load:Qy,useColors:jy,setupFormatters:e0,colors:Wy,storage:Ts,log:Yy});var qe=ah;qe.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);qe.formatters.t=r=>r==null?"undefined":We.baseEncode(r);qe.formatters.m=r=>r==null?"undefined":Ga.baseEncode(r);qe.formatters.p=r=>r==null?"undefined":r.toString();qe.formatters.c=r=>r==null?"undefined":r.toString();qe.formatters.k=r=>r==null?"undefined":r.toString();qe.formatters.a=r=>r==null?"undefined":r.toString();qe.formatters.e=r=>{if(r==null)return"undefined";let e=ch(r.message),t=ch(r.stack);return e!=null&&t!=null?t.includes(e)?t:`${e}
|
|
3
|
+
${t}`:t??e??r.toString()};function t0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ps(){return{forComponent(r){return lh(r)}}}function lh(r){let e=t0(`${r}:trace`);return qe.enabled(`${r}:trace`)&&qe.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=qe(`${r}:trace`)),Object.assign(qe(r),{error:qe(`${r}:error`),trace:e,newScope:t=>lh(`${r}:${t}`)})}function ch(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function pr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Ls(r){let e=mt(ee.decode(`z${r}`));return sn(e)}var Ze=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return pr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return pr(this.map.values(),e=>e.key)}values(){return pr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var mr=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return pr(this.set.entries(),e=>{let t=Ls(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Ls(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pr(this.set.values(),e=>Ls(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var ml={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},uh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},fh=new globalThis.TextEncoder;function r0(r,e){let t=ml[e],n=uh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function n0(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ml[e],o=uh[e],s=r;for(;s.length>0;){let i=fh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function gl(r,{size:e=32,utf8Buffer:t}={}){if(!ml[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return n0(r,e,t);r=fh.encode(r)}return r0(r,e)}var po={hash:r=>Number(gl(r,{size:32})),hashV:(r,e)=>o0(po.hash(r,e))};function o0(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var yl=64,st=class{fp;h;seed;constructor(e,t,n,o=2){if(o>yl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Y(this.fp,e.fp):!1}};function gr(r,e){return Math.floor(Math.random()*(e-r))+r}var yr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");let t=gr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var s0=500,mo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??po,this.seed=e.seed??gr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new st(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new yr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new yr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[gr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new yr(this.bucketSize));for(let a=0;a<s0;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new yr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new st(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=T(e));let t=new st(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},i0={1:.5,2:.84,4:.95,8:.98};function a0(r=.001){return r>.002?2:r>1e-5?4:8}function dh(r,e=.001){let t=a0(e),n=i0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),yl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Ds=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??po,this.seed=e.seed??gr(0,Math.pow(2,10)),this.filterSeries=[new mo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new mo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function go(r,e=.001,t){return new Ds({...dh(r,e),...t??{}})}function z(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new I(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Rs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var hh=45,c0=15,an=new Rs;function ks(r){if(!(r.length>c0))return an.new(r).parseWith(()=>an.readIPv4Addr())}function Os(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>hh))return an.new(r).parseWith(()=>an.readIPv6Addr())}function cn(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>hh)return;let t=an.new(r).parseWith(()=>an.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function ph(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function mh(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function bl(r){switch(r.length){case br:return r.join(".");case wr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function gh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function yh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var br=4,wr=16,XS=parseInt("0xFFFF",16),l0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function yo(r,e){e.length===wr&&r.length===br&&ph(e,0,11)&&(e=e.slice(12)),e.length===br&&r.length===wr&&mh(r,l0,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function bh(r,e){if(typeof e=="string"&&(e=cn(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function wl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=br,o=ks(e);if(o==null&&(n=wr,o=Os(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=xl(s,8*n);return{network:yo(o,i),mask:i}}function xl(r,e){if(e!==8*br&&e!==8*wr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var ln=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=wl(e));else{let n=cn(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=cn(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=xl(o,8*n.length);this.network=yo(n,this.mask)}}contains(e){return bh({network:this.network,mask:this.mask},e)}toString(){let e=gh(this.mask),t=e!==-1?String(e):yh(this.mask);return bl(this.network)+"/"+t}};function wh(r){try{let e=z(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function xh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function bo(r){try{let e=z(r);switch(e.type){case"ip4":case"ip6":return xh(e.host);default:return!1}}catch{return!1}}function xe(r){try{return z(r),!0}catch{return!1}}function it(r){return!!ks(r)}function Ns(r){return!!Os(r)}var vh=Ca(Eh(),1),u0=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],f0=u0.map(r=>new vh.Netmask(r));function El(r){for(let e of f0)if(e.contains(r))return!0;return!1}function d0(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function h0(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return El(o)}function p0(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function m0(r){let e=r.split(":"),t=e[e.length-1];return El(t)}function g0(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function un(r){if(it(r))return El(r);if(d0(r))return h0(r);if(p0(r))return m0(r);if(Ns(r))return g0(r)}function Pt(r){try{let e=z(r);switch(e.type){case"ip4":case"ip6":return un(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ms=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},fn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ms(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Ms(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var vl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function dn(r={}){return y0(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function y0(r,e){e=e??{};let t=e.onEnd,n=new fn,o,s,i,a=ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,g)=>{s=_=>{s=null,n.push(_);try{w(r(n))}catch(E){g(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ye()})}},l=w=>s!=null?s(w):(n.push(w),o),f=w=>(n=new fn,s!=null?s({error:w}):(n.push({error:w}),o)),u=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},d=w=>i?o:(i=!0,w!=null?f(w):l({done:!0})),h=()=>(n=new fn,d(),{done:!0}),p=w=>(d(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:u,end:d,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,E;g!=null&&(_=new Promise((C,O)=>{E=()=>{O(new vl)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,_])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var xo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Sl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Sh=r=>globalThis.DOMException===void 0?new Sl(r):new DOMException(r),_h=r=>{let e=r.reason===void 0?Sh("This operation was aborted."):r.reason;return e instanceof Error?e:Sh(e)};function Eo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(_h(h)),a=()=>{u(_h(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new xo;i=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var b0=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function w0(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=b0(r),u=(...h)=>{let p=t.multiArgs?h:h[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},d=h=>{n(),i(h)};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Eo(o,{milliseconds:t.timeout});return s.cancel=n,s}return o}function at(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=w0(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function vo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Bs=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Fs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},xr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function x0(r){return r.reason}async function Lt(r,e,t){if(e==null)return r;let n=t?.translateError??x0;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Us=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ye(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function E0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ks=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=E0(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Qe),this.cleanup())}async join(e={}){let t=new Us(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Lt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var hn=class extends Pe{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=vo(this.emitEmpty.bind(this),1),this.emitIdle=vo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Fs;let n=new Ks(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await at(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await at(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await at(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=dn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Qe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function Dt(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var pn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var v0=1.2,S0=2,_0=5e3,A0=6e4,C0=5e3,qs=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??C0;this.success=new pn(t),this.failure=new pn(t),this.next=new pn(t),this.failureMultiplier=e.failureMultiplier??S0,this.timeoutMultiplier=e.timeoutMultiplier??v0,this.minTimeout=e.minTimeout??_0,this.maxTimeout=e.maxTimeout??A0,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=Dt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Rt=class extends Error{static name="ValidationError";name="ValidationError"},Vs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},$s=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Al(r){return e=>K(e,r)}function Cl(r){return e=>T(e,r)}function mn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Er(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ah(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Er(n);return et([t,o],t.length+o.length)}function Ch(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=We.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Er(n);return et([t,o],t.length+o.length)}function Il(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=K(e,"base32"),o=mn(t);return`${n}:${o}`}var Tl=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},Ih=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=it(t[n]),i;s&&(i=Tl(t[n]),t[n]=K(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Th=function(r){if(r.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Ph=function(r){if(r.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}};function Lh(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}}var _l=Object.values(Mn).map(r=>r.decoder),I0=(function(){let r=_l[0].or(_l[1]);return _l.slice(2).forEach(e=>r=r.or(e)),r})();function Dh(r){return I0.decode(r)}function Rh(r){return e=>r.encoder.encode(e)}function T0(r){if(parseInt(r).toString()!==r)throw new Rt("Value must be an integer")}function P0(r){if(r<0)throw new Rt("Value must be a positive integer, or zero")}function L0(r){return e=>{if(e>r)throw new Rt(`Value must be smaller than or equal to ${r}`)}}function D0(...r){return e=>{for(let t of r)t(e)}}var So=D0(T0,P0,L0(65535));var be=-1,Pl=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new $s(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},kt=new Pl,G0=[{code:4,name:"ip4",size:32,valueToBytes:Tl,bytesToValue:Th,validate:r=>{if(!it(r))throw new Rt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Er,bytesToValue:mn,validate:So},{code:273,name:"udp",size:16,valueToBytes:Er,bytesToValue:mn,validate:So},{code:33,name:"dccp",size:16,valueToBytes:Er,bytesToValue:mn,validate:So},{code:41,name:"ip6",size:128,valueToBytes:Ih,bytesToValue:Ph,stringToValue:Lh,validate:r=>{if(!Ns(r))throw new Rt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:be},{code:43,name:"ipcidr",size:8,bytesToValue:Al("base10"),valueToBytes:Cl("base10")},{code:53,name:"dns",size:be},{code:54,name:"dns4",size:be},{code:55,name:"dns6",size:be},{code:56,name:"dnsaddr",size:be},{code:132,name:"sctp",size:16,valueToBytes:Er,bytesToValue:mn,validate:So},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:be,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:be,bytesToValue:Al("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Cl("base58btc")(r):ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Il,valueToBytes:Ah},{code:445,name:"onion3",size:296,bytesToValue:Il,valueToBytes:Ch},{code:446,name:"garlic64",size:be},{code:447,name:"garlic32",size:be},{code:448,name:"tls"},{code:449,name:"sni",size:be},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:be,bytesToValue:Rh(Wa),valueToBytes:Dh},{code:480,name:"http"},{code:481,name:"http-path",size:be,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:be}];G0.forEach(r=>{kt.addProtocol(r)});function kh(r){let e=[],t=0;for(;t<r.length;){let n=lr(r,t),o=kt.getProtocol(n),s=ge(n),i=W0(o,r,t+s),a=0;i>0&&o.size===be&&(a=ge(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let f=t+s+a,u=r.subarray(f,f+i);l.value=o.bytesToValue?.(u)??K(u)}e.push(l),t+=c}return e}function Oh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=kt.getProtocol(n.code),s=ge(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===be&&(c=ge(a)));let l=new Uint8Array(s+c+a),f=0;Qr(n.code,l,f),f+=s,i!=null&&(o.size===be&&(Qr(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return et(t,e)}function Nh(r){if(r.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=kt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ee(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ee(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function Mh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=kt.getProtocol(e.code);if(t==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function W0(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:lr(e,t)}var j0=Symbol.for("nodejs.util.inspect.custom"),$l=Symbol.for("@multiformats/multiaddr");function X0(r){if(r==null&&(r="/"),Qt(r))return r.getComponents();if(r instanceof Uint8Array)return kh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Nh(r);if(Array.isArray(r))return r;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var js=class r{[$l]=!0;#e;#n;#t;constructor(e="/",t={}){this.#e=X0(e),t.validate!==!1&&Y0(this)}get bytes(){return this.#t==null&&(this.#t=Oh(this.#e)),this.#t}toString(){return this.#n==null&&(this.#n=Mh(this.#e)),this.#n}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Vs(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Y(this.bytes,e.bytes)}[j0](){return`Multiaddr(${this.toString()})`}};function Y0(r){r.getComponents().forEach(e=>{let t=kt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Qt(r){return!!r?.[$l]}function j(r){return new js(r)}var Xs=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Bh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Xs(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Xs(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var zl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ye(),this.haveNext=ye()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ye(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ye(),await Bh(this.readNext.promise,t?.signal,t)}};function Fh(){return new zl}function Z0(r){return r[Symbol.asyncIterator]!=null}async function Q0(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*J0(r){let e=new AbortController,t=Fh();Q0(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*eb(r){for(let e of r)yield*e}function tb(...r){let e=[];for(let t of r)Z0(t)||e.push(t);return e.length===r.length?eb(e):J0(r)}var En=tb;var rb=4194304,Ys=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Gl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Wl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},jl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function nb(r){return typeof r?.closeRead=="function"}function ob(r){return typeof r?.close=="function"}function Hl(r){return nb(r)?r.readStatus==="closing"||r.readStatus==="closed":ob(r)?r.status!=="open":!1}function sb(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Xl(r,e){let t=e?.maxBufferSize??rb,n=new Z,o=Promise.withResolvers(),s=!1;if(!sb(r))throw new I("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>t){let u=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${u} > ${t}`))}o.resolve()};r.addEventListener("message",i);let a=f=>{f.error!=null?o.reject(f.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(f){if(s===!0)throw new Ys("Stream was unwrapped");if(Hl(r)){if(f?.bytes==null)return null;if(n.byteLength<f.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new xr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let u=f?.bytes??1;for(;;){if(n.byteLength>=u){o.resolve();break}if(await Lt(o.promise,f?.signal),Hl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(Hl(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new xr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(f)}let h=n.sublist(0,d);return n.consume(d),h},async write(f,u){if(s===!0)throw new Ys("Stream was unwrapped");r.send(f)||await at(r,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Zs(r,e={}){let t=Xl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ge(e.maxDataLength));let n=e?.lengthDecoder??lr,o=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new Z;for(;;){let f=await t.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Gl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new jl(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Wl(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new xr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new xr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Z(o(i.byteLength),i),a)},async writeV(i,a){let c=new Z(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},vn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Js=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},_o=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ei(r){return r[Symbol.asyncIterator]!=null}function Uh(r,e){if(r.byteLength>e)throw new vn("Message length too long")}var ri=r=>{let e=ge(r),t=Se(e);return Xt(r,t),ri.bytes=e,t};ri.bytes=0;function ni(r,e){e=e??{};let t=e.lengthEncoder??ri,n=e?.maxDataLength??4194304;function*o(s){Uh(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ei(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}ni.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ri,n=e?.maxDataLength??4194304;return Uh(r,n),new Z(t(r.byteLength),r)};var _r;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(_r||(_r={}));var Zl=r=>{let e=lr(r);return Zl.bytes=ge(e),e};Zl.bytes=0;function Yl(r,e){let t=new Z,n=_r.LENGTH,o=-1,s=e?.lengthDecoder??Zl,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===_r.LENGTH)try{if(o=s(t),o<0)throw new Qs("Invalid message length");if(o>a)throw new vn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=_r.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Js("Message length length too long");break}throw l}if(n===_r.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=_r.LENGTH}}}return ei(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new _o("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new _o("Unexpected end of input")})()}Yl.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Yl(n,{...e??{},onLength:s=>{t=s}})};var oi=class extends hn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var si=class extends hn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ii=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ql}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Bs("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Ql=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Jl=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ce(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Jl({name:e,metrics:t}):n=new Map,n}var eu=class extends Ze{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function tu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new eu({name:e,metrics:t}):n=new Ze,n}var Ao;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>ke(t,r.codec(),n)})(Ao||(Ao={}));var ai=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Sn=class r{static createFromProtobuf=e=>{let t=Ao.decode(e),n=on(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=Kh(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new ai("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Ao.encode({publicKey:je(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Y(this.marshal(),e.marshal())}async validate(e,t){let n=Kh(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Kh=(r,e,t)=>{let n=T(r),o=Xt(n.byteLength),s=Xt(e.length),i=Xt(t.length);return new Z(o,n,s,e,i,t)};var qh="libp2p-peer-record",Vh=Uint8Array.from([3,1]);var Co;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>Oe(s,n.codec()),n.decode=(s,i)=>ke(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new dr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Oe(n,r.codec()),r.decode=(n,o)=>ke(n,r.codec(),o)})(Co||(Co={}));function $h(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ar=class r{static createFromProtobuf=e=>{let t=Co.decode(e),n=sn(mt(t.peerId)),o=(t.addresses??[]).map(i=>j(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=qh;static CODEC=Vh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Co.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!$h(this.multiaddrs,e.multiaddrs))}};function ab(r){return r[Symbol.asyncIterator]!=null}function cb(r){if(ab(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Io=cb;var He=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function ci(r,e,t,n){let o=new He(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){nu(t,"abort",u),nu(r,e,l),nu(r,s,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},u=()=>{c(),a(o)};ru(t,"abort",u),ru(r,e,l),ru(r,s,f)})}function ru(r,e,t){r!=null&&(zh(r)?r.addEventListener(e,t):r.addListener(e,t))}function nu(r,e,t){r!=null&&(zh(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function zh(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var li=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var ui=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Hh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new ui(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ui(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var fi=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new He)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function lb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var di=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=lb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new He),this.cleanup())}async join(e={}){let t=new fi(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Hh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function ou(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var To=class extends Pe{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=ou(this.emitEmpty.bind(this),1),this.emitIdle=ou(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new li;let n=new di(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new He)}),this.clear()}async onEmpty(e){this.size!==0&&await ci(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ci(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ci(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=dn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new He("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var hi="lock:worker:request-read",pi="lock:worker:abort-read-request",mi="lock:worker:release-read",gi="lock:master:grant-read",yi="lock:master:error-read",bi="lock:worker:request-write",wi="lock:worker:abort-write-request",xi="lock:worker:release-write",Ei="lock:master:grant-write",vi="lock:master:error-write",Si="lock:worker:finalize",_i="mortice",Gh={singleProcess:!1};var su=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(u=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:i,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===s&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===Si&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var Wh=(r=10)=>Math.random().toString().substring(2,r+2);var Ai=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(_i)}readLock(e){return this.sendRequest(hi,pi,gi,yi,mi,e)}writeLock(e){return this.sendRequest(bi,wi,Ei,vi,xi,e)}finalize(){this.channel.postMessage({type:Si,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=Wh();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",u)})}};var jh=r=>{if(r=Object.assign({},Gh,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(_i),n=new Pe;return t.addEventListener("message",su(n,t,"requestReadLock","abortReadLockRequest",hi,pi,yi,mi,gi)),t.addEventListener("message",su(n,t,"requestWriteLock","abortWriteLockRequest",bi,wi,vi,xi,Ei)),n}return new Ai(r.name)};var Cr=new Map,Po;function Xh(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function ub(r){if(Po==null&&(Po=jh(r),!Xh(Po))){let e=Po;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Cr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Cr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Cr.get(n);o?.finalize()})}return Po}async function iu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new He)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Yh=(r,e)=>{let t=Cr.get(r);if(t!=null)return t;let n=ub(e);if(Xh(n))return t=n,Cr.set(r,t),t;let o=new To({concurrency:1}),s;return t={async readLock(i){if(s!=null)return iu(s,i);s=new To({concurrency:e.concurrency,autoStart:!1});let a=s,c=iu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,iu(o,i)},finalize:()=>{Cr.delete(r)},queue:o},Cr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var fb={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function au(r){let e=Object.assign({},fb,r);return Yh(e.name,e)}var Ot;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ce(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>Oe(i,o.codec()),o.decode=(i,a)=>ke(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ii.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Ii.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>Oe(i,o.codec()),o.decode=(i,a)=>ke(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Ci.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new dr('Decode error - map field "addresses" had too many elements');a.addresses.push(Ci.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new dr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new no('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new no('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Oe(o,r.codec()),r.decode=(o,s)=>ke(o,r.codec(),s)})(Ot||(Ot={}));var Ci;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>ke(t,r.codec(),n)})(Ci||(Ci={}));var Ii;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Oe(t,r.codec()),r.decode=(t,n)=>ke(t,r.codec(),n)})(Ii||(Ii={}));function db(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=on(e.publicKey,t);return hl(n)}function Zh(r,e,t){let n=Ot.decode(e);return _n(r,n,t)}function _n(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:db(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function Qh(r,e){return hb(r.addresses,e.addresses)&&pb(r.protocols,e.protocols)&&mb(r.publicKey,e.publicKey)&&gb(r.peerRecordEnvelope,e.peerRecordEnvelope)&&yb(r.metadata,e.metadata)&&bb(r.tags,e.tags)}function hb(r,e){return ep(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Y(t.multiaddr,n.multiaddr)))}function pb(r,e){return ep(r,e,(t,n)=>t===n)}function mb(r,e){return Jh(r,e)}function gb(r,e){return Jh(r,e)}function yb(r,e){return tp(r,e,(t,n)=>Y(t,n))}function bb(r,e){return tp(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Jh(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Y(r,e):!1}function ep(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function tp(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Nt="/",rp=new TextEncoder().encode(Nt),Ti=rp[0],Ir=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ti)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Nt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=rp),this._buf[0]!==Ti){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ti,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ti;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Nt).slice(1)}type(){return wb(this.baseNamespace())}name(){return xb(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Nt)||(e+=Nt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Nt):new r(e.slice(0,-1).join(Nt))}child(e){return this.toString()===Nt?e:e.toString()===Nt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Eb(e.map(t=>t.namespaces()))])}};function wb(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function xb(r){let e=r.split(":");return e[e.length-1]}function Eb(r){return[].concat(...r)}var cu="/peers/";function Lo(r){if(!Ft(r)||r.type==null)throw new I("Invalid PeerId");let e=r.toCID().toString();return new Ir(`${cu}${e}`)}async function np(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=j(i.multiaddr)),!Qt(i.multiaddr))throw new I("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(j(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Li(r,e,t,n){if(e==null)throw new I("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new I("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new I("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Pi(d,{validate:op})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Pi(d,{validate:sp,map:ip})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Pi([...a.entries()],{validate:op})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Pi([...h.entries()],{validate:sp,map:ip})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=je(o.id.publicKey):e.publicKey!=null?f=je(e.publicKey):r.publicKey!=null&&(f=je(r.publicKey));let u={addresses:await np(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:l};return u.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Y(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete u.publicKey,u}function Pi(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function op(r,e){if(typeof r!="string")throw new I("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new I("Metadata value must be a Uint8Array")}function sp(r,e){if(typeof r!="string")throw new I("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new I("Tag value must be an integer");if(e.value<0||e.value>100)throw new I("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new I("Tag ttl must be an integer");if(e.ttl<0)throw new I("Tag ttl must be between greater than 0")}}function ip(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function ap(r){let e=r.toString().split("/")[2],t=ue.parse(e,We);return ho(t)}function lu(r,e,t){let n=ap(r);return Zh(n,e,t)}function vb(r,e){return{prefix:cu,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(lu(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(lu(n.key,n.value,e),lu(o.key,o.value,e)))}}var Di=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=tu({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:au({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Lo(e),t)}async load(e,t){let n=Lo(e),o=await this.datastore.get(n,t),s=Ot.decode(o);if(this.#t(e,s))throw await this.datastore.delete(n,t),new tr;return _n(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Li(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#n(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await Li(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#n(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await Li(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#n(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(vb(e??{},this.maxAddressAge),e)){let o=ap(t);if(o.equals(this.peerId))continue;let s=Ot.decode(n);if(this.#t(o,s)){await this.datastore.delete(t,e);continue}yield _n(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Lo(e),o=await this.datastore.get(n,t),s=Ot.decode(o);if(this.#t(e,s))throw await this.datastore.delete(n,t),new tr;return{peerPB:s,peer:_n(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#n(e,t,n,o){t.updated=Date.now();let s=Ot.encode(t);return await this.datastore.put(Lo(e),s,o),{peer:_n(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!Qh(t,n.peerPB)}}#t(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var uu=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Di(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Io(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Ft(t)?t:Ft(t?.expectedPeer)?t.expectedPeer:void 0,s=Ft(t)||t===void 0?n:t,i=await Sn.openAndCertify(e,Ar.DOMAIN,s),a=ho(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Ar.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(f){if(f.name!=="NotFoundError")throw f}if(l?.peerRecordEnvelope!=null){let f=Sn.createFromProtobuf(l.peerRecordEnvelope),u=Ar.createFromProtobuf(f.payload);if(u.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(f=>({isCertified:!0,multiaddr:f}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function cp(r,e={}){return new uu(r,e)}var Ri=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Sb(r){return r[Symbol.asyncIterator]!=null}function _b(r){if(Sb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var fu=_b;function Ab(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var lp=Ab;function Cb(r){return r[Symbol.asyncIterator]!=null}function Ib(r,e){let t=0;if(Cb(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=lp(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Tr=Ib;function Tb(r){return r[Symbol.asyncIterator]!=null}function Pb(r,e){return Tb(r)?(async function*(){yield*(await Io(r)).sort(e)})():(function*(){yield*Io(r).sort(e)})()}var du=Pb;function Lb(r){return r[Symbol.asyncIterator]!=null}function Db(r,e){return Lb(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var hu=Db;var ki=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await fu(this.putMany(e,n)),e=[],await fu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Tr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Tr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>du(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Tr(n,()=>o++>=s)}return e.limit!=null&&(n=hu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Tr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Tr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>du(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Tr(n,()=>s++>=o)}return e.limit!=null&&(n=hu(n,e.limit)),n}};var Oi=class extends ki{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Ri;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Ir(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Ir(n),t?.signal?.throwIfAborted()}};var te=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),M=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),up=r=>({match:e=>r.match(e)===!1?e:!1}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Ie=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),X=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function re(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Rb=M(421),fp=re(Rb),Mi=M(54),Bi=M(55),Fi=M(56),mu=M(53),fT=re(Mi,H(M(421))),dT=re(Bi,H(M(421))),hT=re(Fi,H(M(421))),pT=re(Ie(mu,Fi,Mi,Bi),H(M(421))),dp=X(M(4),H(M(43))),hp=X(H(M(42)),M(41),H(M(43))),gu=Ie(dp,hp),Pr=Ie(gu,mu,Mi,Bi,Fi),mT=re(Ie(gu,X(Ie(mu,Fi,Mi,Bi),H(M(421))))),yu=re(dp),bu=re(hp),gT=re(gu),wu=X(Pr,M(6)),Do=X(Pr,M(273)),Ro=re(X(wu,H(M(421)))),yT=re(Do),xu=X(Do,te(460),H(M(421))),Ui=X(Do,te(461),H(M(421))),kb=Ie(xu,Ui),bT=re(xu),pp=re(Ui),pu=Ie(Pr,wu,Do,xu,Ui),mp=Ie(X(pu,te(477),H(M(421)))),Lr=re(mp),gp=Ie(X(pu,te(478),H(M(421))),X(pu,te(448),H(M(449)),te(477),H(M(421)))),ko=re(gp),yp=X(Do,te(280),H(M(466)),H(M(466)),H(M(421))),Eu=re(yp),bp=X(Ui,te(465),H(M(466)),H(M(466)),H(M(421))),vu=re(bp),Ni=Ie(mp,gp,X(wu,H(M(421))),X(kb,H(M(421))),X(Pr,H(M(421))),yp,bp,M(421)),wT=re(Ni),Ob=X(H(Ni),te(290),up(te(281)),H(M(421))),Dr=re(Ob),Nb=Ie(X(Ni,te(290),te(281),H(M(421))),X(Ni,te(281),H(M(421))),X(te(281),H(M(421)))),Su=re(Nb),Mb=Ie(X(Pr,M(6),te(480),H(M(421))),X(Pr,te(480),H(M(421)))),xT=re(Mb),Bb=X(Pr,Ie(X(M(6,"443"),te(480)),X(M(6),te(443)),X(M(6),te(448),te(480)),X(te(448),te(480)),te(448),te(443)),H(M(421))),ET=re(Bb),Fb=Ie(X(M(777),H(M(421)))),vT=re(Fb),Ub=Ie(X(M(400),H(M(421)))),ST=re(Ub);var wp=864e13;var Ki=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ce({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=z(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=un(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?wp-Date.now():0,lastVerified:o?wp-Date.now():void 0})})}remove(e){let t=z(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!xe(o))continue;let s=z(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),j(n)}confirm(e,t){let n=z(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=z(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var qi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ce({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=z(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:it(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=z(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!xe(n))continue;let o=z(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,j(i)):e}confirm(e,t){if(!xe(e))return!1;let n=z(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!xe(e))return!1;let n=z(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var Kb={maxObservedAddresses:10},Vi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Kb.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Pt(e)||wh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:j(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var qb={maxObservedAddresses:10},$i=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??qb.maxObservedAddresses}get(e,t){if(Pt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!xe(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!xe(e))return e.toString();let t=z(e);return`${t.host}-${t.port}-${t.protocol}`}};var xp=6e4,Ep={maxObservedAddresses:10,addressVerificationTTL:xp*10,addressVerificationRetry:xp*5},Vb=r=>r;function _u(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&ft(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var zi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Vi(e,t),this.dnsMappings=new Ki(e,t),this.ipMappings=new qi(e,t),this.transportAddresses=new $i(e,t),this.announceFilter=t.announceFilter??Vb,this.observedAddressFilter=go(1024),this.addressVerificationTTL=t.addressVerificationTTL??Ep.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Ep.addressVerificationRetry,this._updatePeerStoreAddresses=vo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>j(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=z(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=_u(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=_u(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=_u(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=j(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(j(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${it(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(j(`/ip${it(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!xe(e))return!1;let t=z(e);if(t.type!=="ip4"||un(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Lr.exactMatch(s)||ko.exactMatch(s),s=>Ro.exactMatch(s),s=>pp.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(f=>z(f).type==="ip4"&&s(f)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!bo(l)).pop();if(a==null)continue;let c=z(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var vp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(vp||(vp={}));var Hi=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Gi=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},An=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Oo=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Wi=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ji=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Xi=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},No=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Yi=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Zi=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Qi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ji=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},ea=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Jt=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Rr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ta=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},ra=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Au=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Ps())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>es(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},$b=["metrics","connectionProtector","dns"],zb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Sp(r={}){let e=new Au(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!zb.includes(o)){let i=e.components[o];if(i==null&&!$b.includes(o))throw new Hi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function _p(r){let e={};for(let t of Object.values(r.components))for(let n of Hb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Gb(t))if(e[n]!==!0)throw new Gi(`Service "${Wb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Hb(r){return Array.isArray(r?.[Dn])?r[Dn]:[]}function Gb(r){return Array.isArray(r?.[Da])?r[Da]:[]}function Wb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Ap(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Lr.matches(e)?!0:Pt(e)),r}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function na(r){if(Ft(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:ft(n),e.forEach(o=>{if(!Qt(o))throw new Mt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new I("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ft(s);if(t?.equals(i)!==!0)throw new I("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!fp.exactMatch(n)),{peerId:t,multiaddrs:e}}var jb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Cp(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??jb;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Mo(r){let e=z(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new I(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new I(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new ln(e.host,t)}function Cu(r){return!Dr.exactMatch(r)}function oa(r,e,t){if(r==null||e==null)return;let n=e.sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Cu(s)))return n}var sa=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Mo(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Ze;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let f=await this.peerStore.get(l);o.set(l,[...f.tags.values()].reduce((u,d)=>u+d.value,0))}catch(f){f.name!=="NotFoundError"&&this.log.error("error loading peer tags",f)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(f=>{if(xe(c.remoteAddr)){let u=z(c.remoteAddr);return f.contains(u.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Cp(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Ip="last-dial-failure",Tp="last-dial-success";var Pp=100,ia=50;function Xb(r,e){let t=Ro.exactMatch(r.multiaddr),n=Ro.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=ko.exactMatch(r.multiaddr),s=ko.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Lr.exactMatch(r.multiaddr),a=Lr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Su.exactMatch(r.multiaddr),l=Su.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let f=Eu.exactMatch(r.multiaddr),u=Eu.exactMatch(e.multiaddr);if(f&&!u)return-1;if(!f&&u)return 1;let d=vu.exactMatch(r.multiaddr),h=vu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function Yb(r,e){let t=bo(r.multiaddr),n=bo(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Zb(r,e){let t=Pt(r.multiaddr),n=Pt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Qb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Jb(r,e){let t=Dr.exactMatch(r.multiaddr),n=Dr.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Lp(r){return r.sort(Xb).sort(Qb).sort(Jb).sort(Zb).sort(Yb)}var Tu=Ca(Rp(),1);function Pu(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Fo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Pu(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Uo=class extends Tu.default{#e;#n;#t=0;#h;#a;#p=0;#o;#c;#r;#m;#s=0;#l;#i;#g;#w=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Fo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#n=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#n||this.#t<this.#h}get#E(){return this.#s<this.#l}#v(){this.#s--,this.#u(),this.emit("next")}#S(){this.#b(),this.#y(),this.#c=void 0}get#_(){let e=Date.now();if(this.#o===void 0){let t=this.#p-e;if(t<0)this.#t=this.#e?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#S()},t)),!0}return!1}#u(){if(this.#r.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#x&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#n||this.#o!==void 0||(this.#o=setInterval(()=>{this.#b()},this.#a),this.#p=Date.now()+this.#a)}#b(){this.#t===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#t=this.#e?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#r.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#w++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#s++;try{t.signal?.throwIfAborted(),this.#t++;let s=e({signal:t.signal});t.timeout&&(s=Eo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof xo&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},t),this.emit("add"),this.#u()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function ca(r){let e=[Ge.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Lu=60;function la(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Ge[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ge[e.type],TTL:e.TTL??e.ttl??Lu,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var rw=4;function Du(r,e={}){let t=new Uo({concurrency:e.queryConcurrency??rw});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ca(o.types).forEach(a=>{s.append("type",Ge[a])}),o.onProgress?.(new de("dns:query",n));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=la(await a.json());return o.onProgress?.(new de("dns:response",c)),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function kp(){return[Du("https://cloudflare-dns.com/dns-query"),Du("https://dns.google/resolve")]}var Mp=Ca(Np(),1);var Ru=class{lru;constructor(e){this.lru=(0,Mp.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return la({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ge[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Lu)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Bp(r){return new Ru(r)}var nw=1e3,ua=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Bp(e.cacheSize??nw),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=kp())}async query(e,t={}){let n=ca(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new de("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Ge;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ge||(Ge={}));function Fp(r={}){return new ua(r)}var ku=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Ge.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(j(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Fp()),this.dns)}},kr=new ku;async function Ou(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new ra("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Ou(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Ko={maxParallelDials:ia,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:kr}},fa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Ko.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Ko.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Ko.dialTimeout,this.connections=t.connections??new Ze,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Ko.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new si({concurrency:t.maxParallelDials??Ko.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Qe.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=na(e);if(n!=null&&t.force!==!0){let i=oa(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new de("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Mr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new de("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new de("dial-queue:start-dial"));let a=Dt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Fu,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let f=[],u=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...u]);let d=await this.calculateMultiaddrs(n,u,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}f.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,f.map(h=>h.multiaddr.toString())),e?.onProgress?.(new de("dial-queue:calculated-addresses",f));for(let h of f){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Mr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Tp]:T(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Ip]:T(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}if(t.aborted)throw new Xo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Mr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new No("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(u){if(u.name!=="NotFoundError")throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...u.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(u){u.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,u)}}}let s=(await Promise.all(o.map(async u=>{let d=await Ou(u.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(u.multiaddr)?u:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(u),isCertified:d.isCertified}:d)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let d=u.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let u of i){let d=u.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(d,u)}let c=[...a.values()];if(c.length===0)throw new Qi("The dial request has no valid addresses");let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let f=this.addressSorter==null?Lp(l):l.sort(this.addressSorter);if(f.length===0)throw new No("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:u})=>u.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Dr.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ow=Object.prototype.toString,sw=r=>ow.call(r)==="[object Error]",iw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Uu(r){if(!(r&&sw(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:iw.has(t)}function aw(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function da(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Ku=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},cw=(r,e,t)=>{let n=t.retries-(e-1);return Object.freeze({error:r,attemptNumber:e,retriesLeft:n})};function lw(r,e){let t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*e.factor**(r-1));return n=Math.min(n,e.maxTimeout),n}async function uw(r,e,t,n,o){let s=r;if(s instanceof Error||(s=new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`)),s instanceof Ku)throw s.originalError;if(s instanceof TypeError&&!Uu(s))throw s;let i=cw(s,e,t);await t.onFailedAttempt(i);let a=Date.now();if(a-n>=o||e>=t.retries+1||!await t.shouldRetry(i))throw s;let c=lw(e,t),l=o-(a-n);if(l<=0)throw s;let f=Math.min(c,l);f>0&&await new Promise((u,d)=>{let h=()=>{clearTimeout(p),t.signal?.removeEventListener("abort",h),d(t.signal.reason)},p=setTimeout(()=>{t.signal?.removeEventListener("abort",h),u()},f);t.unref&&p.unref?.(),t.signal?.addEventListener("abort",h,{once:!0})}),t.signal?.throwIfAborted()}async function qu(r,e={}){if(e={...e},aw(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,da("factor",e.factor,{min:0,allowInfinity:!1}),da("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),da("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0});let t=e.maxRetryTime??Number.POSITIVE_INFINITY;da("maxRetryTime",t,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,o=Date.now(),s=t;for(;n<e.retries+1;){n++;try{e.signal?.throwIfAborted();let i=await r(n);return e.signal?.throwIfAborted(),i}catch(i){await uw(i,n,e,o,s)}}throw new Error("Retry attempts exhausted without throwing an error.")}var ha=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new oi({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);Up(t)&&(this.queue.has(e)||this.queue.add(async n=>{await qu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(La)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>Up(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function Up(r){for(let e of r.tags.keys())if(e.startsWith(La))return!0;return!1}var Fu=50,Vu={maxConnections:Pp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},pa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Vu.maxConnections,this.maxConnections<1)throw new I("Connection Manager maxConnections must be greater than 0");this.connections=new Ze,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Mo(j(n))),this.deny=(t.deny??[]).map(n=>Mo(j(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Vu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ii({points:t.inboundConnectionThreshold??Vu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new sa({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>j(n))}),this.dialQueue=new fa(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ia,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections}),this.reconnectQueue=new ha({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Qu(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Ju(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([at(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new I("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new ht("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=na(e);if(this.peerId.equals(n))throw new Nr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=oa(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Fu});if(s.status!=="open")throw new er("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Mt("Duplicate multiaddr connection")),c;return a||i.push(s),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([at(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(xe(e.remoteAddr)){let s=z(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(xe(e.remoteAddr)){let s=z(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(xe(e.remoteAddr)){let o=z(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var hw=1e4,pw="1.0.0",mw="ping",gw="ipfs",Kp=32,yw=!0,ma=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??gw}/${mw}/${pw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??hw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??yw,this.timeout=new qs({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Dn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Xl(o);t=Date.now(),await Promise.all([s.write(en(Kp),{signal:n}),s.read({bytes:Kp,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var ga=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:K(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:K(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new An("No content routers available");let n=this,o=new mr;for await(let s of En(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new An("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new An("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new ht;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new ht;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var ya=globalThis.CustomEvent??Event;async function*$u(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ye(),a=ye(),c=!1,l,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ye(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new ya("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new ya("task-complete"))})}c=!0,o.dispatchEvent(new ya("task-complete"))}catch(p){l=p,o.dispatchEvent(new ya("task-complete"))}});function u(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;u();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(u()||(a=ye(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var ba=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:K(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Oo("No peer routers available");if(e.toString()===this.peerId.toString())throw new Wi("Should not try to find self");let n=this,o=En(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new tr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Oo("No peer routers available");let n=this,o=go(1024);for await(let s of $u((async function*(){let i=En(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var wa=class extends Pe{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Dt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ye(),yield(await at(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Dt([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=en(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Lt(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var zu=32,Hu=64,xa=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Ce({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new ji(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new Xi(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:zu,maxOutboundStreams:Hu,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new I("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Ea=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Ce({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ce({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ln.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new I("Transport must have a valid tag");if(this.transports.has(t))throw new I(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ta(`No transport available for address ${String(e)}`);return t?.onProgress?.(new de("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new ht("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new Yi)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(s)??[];f==null&&(f=[],this.listeners.set(s,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let u=f.findIndex(d=>d===l);f.splice(u,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),yu.matches(c)?t.ipv4.attempts++:bu.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),yu.matches(c)&&t.ipv4.success++,bu.matches(c)&&t.ipv6.success++},u=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,u),t.errors.set(c.toString(),u),u}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Ln.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Zi(`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:
|
|
3
4
|
${[...t.errors.entries()].map(([s,i])=>`
|
|
4
|
-
${s}: ${`${
|
|
5
|
+
${s}: ${`${bw(i)}`.split(`
|
|
5
6
|
`).join(`
|
|
6
7
|
`)}
|
|
7
|
-
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function
|
|
8
|
-
`);async function
|
|
9
|
-
`),l=
|
|
10
|
-
`);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await
|
|
11
|
-
`),t);if(n.trace("reading protocol response"),a=await
|
|
12
|
-
`),t),n.trace('responded with "%s" for "%s"',
|
|
13
|
-
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new
|
|
14
|
-
`))),
|
|
15
|
-
`));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(
|
|
16
|
-
`),t),n('responded with "na" for "%s"',s)}}var af=class extends Ie{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Gu(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new ss(n.local,n.error))})}[Symbol.toStringTag]="Connection";[ff]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new rr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new nr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new nr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Mn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let i=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:i}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Rn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=ex(n.protocol,this.components.registrar,t),s=im(n.protocol,"outbound",this);if(s>o){let i=new os(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(i),i}return await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n),n}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let c=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",c),t.protocol=await kn(t,c,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Jw(t.protocol,this.components.registrar);if(im(t.protocol,"inbound",this)>o)throw new ns(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Mn("Cannot open protocol stream on limited connection");await i(t,this)}catch(o){t.abort(o)}}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function am(r,e){return new af(r,e)}function Jw(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return nf}function ex(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??of}function im(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Da=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=_e({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=_e({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new da(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=kt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ha("Connection denied");await Rt(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ht(n),await Rt(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(tx(n)){if(n.remotePeer==null)throw new Ut(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getPeerId(),d;f!=null&&(d=ht(f)),n?.onProgress?.(new fe(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new qr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new fe(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=am(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await kn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Fr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Fr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Rn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Fr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Fr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Rn(e,o,n),i=t.get(s);if(i==null)throw new rr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection",s),new rr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await kn(e,o,n),i=t.get(s);if(i==null)throw new rr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function tx(r){return r.skipEncryption===!0}var Oa="2.10.0-a02cb0461",Ra="js-libp2p";function lm(r,e){return`${r??Ra}/${e??Oa} browser/${globalThis.navigator.userAgent}`}var Xo=class extends Ie{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Ie,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??fi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Ra,s=e.nodeInfo?.version??Oa,i=this.components=Wp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??lm(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Wi,connectionGater:Xp(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Rp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Da(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new La(this.components,e.transportManager)),this.configureComponent("connectionManager",new Sa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new _a(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Pa(this.components)),this.configureComponent("addressManager",new na(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ia(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Aa(this.components,{routers:c})),this.configureComponent("randomWalk",new Ta(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[Ma]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ma])),f[Ua]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ua])),f[Ba]!=null&&(this.log("registering service %s for peer discovery",l),f[Ba].addEventListener?.("peer",d=>{this.#e(d)}))}jp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Dr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new O("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new O("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){er(e)&&(e=ht(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=tt([C("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=fn(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function rx(r={}){r.privateKey??=await ph("Ed25519");let e=new Xo({...await up(r),peerId:bh(r.privateKey)});return r.start!==!1&&await e.start(),e}var nx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function ox(r){return r==null?!1:r instanceof Xo?!0:nx.every(e=>typeof r[e]=="function")}return mm(sx);})();
|
|
8
|
+
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function bw(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var dt="/multistream/1.0.0";var ww=T(`
|
|
9
|
+
`);async function qo(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==ww[0])throw new jo("Missing newline");return K(n).trimEnd()}async function Cn(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=Zs(r,{...t,maxDataLength:1024});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',dt,i);let c=T(`${dt}
|
|
10
|
+
`),l=T(`${i}
|
|
11
|
+
`);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await qo(o,t),n.trace('read "%s"',a),a!==dt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(T(`${i}
|
|
12
|
+
`),t);if(n.trace("reading protocol response"),a=await qo(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Wo(`Protocol selection failed - could not negotiate ${e}`)}async function In(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=Zs(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await qo(o,t);if(n.trace('read "%s"',s),s===dt){n.trace('respond with "%s" for "%s"',dt,s),await o.write(T(`${dt}
|
|
13
|
+
`),t),n.trace('responded with "%s" for "%s"',dt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(T(`${s}
|
|
14
|
+
`),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Z(...e.map(a=>ni.single(T(`${a}
|
|
15
|
+
`))),T(`
|
|
16
|
+
`));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(T(`na
|
|
17
|
+
`),t),n('responded with "na" for "%s"',s)}}var Wu=class extends Pe{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Cu(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Qo(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Zu]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Jt("Connection is not multiplexed");if(this.muxer.status!=="open")throw new er(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new er(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Pn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Cn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=vw(n.protocol,this.components.registrar,t),s=zp(n.protocol,"outbound",this);if(s>o){let a=new Zo(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await In(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Ew(t.protocol,this.components.registrar);if(zp(t.protocol,"inbound",this)>o)throw new Yo(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Pn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,f,u)=>{await i(l,f),u(l,f)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,f)=>{e=l,t=f,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Hp(r,e){return new Wu(r,e)}function Ew(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return zu}function vw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Hu}function zp(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var va=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ce({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ce({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Ji(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Dt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new ea("Connection denied");await Lt(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=ft(n),await Lt(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),o=await u.protect(o,n))}try{if(Sw(n)){if(n.remotePeer==null)throw new Mt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let u=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;u!=null&&(d=ft(u)),n?.onProgress?.(new de(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let u=new Nr("Can not dial self");throw e.abort(u),u}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new de(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(u){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,u),u}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let f=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return f.log("successfully upgraded connection"),f}_createConnection(e){let t=Hp(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await In(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Rr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Rr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Cn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Rr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Rr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Cn(e,o,n),i=t.get(s);if(i==null)throw new Jt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection",s),new Jt(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await In(e,o,n),i=t.get(s);if(i==null)throw new Jt(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Sw(r){return r.skipEncryption===!0}var Sa="2.10.0-e8398d97e",_a="js-libp2p";function Wp(r,e){return`${r??_a}/${e??Sa} browser/${globalThis.navigator.userAgent}`}var Vo=class extends Pe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Pe,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let f=n(l),u=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return f||u},this.peerId=e.peerId,this.logger=e.logger??Ps(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??_a,s=e.nodeInfo?.version??Sa,i=this.components=Sp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Wp(o,s)},logger:this.logger,events:t,datastore:e.datastore??new Oi,connectionGater:Ap(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",cp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let f={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new va(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,f)=>this.configureComponent(`connection-encryption-${f}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,f)=>this.configureComponent(`stream-muxers-${f}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ea(this.components,e.transportManager)),this.configureComponent("connectionManager",new pa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ma(this.components,e.connectionMonitor)),this.configureComponent("registrar",new xa(this.components)),this.configureComponent("addressManager",new zi(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,f)=>this.configureComponent(`peer-router-${f}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new ba(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,f)=>this.configureComponent(`content-router-${f}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ga(this.components,{routers:c})),this.configureComponent("randomWalk",new wa(this.components)),(e.peerDiscovery??[]).forEach((l,f)=>{this.configureComponent(`peer-discovery-${f}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let f=e.services[l],u=f(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=u,this.configureComponent(l,u),u[Ia]!=null&&(this.log("registering service %s for content routing",l),c.push(u[Ia])),u[Pa]!=null&&(this.log("registering service %s for peer routing",l),a.push(u[Pa])),u[Ta]!=null&&(this.log("registering service %s for peer discovery",l),u[Ta].addEventListener?.("peer",d=>{this.#e(d)}))}_p(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new mr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new I("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new I("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Qt(e)&&(e=ft(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=et([T("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=on(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function _w(r={}){r.privateKey??=await th("Ed25519");let e=new Vo({...await ih(r),peerId:sh(r.privateKey)});return r.start!==!1&&await e.start(),e}var Aw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Cw(r){return r==null?!1:r instanceof Vo?!0:Aw.every(e=>typeof r[e]=="function")}return Jp(Iw);})();
|
|
17
18
|
/*! Bundled license information:
|
|
18
19
|
|
|
19
20
|
@noble/hashes/esm/utils.js:
|