libp2p 2.8.2-b2124c2db → 2.8.2-da4e9da82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +15 -15
- package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
- package/dist/src/connection-manager/dial-queue.js +3 -2
- package/dist/src/connection-manager/dial-queue.js.map +1 -1
- package/dist/src/get-peer.d.ts +2 -1
- package/dist/src/get-peer.d.ts.map +1 -1
- package/dist/src/get-peer.js +13 -8
- package/dist/src/get-peer.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +11 -11
- package/src/connection-manager/dial-queue.ts +3 -2
- package/src/get-peer.ts +14 -8
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
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 zh=Object.create;var ho=Object.defineProperty;var Vh=Object.getOwnPropertyDescriptor;var $h=Object.getOwnPropertyNames;var Hh=Object.getPrototypeOf,Gh=Object.prototype.hasOwnProperty;var Ae=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Lt=(r,t)=>{for(var e in t)ho(r,e,{get:t[e],enumerable:!0})},jl=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $h(t))!Gh.call(r,o)&&o!==e&&ho(r,o,{get:()=>t[o],enumerable:!(n=Vh(t,o))||n.enumerable});return r};var ln=(r,t,e)=>(e=r!=null?zh(Hh(r)):{},jl(t||!r||!r.__esModule?ho(e,"default",{value:r,enumerable:!0}):e,r)),Wh=r=>jl(ho({},"__esModule",{value:!0}),r);var Bf=Ae((_v,dc)=>{"use strict";var Kg=Object.prototype.hasOwnProperty,Mt="~";function Un(){}Object.create&&(Un.prototype=Object.create(null),new Un().__proto__||(Mt=!1));function qg(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Mf(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new qg(e,n||r,o),i=Mt?Mt+t:t;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 jo(r,t){--r._eventsCount===0?r._events=new Un:delete r._events[t]}function Ct(){this._events=new Un,this._eventsCount=0}Ct.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Kg.call(e,n)&&t.push(Mt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ct.prototype.listeners=function(t){var e=Mt?Mt+t:t,n=this._events[e];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};Ct.prototype.listenerCount=function(t){var e=Mt?Mt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Ct.prototype.emit=function(t,e,n,o,s,i){var a=Mt?Mt+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,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,m;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,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,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!u)for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c[f].fn.apply(c[f].context,u)}}return!0};Ct.prototype.on=function(t,e,n){return Mf(this,t,e,n,!1)};Ct.prototype.once=function(t,e,n){return Mf(this,t,e,n,!0)};Ct.prototype.removeListener=function(t,e,n,o){var s=Mt?Mt+t:t;if(!this._events[s])return this;if(!e)return jo(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&jo(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:jo(this,s)}return this};Ct.prototype.removeAllListeners=function(t){var e;return t?(e=Mt?Mt+t:t,this._events[e]&&jo(this,e)):(this._events=new Un,this._eventsCount=0),this};Ct.prototype.off=Ct.prototype.removeListener;Ct.prototype.addListener=Ct.prototype.on;Ct.prefixed=Mt;Ct.EventEmitter=Ct;typeof dc<"u"&&(dc.exports=Ct)});var qf=Ae((Xv,Kf)=>{Kf.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var sd=Ae((vS,od)=>{"use strict";od.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var fd=Ae((ld,ud)=>{"use strict";var as=sd(),{hasOwnProperty:ad}=Object.prototype,{propertyIsEnumerable:d0}=Object,Zr=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),h0=ld,id={concatArrays:!1,ignoreUndefined:!1},cs=r=>{let t=[];for(let e in r)ad.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)d0.call(r,n)&&t.push(n)}return t};function jr(r){return Array.isArray(r)?p0(r):as(r)?m0(r):r}function p0(r){let t=r.slice(0,0);return cs(r).forEach(e=>{Zr(t,e,jr(r[e]))}),t}function m0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return cs(r).forEach(e=>{Zr(t,e,jr(r[e]))}),t}var cd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Zr(r,o,Bc(r[o],t[o],n)):Zr(r,o,jr(t[o])))}),r),g0=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)ad.call(s,a)&&(i.push(String(a)),s===r?Zr(n,o++,s[a]):Zr(n,o++,jr(s[a])));n=cd(n,s,cs(s).filter(a=>!i.includes(a)),e)}),n};function Bc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?g0(r,t,e):!as(t)||!as(r)?jr(t):cd(r,t,cs(t),e)}ud.exports=function(...r){let t=Bc(jr(id),this!==h0&&this||{},id),e={_:{}};for(let n of r)if(n!==void 0){if(!as(n))throw new TypeError("`"+n+"` is not an Option Object");e=Bc(e,{_:n},t)}return e._}});var Kd=Ae(Yn=>{(function(){var r,t,e,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,m,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=t(c),m=p[0],u=p[1],c=c.substring(u),l.push(m)}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")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var l,u,f,d,m;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")),m=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===m)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,m,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(g){throw f=g,new Error("Invalid mask: "+u)}for(d=m=32;m>=0;d=--m)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(g){throw f=g,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}(),Yn.ip2long=i,Yn.long2ip=a,Yn.Netmask=r}).call(Yn)});var hh=Ae((UI,dh)=>{function Gt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}dh.exports=Gt;Gt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Gt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Gt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Gt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Gt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Gt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Gt.prototype.start=Gt.prototype.try;Gt.prototype.errors=function(){return this._errors};Gt.prototype.attempts=function(){return this._attempts};Gt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var ph=Ae(br=>{var tw=hh();br.operation=function(r){var t=br.timeouts(r);return new tw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};br.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};br.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};br.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var l=br.operation(t),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[s].options=t}}});var gh=Ae((qI,mh)=>{mh.exports=ph()});var Pw={};Lt(Pw,{createLibp2p:()=>Tw});var Yl=Symbol.for("@libp2p/connection");var Oi=Symbol.for("@libp2p/content-routing");var Fi=Symbol.for("@libp2p/peer-discovery");var po=Symbol.for("@libp2p/peer-id");function mo(r){return!!r?.[po]}var Ui=Symbol.for("@libp2p/peer-routing");var Ki="keep-alive";var Ow=Symbol.for("@libp2p/transport");var $e;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})($e||($e={}));var Wt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Er=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},un=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var go=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Sr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var He=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Ar=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},_e=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},yo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},wo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},fn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},bo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var xo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},le=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var _r=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Ir=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},vo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Eo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Ie=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var ue=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function So(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ql(...r){let t=[];for(let e of r)So(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Jl(...r){let t=[];for(let e of r)So(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var dn=Symbol.for("@libp2p/service-capabilities"),qi=Symbol.for("@libp2p/service-dependencies");var Gi={};Lt(Gi,{base58btc:()=>G,base58flickr:()=>Jh});var ub=new Uint8Array(0);function tu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function fe(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 eu(r){return new TextEncoder().encode(r)}function ru(r){return new TextDecoder().decode(r)}function Xh(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[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 g=0,h=0,w=0,x=p.length;w!==x&&p[w]===0;)w++,g++;for(var y=(x-w)*u+1>>>0,E=new Uint8Array(y);w!==x;){for(var _=p[w],L=0,I=y-1;(_!==0||L<h)&&I!==-1;I--,L++)_+=256*E[I]>>>0,E[I]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=L,w++}for(var P=y-h;P!==y&&E[P]===0;)P++;for(var T=c.repeat(g);P<y;++P)T+=r.charAt(E[P]);return T}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var h=0,w=0;p[g]===c;)h++,g++;for(var x=(p.length-g)*l+1>>>0,y=new Uint8Array(x);p[g];){var E=e[p.charCodeAt(g)];if(E===255)return;for(var _=0,L=x-1;(E!==0||_<w)&&L!==-1;L--,_++)E+=a*y[L]>>>0,y[L]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=_,g++}if(p[g]!==" "){for(var I=x-w;I!==x&&y[I]===0;)I++;for(var P=new Uint8Array(h+(x-I)),T=h;I!==x;)P[T++]=y[I++];return P}}}function m(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var Zh=Xh,jh=Zh,ou=jh;var zi=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Vi=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return su(this,t)}},$i=class{decoders;constructor(t){this.decoders=t}or(t){return su(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function su(r,t){return new $i({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Hi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new zi(t,e,n),this.decoder=new Vi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Cr({name:r,prefix:t,encode:e,decode:n}){return new Hi(r,t,e,n)}function Ce({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ou(e,r);return Cr({prefix:t,name:r,encode:n,decode:s=>fe(o(s))})}function Yh(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function Qh(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function ct({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Cr({prefix:t,name:r,encode(o){return Qh(o,n,e)},decode(o){return Yh(o,n,e,r)}})}var G=Ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jh=Ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wi={};Lt(Wi,{base32:()=>Kt,base32hex:()=>np,base32hexpad:()=>sp,base32hexpadupper:()=>ip,base32hexupper:()=>op,base32pad:()=>ep,base32padupper:()=>rp,base32upper:()=>tp,base32z:()=>ap});var Kt=ct({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tp=ct({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ep=ct({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rp=ct({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),np=ct({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),op=ct({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sp=ct({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ip=ct({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ap=ct({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xi={};Lt(Xi,{base36:()=>hn,base36upper:()=>cp});var hn=Ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cp=Ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var lp=cu,iu=128,up=127,fp=~up,dp=Math.pow(2,31);function cu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=dp;)t[e++]=r&255|iu,r/=128;for(;r&fp;)t[e++]=r&255|iu,r>>>=7;return t[e]=r|0,cu.bytes=e-n+1,t}var hp=Zi,pp=128,au=127;function Zi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Zi.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&au)<<o:(i&au)*Math.pow(2,o),o+=7}while(i>=pp);return Zi.bytes=s-n,e}var mp=Math.pow(2,7),gp=Math.pow(2,14),yp=Math.pow(2,21),wp=Math.pow(2,28),bp=Math.pow(2,35),xp=Math.pow(2,42),vp=Math.pow(2,49),Ep=Math.pow(2,56),Sp=Math.pow(2,63),Ap=function(r){return r<mp?1:r<gp?2:r<yp?3:r<wp?4:r<bp?5:r<xp?6:r<vp?7:r<Ep?8:r<Sp?9:10},_p={encode:lp,decode:hp,encodingLength:Ap},Ip=_p,pn=Ip;function mn(r,t=0){return[pn.decode(r,t),pn.decode.bytes]}function Tr(r,t,e=0){return pn.encode(r,t,e),t}function Pr(r){return pn.encodingLength(r)}function Xt(r,t){let e=t.byteLength,n=Pr(r),o=n+Pr(e),s=new Uint8Array(o+e);return Tr(r,s,0),Tr(e,s,n),s.set(t,o),new Lr(r,e,t,s)}function qt(r){let t=fe(r),[e,n]=mn(t),[o,s]=mn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Lr(e,o,i,t)}function lu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&tu(r.bytes,e.bytes)}}var Lr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function uu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Tp(e,ji(r),t??G.encoder);default:return Pp(e,ji(r),t??Kt.encoder)}}var fu=new WeakMap;function ji(r){let t=fu.get(r);if(t==null){let e=new Map;return fu.set(r,e),e}return t}var ut=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==gn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Lp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Xt(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&lu(t.multihash,n.multihash)}toString(t){return uu(this,t)}toJSON(){return{"/":uu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??du(n,o,s.bytes))}else if(e[Dp]===!0){let{version:n,multihash:o,code:s}=e,i=qt(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==gn)throw new Error(`Version 0 CID must use dag-pb (code: ${gn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=du(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,gn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=fe(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Lr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=mn(t.subarray(e));return e+=d,f},o=n(),s=gn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Cp(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ji(s).set(n,t),s}};function Cp(r,t){switch(r[0]){case"Q":{let e=t??G;return[G.prefix,e.decode(`${G.prefix}${r}`)]}case G.prefix:{let e=t??G;return[G.prefix,e.decode(r)]}case Kt.prefix:{let e=t??Kt;return[Kt.prefix,e.decode(r)]}case hn.prefix:{let e=t??hn;return[hn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Tp(r,t,e){let{prefix:n}=e;if(n!==G.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Pp(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var gn=112,Lp=18;function du(r,t,e){let n=Pr(r),o=n+Pr(t),s=new Uint8Array(o+e.byteLength);return Tr(r,s,0),Tr(t,s,n),s.set(e,o),s}var Dp=Symbol.for("@ipld/js-cid/CID");var Yi={};Lt(Yi,{identity:()=>de});var hu=0,kp="identity",pu=fe;function Rp(r){return Xt(hu,pu(r))}var de={code:hu,name:kp,encode:pu,digest:Rp};function rt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function mu(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Np(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Dr(r,...t){if(!Np(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function gu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");mu(r.outputLen),mu(r.blockLen)}function kr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function yu(r,t){Dr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ge=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function _o(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Zt(r,t){return r<<32-t|r>>>t}function wu(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function yn(r){return typeof r=="string"&&(r=wu(r)),Dr(r),r}function Qi(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Dr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Rr=class{clone(){return this._cloneInto()}};function Io(r){let t=n=>r().update(yn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Nr(r=32){if(Ge&&typeof Ge.getRandomValues=="function")return Ge.getRandomValues(new Uint8Array(r));if(Ge&&typeof Ge.randomBytes=="function")return Ge.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Mp(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function bu(r,t,e){return r&t^~r&e}function xu(r,t,e){return r&t^r&e^t&e}var Mr=class extends Rr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=_o(this.buffer)}update(t){kr(this);let{view:e,buffer:n,blockLen:o}=this;t=yn(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=_o(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){kr(this),yu(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Mp(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=_o(t),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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Co=BigInt(4294967295),Ji=BigInt(32);function vu(r,t=!1){return t?{h:Number(r&Co),l:Number(r>>Ji&Co)}:{h:Number(r>>Ji&Co)|0,l:Number(r&Co)|0}}function Bp(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=vu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Op=(r,t)=>BigInt(r>>>0)<<Ji|BigInt(t>>>0),Fp=(r,t,e)=>r>>>e,Up=(r,t,e)=>r<<32-e|t>>>e,Kp=(r,t,e)=>r>>>e|t<<32-e,qp=(r,t,e)=>r<<32-e|t>>>e,zp=(r,t,e)=>r<<64-e|t>>>e-32,Vp=(r,t,e)=>r>>>e-32|t<<64-e,$p=(r,t)=>t,Hp=(r,t)=>r,Gp=(r,t,e)=>r<<e|t>>>32-e,Wp=(r,t,e)=>t<<e|r>>>32-e,Xp=(r,t,e)=>t<<e-32|r>>>64-e,Zp=(r,t,e)=>r<<e-32|t>>>64-e;function jp(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Yp=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Qp=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Jp=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),tm=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,em=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),rm=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var nm={fromBig:vu,split:Bp,toBig:Op,shrSH:Fp,shrSL:Up,rotrSH:Kp,rotrSL:qp,rotrBH:zp,rotrBL:Vp,rotr32H:$p,rotr32L:Hp,rotlSH:Gp,rotlSL:Wp,rotlBH:Xp,rotlBL:Zp,add:jp,add3L:Yp,add3H:Qp,add4L:Jp,add4H:tm,add5H:rm,add5L:em},F=nm;var[om,sm]=F.split(["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))),Te=new Uint32Array(80),Pe=new Uint32Array(80),ta=class extends Mr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:p,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,m,p,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,m,p,g,h){this.Ah=t|0,this.Al=e|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=m|0,this.Gl=p|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let y=0;y<16;y++,e+=4)Te[y]=t.getUint32(e),Pe[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let E=Te[y-15]|0,_=Pe[y-15]|0,L=F.rotrSH(E,_,1)^F.rotrSH(E,_,8)^F.shrSH(E,_,7),I=F.rotrSL(E,_,1)^F.rotrSL(E,_,8)^F.shrSL(E,_,7),P=Te[y-2]|0,T=Pe[y-2]|0,nt=F.rotrSH(P,T,19)^F.rotrBH(P,T,61)^F.shrSH(P,T,6),H=F.rotrSL(P,T,19)^F.rotrBL(P,T,61)^F.shrSL(P,T,6),K=F.add4L(I,H,Pe[y-7],Pe[y-16]),ht=F.add4H(K,L,nt,Te[y-7],Te[y-16]);Te[y]=ht|0,Pe[y]=K|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:p,Gh:g,Gl:h,Hh:w,Hl:x}=this;for(let y=0;y<80;y++){let E=F.rotrSH(f,d,14)^F.rotrSH(f,d,18)^F.rotrBH(f,d,41),_=F.rotrSL(f,d,14)^F.rotrSL(f,d,18)^F.rotrBL(f,d,41),L=f&m^~f&g,I=d&p^~d&h,P=F.add5L(x,_,I,sm[y],Pe[y]),T=F.add5H(P,w,E,L,om[y],Te[y]),nt=P|0,H=F.rotrSH(n,o,28)^F.rotrBH(n,o,34)^F.rotrBH(n,o,39),K=F.rotrSL(n,o,28)^F.rotrBL(n,o,34)^F.rotrBL(n,o,39),ht=n&s^n&a^s&a,A=o&i^o&c^i&c;w=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=F.add(l|0,u|0,T|0,nt|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=F.add3L(nt,K,A);n=F.add3H(D,T,H,ht),o=D|0}({h:n,l:o}=F.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=F.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=F.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=F.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=F.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:p}=F.add(this.Fh|0,this.Fl|0,m|0,p|0),{h:g,l:h}=F.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=F.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,m,p,g,h,w,x)}roundClean(){Te.fill(0),Pe.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Eu=Io(()=>new ta);var Lo={};Lt(Lo,{aInRange:()=>Ot,abool:()=>jt,abytes:()=>Br,bitGet:()=>fm,bitLen:()=>oa,bitMask:()=>bn,bitSet:()=>dm,bytesToHex:()=>pe,bytesToNumberBE:()=>me,bytesToNumberLE:()=>De,concatBytes:()=>ge,createHmacDrbg:()=>sa,ensureBytes:()=>it,equalBytes:()=>lm,hexToBytes:()=>Xe,hexToNumber:()=>na,inRange:()=>wn,isBytes:()=>Le,memoized:()=>je,notImplemented:()=>pm,numberToBytesBE:()=>ke,numberToBytesLE:()=>Ze,numberToHexUnpadded:()=>We,numberToVarBytesBE:()=>cm,utf8ToBytes:()=>um,validateObject:()=>oe});var To=BigInt(0),Po=BigInt(1),im=BigInt(2);function Le(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Br(r){if(!Le(r))throw new Error("Uint8Array expected")}function jt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var am=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function pe(r){Br(r);let t="";for(let e=0;e<r.length;e++)t+=am[r[e]];return t}function We(r){let t=r.toString(16);return t.length&1?"0"+t:t}function na(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?To:BigInt("0x"+r)}var he={_0:48,_9:57,A:65,F:70,a:97,f:102};function Su(r){if(r>=he._0&&r<=he._9)return r-he._0;if(r>=he.A&&r<=he.F)return r-(he.A-10);if(r>=he.a&&r<=he.f)return r-(he.a-10)}function Xe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Su(r.charCodeAt(s)),a=Su(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 me(r){return na(pe(r))}function De(r){return Br(r),na(pe(Uint8Array.from(r).reverse()))}function ke(r,t){return Xe(r.toString(16).padStart(t*2,"0"))}function Ze(r,t){return ke(r,t).reverse()}function cm(r){return Xe(We(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=Xe(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Le(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function ge(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Br(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function lm(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function um(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var ea=r=>typeof r=="bigint"&&To<=r;function wn(r,t,e){return ea(r)&&ea(t)&&ea(e)&&t<=r&&r<e}function Ot(r,t,e,n){if(!wn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function oa(r){let t;for(t=0;r>To;r>>=Po,t+=1);return t}function fm(r,t){return r>>BigInt(t)&Po}function dm(r,t,e){return r|(e?Po:To)<<BigInt(t)}var bn=r=>(im<<BigInt(r-1))-Po,ra=r=>new Uint8Array(r),Au=r=>Uint8Array.from(r);function sa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=ra(r),o=ra(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=ra())=>{o=a(Au([0]),f),n=a(),f.length!==0&&(o=a(Au([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let m=n.slice();d.push(m),f+=n.length}return ge(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var hm={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Le(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function oe(r,t,e={}){let n=(o,s,i)=>{let a=hm[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var pm=()=>{throw new Error("not implemented")};function je(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var pt=BigInt(0),ot=BigInt(1),Ye=BigInt(2),mm=BigInt(3),ia=BigInt(4),_u=BigInt(5),Iu=BigInt(8),gm=BigInt(9),ym=BigInt(16);function J(r,t){let e=r%t;return e>=pt?e:t+e}function wm(r,t,e){if(t<pt)throw new Error("invalid exponent, negatives unsupported");if(e<=pt)throw new Error("invalid modulus");if(e===ot)return pt;let n=ot;for(;t>pt;)t&ot&&(n=n*r%e),r=r*r%e,t>>=ot;return n}function st(r,t,e){let n=r;for(;t-- >pt;)n*=n,n%=e;return n}function Do(r,t){if(r===pt)throw new Error("invert: expected non-zero number");if(t<=pt)throw new Error("invert: expected positive modulus, got "+t);let e=J(r,t),n=t,o=pt,s=ot,i=ot,a=pt;for(;e!==pt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ot)throw new Error("invert: does not exist");return J(o,t)}function bm(r){let t=(r-ot)/Ye,e,n,o;for(e=r-ot,n=0;e%Ye===pt;e/=Ye,n++);for(o=Ye;o<r&&wm(o,t,r)!==r-ot;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ot)/ia;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ot)/Ye;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let p=a.pow(u,ot<<BigInt(l-m-1));u=a.sqr(p),f=a.mul(f,p),d=a.mul(d,u),l=m}return f}}function xm(r){if(r%ia===mm){let t=(r+ot)/ia;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Iu===_u){let t=(r-_u)/Iu;return function(n,o){let s=n.mul(o,Ye),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,Ye),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%ym,bm(r)}var Cu=(r,t)=>(J(r,t)&ot)===ot,vm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function aa(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=vm.reduce((n,o)=>(n[o]="function",n),t);return oe(r,e)}function Em(r,t,e){if(e<pt)throw new Error("invalid exponent, negatives unsupported");if(e===pt)return r.ONE;if(e===ot)return t;let n=r.ONE,o=t;for(;e>pt;)e&ot&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ot;return n}function Sm(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function ca(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Re(r,t,e=!1,n={}){if(r<=pt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=ca(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:bn(o),ZERO:pt,ONE:ot,create:c=>J(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return pt<=c&&c<r},is0:c=>c===pt,isOdd:c=>(c&ot)===ot,neg:c=>J(-c,r),eql:(c,l)=>c===l,sqr:c=>J(c*c,r),add:(c,l)=>J(c+l,r),sub:(c,l)=>J(c-l,r),mul:(c,l)=>J(c*l,r),pow:(c,l)=>Em(a,c,l),div:(c,l)=>J(c*Do(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Do(c,r),sqrt:n.sqrt||(c=>(i||(i=xm(r)),i(a,c))),invertBatch:c=>Sm(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Ze(c,s):ke(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?De(c):me(c)}});return Object.freeze(a)}function Tu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function la(r){let t=Tu(r);return t+Math.ceil(t/2)}function Pu(r,t,e=!1){let n=r.length,o=Tu(t),s=la(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?De(r):me(r),a=J(i,t-ot)+ot;return e?Ze(a,o):ke(a,o)}var Lu=BigInt(0),ko=BigInt(1);function ua(r,t){let e=t.negate();return r?e:t}function Du(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function fa(r,t){Du(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Am(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function _m(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var da=new WeakMap,ku=new WeakMap;function ha(r){return ku.get(r)||1}function Ro(r,t){return{constTimeNegate:ua,hasPrecomputes(e){return ha(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Lu;)n&ko&&(o=o.add(s)),s=s.double(),n>>=ko;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=fa(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=fa(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let m=d*i,p=Number(o&l);o>>=f,p>i&&(p-=u,o+=ko);let g=m,h=m+Math.abs(p)-1,w=d%2!==0,x=p<0;p===0?c=c.add(ua(w,n[g])):a=a.add(ua(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=fa(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===Lu)break;let m=Number(o&c);if(o>>=u,m>a&&(m-=l,o+=ko),m===0)continue;let p=n[d+Math.abs(m)-1];m<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(e,n,o){let s=da.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&da.set(n,o(s))),s},wNAFCached(e,n,o){let s=ha(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=ha(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Du(n,t),ku.set(e,n),da.delete(e)}}}function No(r,t,e,n){if(Am(e,r),_m(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=oa(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let p=n[m],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[m])}let d=o;for(let m=c.length-1,p=o;m>0;m--)p=p.add(c[m]),d=d.add(p);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function xn(r){return aa(r.Fp),oe(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ca(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Yt=BigInt(0),Ft=BigInt(1),Mo=BigInt(2),Im=BigInt(8),Cm={zip215:!0};function Tm(r){let t=xn(r);return oe(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Ru(r){let t=Tm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Mo<<BigInt(a*8)-Ft,u=e.create,f=Re(t.n,t.nBitLength),d=t.uvRatio||((v,b)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(b))}}catch{return{isValid:!1,value:Yt}}}),m=t.adjustScalarBytes||(v=>v),p=t.domain||((v,b,S)=>{if(jt("phflag",S),b.length||S)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b){Ot("coordinate "+v,b,Yt,l)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let w=je((v,b)=>{let{ex:S,ey:C,ez:N}=v,M=v.is0();b==null&&(b=M?Im:e.inv(N));let U=u(S*b),q=u(C*b),O=u(N*b);if(M)return{x:Yt,y:Ft};if(O!==Ft)throw new Error("invZ was invalid");return{x:U,y:q}}),x=je(v=>{let{a:b,d:S}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:C,ey:N,ez:M,et:U}=v,q=u(C*C),O=u(N*N),Y=u(M*M),et=u(Y*Y),gt=u(q*b),yt=u(Y*u(gt+O)),xt=u(et+u(S*u(q*O)));if(yt!==xt)throw new Error("bad point: equation left != right (1)");let Et=u(C*N),Bt=u(M*U);if(Et!==Bt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(b,S,C,N){this.ex=b,this.ey=S,this.ez=C,this.et=N,g("x",b),g("y",S),g("z",C),g("t",N),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof y)throw new Error("extended point not allowed");let{x:S,y:C}=b||{};return g("x",S),g("y",C),new y(S,C,Ft,u(S*C))}static normalizeZ(b){let S=e.invertBatch(b.map(C=>C.ez));return b.map((C,N)=>C.toAffine(S[N])).map(y.fromAffine)}static msm(b,S){return No(y,f,b,S)}_setWindowSize(b){L.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:S,ey:C,ez:N}=this,{ex:M,ey:U,ez:q}=b,O=u(S*q),Y=u(M*N),et=u(C*q),gt=u(U*N);return O===Y&&et===gt}is0(){return this.equals(y.ZERO)}negate(){return new y(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:b}=t,{ex:S,ey:C,ez:N}=this,M=u(S*S),U=u(C*C),q=u(Mo*u(N*N)),O=u(b*M),Y=S+C,et=u(u(Y*Y)-M-U),gt=O+U,yt=gt-q,xt=O-U,Et=u(et*yt),Bt=u(gt*xt),Pt=u(et*xt),re=u(yt*gt);return new y(Et,Bt,re,Pt)}add(b){h(b);let{a:S,d:C}=t,{ex:N,ey:M,ez:U,et:q}=this,{ex:O,ey:Y,ez:et,et:gt}=b;if(S===BigInt(-1)){let Vl=u((M-N)*(Y+O)),$l=u((M+N)*(Y-O)),Bi=u($l-Vl);if(Bi===Yt)return this.double();let Hl=u(U*Mo*gt),Gl=u(q*Mo*et),Wl=Gl+Hl,Xl=$l+Vl,Zl=Gl-Hl,Fh=u(Wl*Bi),Uh=u(Xl*Zl),Kh=u(Wl*Zl),qh=u(Bi*Xl);return new y(Fh,Uh,qh,Kh)}let yt=u(N*O),xt=u(M*Y),Et=u(q*C*gt),Bt=u(U*et),Pt=u((N+M)*(O+Y)-yt-xt),re=Bt-Et,ce=Bt+Et,cn=u(xt-S*yt),Nh=u(Pt*re),Mh=u(ce*cn),Bh=u(Pt*cn),Oh=u(re*ce);return new y(Nh,Mh,Oh,Bh)}subtract(b){return this.add(b.negate())}wNAF(b){return L.wNAFCached(this,b,y.normalizeZ)}multiply(b){let S=b;Ot("scalar",S,Ft,n);let{p:C,f:N}=this.wNAF(S);return y.normalizeZ([C,N])[0]}multiplyUnsafe(b,S=y.ZERO){let C=b;return Ot("scalar",C,Yt,n),C===Yt?_:this.is0()||C===Ft?this:L.wNAFCachedUnsafe(this,C,y.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=t;return b===Ft?this:this.multiplyUnsafe(b)}static fromHex(b,S=!1){let{d:C,a:N}=t,M=e.BYTES;b=it("pointHex",b,M),jt("zip215",S);let U=b.slice(),q=b[M-1];U[M-1]=q&-129;let O=De(U),Y=S?l:e.ORDER;Ot("pointHex.y",O,Yt,Y);let et=u(O*O),gt=u(et-Ft),yt=u(C*et-N),{isValid:xt,value:Et}=d(gt,yt);if(!xt)throw new Error("Point.fromHex: invalid y coordinate");let Bt=(Et&Ft)===Ft,Pt=(q&128)!==0;if(!S&&Et===Yt&&Pt)throw new Error("Point.fromHex: x=0 and x_0=1");return Pt!==Bt&&(Et=u(-Et)),y.fromAffine({x:Et,y:O})}static fromPrivateKey(b){return T(b).point}toRawBytes(){let{x:b,y:S}=this.toAffine(),C=Ze(S,e.BYTES);return C[C.length-1]|=b&Ft?128:0,C}toHex(){return pe(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,Ft,u(t.Gx*t.Gy)),y.ZERO=new y(Yt,Ft,Ft,Yt);let{BASE:E,ZERO:_}=y,L=Ro(y,a*8);function I(v){return J(v,n)}function P(v){return I(De(v))}function T(v){let b=e.BYTES;v=it("private key",v,b);let S=it("hashed private key",s(v),2*b),C=m(S.slice(0,b)),N=S.slice(b,2*b),M=P(C),U=E.multiply(M),q=U.toRawBytes();return{head:C,prefix:N,scalar:M,point:U,pointBytes:q}}function nt(v){return T(v).pointBytes}function H(v=new Uint8Array,...b){let S=ge(...b);return P(s(p(S,it("context",v),!!o)))}function K(v,b,S={}){v=it("message",v),o&&(v=o(v));let{prefix:C,scalar:N,pointBytes:M}=T(b),U=H(S.context,C,v),q=E.multiply(U).toRawBytes(),O=H(S.context,q,M,v),Y=I(U+O*N);Ot("signature.s",Y,Yt,n);let et=ge(q,Ze(Y,e.BYTES));return it("result",et,e.BYTES*2)}let ht=Cm;function A(v,b,S,C=ht){let{context:N,zip215:M}=C,U=e.BYTES;v=it("signature",v,2*U),b=it("message",b),S=it("publicKey",S,U),M!==void 0&&jt("zip215",M),o&&(b=o(b));let q=De(v.slice(U,2*U)),O,Y,et;try{O=y.fromHex(S,M),Y=y.fromHex(v.slice(0,U),M),et=E.multiplyUnsafe(q)}catch{return!1}if(!M&&O.isSmallOrder())return!1;let gt=H(N,Y.toRawBytes(),O.toRawBytes(),b);return Y.add(O.multiplyUnsafe(gt)).subtract(et).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:nt,sign:K,verify:A,ExtendedPoint:y,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,b=y.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var pa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Nu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),rx=BigInt(0),Pm=BigInt(1),Mu=BigInt(2),nx=BigInt(3),Lm=BigInt(5),Dm=BigInt(8);function km(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=pa,a=r*r%s*r%s,c=st(a,Mu,s)*a%s,l=st(c,Pm,s)*r%s,u=st(l,Lm,s)*l%s,f=st(u,t,s)*u%s,d=st(f,e,s)*f%s,m=st(d,n,s)*d%s,p=st(m,o,s)*m%s,g=st(p,o,s)*m%s,h=st(g,t,s)*u%s;return{pow_p_5_8:st(h,Mu,s)*r%s,b2:a}}function Rm(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Nm(r,t){let e=pa,n=J(t*t*t,e),o=J(n*n*t,e),s=km(r*o).pow_p_5_8,i=J(r*n*s,e),a=J(t*i*i,e),c=i,l=J(i*Nu,e),u=a===r,f=a===J(-r,e),d=a===J(-r*Nu,e);return u&&(i=c),(f||d)&&(i=l),Cu(i,e)&&(i=J(-i,e)),{isValid:u||f,value:i}}var Mm=Re(pa,void 0,!0),Bm={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Mm,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Dm,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Eu,randomBytes:Nr,adjustScalarBytes:Rm,uvRatio:Nm},vn=Ru(Bm);var Bo=32,Oo=64,ma=32;function Bu(){let r=vn.utils.randomPrivateKey(),t=vn.getPublicKey(r);return{privateKey:Om(r,t),publicKey:t}}function Ou(r,t){let e=r.subarray(0,ma);return vn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Fu(r,t,e){return vn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Om(r,t){let e=new Uint8Array(Oo);for(let n=0;n<ma;n++)e[n]=r[n],e[ma+n]=t[n];return e}var En=class{type="Ed25519";raw;constructor(t){this.raw=Uo(t,Bo)}toMultihash(){return de.digest(se(this))}toCID(){return ut.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:rt(this.raw,t.raw)}verify(t,e){return Fu(this.raw,e,t)}},Fo=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Uo(t,Oo),this.publicKey=new En(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:rt(this.raw,t.raw)}sign(t){return Ou(this.raw,t)}};function ga(r){return r=Uo(r,Bo),new En(r)}async function Ku(){let{privateKey:r,publicKey:t}=Bu();return new Fo(r,t)}function Uo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function lt(r=0){return new Uint8Array(r)}function St(r=0){return new Uint8Array(r)}var Fm=Math.pow(2,7),Um=Math.pow(2,14),Km=Math.pow(2,21),ya=Math.pow(2,28),wa=Math.pow(2,35),ba=Math.pow(2,42),xa=Math.pow(2,49),j=128,At=127;function dt(r){if(r<Fm)return 1;if(r<Um)return 2;if(r<Km)return 3;if(r<ya)return 4;if(r<wa)return 5;if(r<ba)return 6;if(r<xa)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function va(r,t,e=0){switch(dt(r)){case 8:t[e++]=r&255|j,r/=128;case 7:t[e++]=r&255|j,r/=128;case 6:t[e++]=r&255|j,r/=128;case 5:t[e++]=r&255|j,r/=128;case 4:t[e++]=r&255|j,r>>>=7;case 3:t[e++]=r&255|j,r>>>=7;case 2:t[e++]=r&255|j,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function qm(r,t,e=0){switch(dt(r)){case 8:t.set(e++,r&255|j),r/=128;case 7:t.set(e++,r&255|j),r/=128;case 6:t.set(e++,r&255|j),r/=128;case 5:t.set(e++,r&255|j),r/=128;case 4:t.set(e++,r&255|j),r>>>=7;case 3:t.set(e++,r&255|j),r>>>=7;case 2:t.set(e++,r&255|j),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ea(r,t){let e=r[t],n=0;if(n+=e&At,e<j||(e=r[t+1],n+=(e&At)<<7,e<j)||(e=r[t+2],n+=(e&At)<<14,e<j)||(e=r[t+3],n+=(e&At)<<21,e<j)||(e=r[t+4],n+=(e&At)*ya,e<j)||(e=r[t+5],n+=(e&At)*wa,e<j)||(e=r[t+6],n+=(e&At)*ba,e<j)||(e=r[t+7],n+=(e&At)*xa,e<j))return n;throw new RangeError("Could not decode varint")}function zm(r,t){let e=r.get(t),n=0;if(n+=e&At,e<j||(e=r.get(t+1),n+=(e&At)<<7,e<j)||(e=r.get(t+2),n+=(e&At)<<14,e<j)||(e=r.get(t+3),n+=(e&At)<<21,e<j)||(e=r.get(t+4),n+=(e&At)*ya,e<j)||(e=r.get(t+5),n+=(e&At)*wa,e<j)||(e=r.get(t+6),n+=(e&At)*ba,e<j)||(e=r.get(t+7),n+=(e&At)*xa,e<j))return n;throw new RangeError("Could not decode varint")}function _t(r,t,e=0){return t==null&&(t=St(dt(r))),t instanceof Uint8Array?va(r,t,e):qm(r,t,e)}function Qt(r,t=0){return r instanceof Uint8Array?Ea(r,t):zm(r,t)}var Sa=new Float32Array([-0]),Ne=new Uint8Array(Sa.buffer);function qu(r,t,e){Sa[0]=r,t[e]=Ne[0],t[e+1]=Ne[1],t[e+2]=Ne[2],t[e+3]=Ne[3]}function zu(r,t){return Ne[0]=r[t],Ne[1]=r[t+1],Ne[2]=r[t+2],Ne[3]=r[t+3],Sa[0]}var Aa=new Float64Array([-0]),It=new Uint8Array(Aa.buffer);function Vu(r,t,e){Aa[0]=r,t[e]=It[0],t[e+1]=It[1],t[e+2]=It[2],t[e+3]=It[3],t[e+4]=It[4],t[e+5]=It[5],t[e+6]=It[6],t[e+7]=It[7]}function $u(r,t){return It[0]=r[t],It[1]=r[t+1],It[2]=r[t+2],It[3]=r[t+3],It[4]=r[t+4],It[5]=r[t+5],It[6]=r[t+6],It[7]=r[t+7],Aa[0]}var Vm=BigInt(Number.MAX_SAFE_INTEGER),$m=BigInt(Number.MIN_SAFE_INTEGER),zt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Je;if(t<Vm&&t>$m)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Hu&&(o=0n,++n>Hu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Je;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Je}},Je=new zt(0,0);Je.toBigInt=function(){return 0n};Je.zzEncode=Je.zzDecode=function(){return this};Je.length=function(){return 1};var Hu=4294967296n;function Gu(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Wu(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 _a(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Jt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Ko(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ia=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Jt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Jt(this,4);return Ko(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Jt(this,4);return Ko(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Jt(this,4);let t=zu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Jt(this,4);let t=$u(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Jt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Wu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Jt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Jt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new zt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Jt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Jt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Jt(this,8);let t=Ko(this.buf,this.pos+=4),e=Ko(this.buf,this.pos+=4);return new zt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ea(this.buf,this.pos);return this.pos+=dt(t),t}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 Ca(r){return new Ia(r instanceof Uint8Array?r:r.subarray())}function Dt(r,t,e){let n=Ca(r);return t.decode(n,void 0,e)}var Ta={};Lt(Ta,{base10:()=>Hm});var Hm=Ce({prefix:"9",name:"base10",alphabet:"0123456789"});var Pa={};Lt(Pa,{base16:()=>Gm,base16upper:()=>Wm});var Gm=ct({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Wm=ct({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var La={};Lt(La,{base2:()=>Xm});var Xm=ct({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Da={};Lt(Da,{base256emoji:()=>Jm});var Zu=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}"),Zm=Zu.reduce((r,t,e)=>(r[e]=t,r),[]),jm=Zu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Ym(r){return r.reduce((t,e)=>(t+=Zm[e],t),"")}function Qm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=jm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Jm=Cr({prefix:"\u{1F680}",name:"base256emoji",encode:Ym,decode:Qm});var Na={};Lt(Na,{base64:()=>ka,base64pad:()=>tg,base64url:()=>Ra,base64urlpad:()=>eg});var ka=ct({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tg=ct({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ra=ct({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eg=ct({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ma={};Lt(Ma,{base8:()=>rg});var rg=ct({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ba={};Lt(Ba,{identity:()=>ng});var ng=Cr({prefix:"\0",name:"identity",encode:r=>ru(r),decode:r=>eu(r)});var Bx=new TextEncoder,Ox=new TextDecoder;var Ua={};Lt(Ua,{sha256:()=>Or,sha512:()=>ig});function Fa({name:r,code:t,encode:e}){return new Oa(r,t,e)}var Oa=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Xt(this.code,e):e.then(n=>Xt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Yu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Or=Fa({name:"sha2-256",code:18,encode:Yu("SHA-256")}),ig=Fa({name:"sha2-512",code:19,encode:Yu("SHA-512")});var Sn={...Ba,...La,...Ma,...Ta,...Pa,...Wi,...Xi,...Gi,...Na,...Da},Zx={...Ua,...Yi};function Ju(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Qu=Ju("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ka=Ju("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=St(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ag={utf8:Qu,"utf-8":Qu,hex:Sn.base16,latin1:Ka,ascii:Ka,binary:Ka,...Sn},qo=ag;function k(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function qa(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return St(i);o+i>t&&(n=St(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var tr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function za(){}var $a=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},cg=qa();function lg(r){return globalThis.Buffer!=null?St(r):cg(r)}var _n=class{len;head;tail;states;constructor(){this.len=0,this.head=new tr(za,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new tr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ha((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(zo,10,zt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=zt.fromBigInt(t);return this._push(zo,e.length(),e)}uint64Number(t){return this._push(va,dt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=zt.fromBigInt(t).zzEncode();return this._push(zo,e.length(),e)}sint64Number(t){let e=zt.fromNumber(t).zzEncode();return this._push(zo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Va,1,t?1:0)}fixed32(t){return this._push(An,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=zt.fromBigInt(t);return this._push(An,4,e.lo)._push(An,4,e.hi)}fixed64Number(t){let e=zt.fromNumber(t);return this._push(An,4,e.lo)._push(An,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(qu,4,t)}double(t){return this._push(Vu,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Va,1,0):this.uint32(e)._push(fg,e,t)}string(t){let e=Gu(t);return e!==0?this.uint32(e)._push(_a,e,t):this._push(Va,1,0)}fork(){return this.states=new $a(this),this.head=this.tail=new tr(za,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 tr(za,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=lg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Va(r,t,e){t[e]=r&255}function ug(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ha=class extends tr{next;constructor(t,e){super(ug,t,e),this.next=void 0}};function zo(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function An(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function fg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(_n.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(dg,t,r),this},_n.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(hg,t,r),this});function dg(r,t,e){t.set(r,e)}function hg(r,t,e){r.length<40?_a(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function Ga(){return new _n}function kt(r,t){let e=Ga();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Fr;(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"})(Fr||(Fr={}));function Vo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Wa(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Vo("enum",Fr.VARINT,e,n)}function Rt(r,t){return Vo("message",Fr.LENGTH_DELIMITED,r,t)}var er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},In=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var mt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(mt||(mt={}));var Xa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(Xa||(Xa={}));(function(r){r.codec=()=>Wa(Xa)})(mt||(mt={}));var ie;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),mt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=mt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ie||(ie={}));var Za;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),mt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=mt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Za||(Za={}));var Ln={};Lt(Ln,{MAX_RSA_KEY_SIZE:()=>tc,generateRSAKeyPair:()=>oc,jwkToJWKKeyPair:()=>mf,jwkToPkcs1:()=>_g,jwkToPkix:()=>rc,jwkToRSAPrivateKey:()=>pf,pkcs1ToJwk:()=>ff,pkcs1ToRSAPrivateKey:()=>hf,pkixToJwk:()=>df,pkixToRSAPublicKey:()=>nc});var pg=new Uint32Array([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]),Me=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Be=new Uint32Array(64),ja=class extends Mr{constructor(){super(64,32,8,!1),this.A=Me[0]|0,this.B=Me[1]|0,this.C=Me[2]|0,this.D=Me[3]|0,this.E=Me[4]|0,this.F=Me[5]|0,this.G=Me[6]|0,this.H=Me[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|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(t,e){for(let f=0;f<16;f++,e+=4)Be[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Be[f-15],m=Be[f-2],p=Zt(d,7)^Zt(d,18)^d>>>3,g=Zt(m,17)^Zt(m,19)^m>>>10;Be[f]=g+Be[f-7]+p+Be[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=Zt(a,6)^Zt(a,11)^Zt(a,25),m=u+d+bu(a,c,l)+pg[f]+Be[f]|0,g=(Zt(n,2)^Zt(n,13)^Zt(n,22))+xu(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|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(){Be.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Ur=Io(()=>new ja);function B(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function Nt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=St(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var rf=Symbol.for("@achingbrain/uint8arraylist");function ef(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function $o(r){return!!r?.[rf]}var Q=class r{bufs;length;[rf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if($o(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if($o(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=ef(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ef(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if($o(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Nt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Nt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!$o(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!rt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var mg=parseInt("11111",2),Qa=parseInt("10000000",2),gg=parseInt("01111111",2),nf={2:yg,3:xg,5:bg,6:wg,16:Ya,22:Ya,48:Ya};function Cn(r,t={offset:0}){let e=r[t.offset]&mg;if(t.offset++,nf[e]!=null)return nf[e](r,t);throw new Error("No decoder for tag "+e)}function Ho(r,t){let e=0;if((r[t.offset]&Qa)===Qa){let n=r[t.offset]&gg,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Ya(r,t){Ho(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Cn(r,t);if(n===null)break;e.push(n)}return e}function yg(r,t){let e=Ho(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function wg(r,t){let e=Ho(r,t);return t.offset+=e,["oid-unimplemented"]}function bg(r,t){return t.offset++,null}function xg(r,t){let e=Ho(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return Cn(o,{offset:0})}function vg(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Q;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Ja(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=vg(r.byteLength);return new Q(Uint8Array.from([t.byteLength|Qa]),t)}function $t(r){let t=new Q,e=parseInt("10000000",2);return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Q(Uint8Array.from([2]),Ja(t),t)}function of(r){let t=Uint8Array.from([0]),e=new Q(t,r);return new Q(Uint8Array.from([3]),Ja(e),e)}function Go(r){let t=new Q;for(let e of r)t.append(e);return new Q(Uint8Array.from([48]),Ja(t),t)}function Kr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Nr(r)}var Tn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Pn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Wo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var sf={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Wo("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 t}};var Oe=sf;async function af(r){let t=await Oe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Eg(t);return{privateKey:e[0],publicKey:e[1]}}async function cf(r,t){let e=await Oe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Oe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function lf(r,t,e){let n=await Oe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Oe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Eg(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([Oe.get().subtle.exportKey("jwk",r.privateKey),Oe.get().subtle.exportKey("jwk",r.publicKey)])}function uf(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return k(r.n,"base64url").length*8}var qr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Ln.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return ut.createV1(114,this._multihash)}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:rt(this.raw,t.raw)}verify(t,e){return lf(this._key,e,t)}},Dn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Ln.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:rt(this.raw,t.raw)}sign(t){return cf(this._key,t)}};var tc=8192,ec=18,Sg=1062,Ag=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ff(r){let t=Cn(r);return{n:B(t[1],"base64url"),e:B(t[2],"base64url"),d:B(t[3],"base64url"),p:B(t[4],"base64url"),q:B(t[5],"base64url"),dp:B(t[6],"base64url"),dq:B(t[7],"base64url"),qi:B(t[8],"base64url"),kty:"RSA"}}function _g(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 R("JWK was missing components");return Go([$t(Uint8Array.from([0])),$t(k(r.n,"base64url")),$t(k(r.e,"base64url")),$t(k(r.d,"base64url")),$t(k(r.p,"base64url")),$t(k(r.q,"base64url")),$t(k(r.dp,"base64url")),$t(k(r.dq,"base64url")),$t(k(r.qi,"base64url"))]).subarray()}function df(r){let t=Cn(r,{offset:0});return{kty:"RSA",n:B(t[1][0],"base64url"),e:B(t[1][1],"base64url")}}function rc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Go([Ag,of(Go([$t(k(r.n,"base64url")),$t(k(r.e,"base64url"))]))]).subarray()}function hf(r){let t=ff(r);return pf(t)}function nc(r,t){if(r.byteLength>=Sg)throw new Er("Key size is too large");let e=df(r);if(t==null){let n=Ur(ie.encode({Type:mt.RSA,Data:r}));t=Xt(ec,n)}return new qr(e,t)}function pf(r){if(uf(r)>tc)throw new R("Key size is too large");let t=mf(r),e=Ur(ie.encode({Type:mt.RSA,Data:rc(t.publicKey)})),n=Xt(ec,e);return new Dn(t.privateKey,new qr(t.publicKey,n))}async function oc(r){if(r>tc)throw new R("Key size is too large");let t=await af(r),e=Ur(ie.encode({Type:mt.RSA,Data:rc(t.publicKey)})),n=Xt(ec,e);return new Dn(t.privateKey,new qr(t.publicKey,n))}function mf(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Xo=class extends Rr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,gu(t);let n=yn(e);if(this.iHash=t.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?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return kr(this),this.iHash.update(t),this}digestInto(t){kr(this),Dr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},sc=(r,t,e)=>new Xo(r,t).update(e).digest();sc.create=(r,t)=>new Xo(r,t);function gf(r){r.lowS!==void 0&&jt("lowS",r.lowS),r.prehash!==void 0&&jt("prehash",r.prehash)}function Ig(r){let t=xn(r);oe(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Cg,hexToBytes:Tg}=Lo,ic=class extends Error{constructor(t=""){super(t)}},ye={Err:ic,_tlv:{encode:(r,t)=>{let{Err:e}=ye;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=We(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?We(o.length/2|128):"";return We(r)+s+o+t},decode(r,t){let{Err:e}=ye,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=ye;if(r<we)throw new t("integer: negative integers are not allowed");let e=We(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=ye;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Cg(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ye,o=typeof r=="string"?Tg(r):r;Br(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("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 t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=ye,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},we=BigInt(0),wt=BigInt(1),x2=BigInt(2),yf=BigInt(3),v2=BigInt(4);function Pg(r){let t=Ig(r),{Fp:e}=t,n=Re(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let x=h.toAffine();return ge(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=t,x=e.sqr(g),y=e.mul(x,g);return e.add(e.add(y,e.mul(g,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return wn(g,wt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=t;if(h&&typeof g!="bigint"){if(Le(g)&&(g=pe(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let E;try{E=typeof g=="bigint"?g:me(it("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=J(E,y)),Ot("private key",E,wt,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=je((g,h)=>{let{px:w,py:x,pz:y}=g;if(e.eql(y,e.ONE))return{x:w,y:x};let E=g.is0();h==null&&(h=E?e.ONE:e.inv(y));let _=e.mul(w,h),L=e.mul(x,h),I=e.mul(y,h);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(I,e.ONE))throw new Error("invZ was invalid");return{x:_,y:L}}),f=je(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let x=e.sqr(w),y=i(h);if(!e.eql(x,y))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!e.isValid(w)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let y=E=>e.eql(E,e.ZERO);return y(w)&&y(x)?d.ZERO:new d(w,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(w[y])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(it("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return No(d,n,h,w)}_setWindowSize(h){p.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=e.eql(e.mul(w,L),e.mul(E,y)),P=e.eql(e.mul(x,L),e.mul(_,y));return I&&P}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,x=e.mul(w,yf),{px:y,py:E,pz:_}=this,L=e.ZERO,I=e.ZERO,P=e.ZERO,T=e.mul(y,y),nt=e.mul(E,E),H=e.mul(_,_),K=e.mul(y,E);return K=e.add(K,K),P=e.mul(y,_),P=e.add(P,P),L=e.mul(h,P),I=e.mul(x,H),I=e.add(L,I),L=e.sub(nt,I),I=e.add(nt,I),I=e.mul(L,I),L=e.mul(K,L),P=e.mul(x,P),H=e.mul(h,H),K=e.sub(T,H),K=e.mul(h,K),K=e.add(K,P),P=e.add(T,T),T=e.add(P,T),T=e.add(T,H),T=e.mul(T,K),I=e.add(I,T),H=e.mul(E,_),H=e.add(H,H),T=e.mul(H,K),L=e.sub(L,T),P=e.mul(H,nt),P=e.add(P,P),P=e.add(P,P),new d(L,I,P)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=e.ZERO,P=e.ZERO,T=e.ZERO,nt=t.a,H=e.mul(t.b,yf),K=e.mul(w,E),ht=e.mul(x,_),A=e.mul(y,L),D=e.add(w,x),v=e.add(E,_);D=e.mul(D,v),v=e.add(K,ht),D=e.sub(D,v),v=e.add(w,y);let b=e.add(E,L);return v=e.mul(v,b),b=e.add(K,A),v=e.sub(v,b),b=e.add(x,y),I=e.add(_,L),b=e.mul(b,I),I=e.add(ht,A),b=e.sub(b,I),T=e.mul(nt,v),I=e.mul(H,A),T=e.add(I,T),I=e.sub(ht,T),T=e.add(ht,T),P=e.mul(I,T),ht=e.add(K,K),ht=e.add(ht,K),A=e.mul(nt,A),v=e.mul(H,v),ht=e.add(ht,A),A=e.sub(K,A),A=e.mul(nt,A),v=e.add(v,A),K=e.mul(ht,v),P=e.add(P,K),K=e.mul(b,v),I=e.mul(D,I),I=e.sub(I,K),K=e.mul(D,ht),T=e.mul(b,T),T=e.add(T,K),new d(I,P,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return p.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:x}=t;Ot("scalar",h,we,x);let y=d.ZERO;if(h===we)return y;if(this.is0()||h===wt)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:L,k2:I}=w.splitScalar(h),P=y,T=y,nt=this;for(;_>we||I>we;)_&wt&&(P=P.add(nt)),I&wt&&(T=T.add(nt)),nt=nt.double(),_>>=wt,I>>=wt;return E&&(P=P.negate()),L&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),P.add(T)}multiply(h){let{endo:w,n:x}=t;Ot("scalar",h,wt,x);let y,E;if(w){let{k1neg:_,k1:L,k2neg:I,k2:P}=w.splitScalar(h),{p:T,f:nt}=this.wNAF(L),{p:H,f:K}=this.wNAF(P);T=p.constTimeNegate(_,T),H=p.constTimeNegate(I,H),H=new d(e.mul(H.px,w.beta),H.py,H.pz),y=T.add(H),E=nt.add(K)}else{let{p:_,f:L}=this.wNAF(h);y=_,E=L}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(L,I)=>I===we||I===wt||!L.equals(y)?L.multiplyUnsafe(I):L.multiply(I),_=E(this,w).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===wt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===wt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return jt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return jt("isCompressed",h),pe(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,p=Ro(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Lg(r){let t=xn(r);return oe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function wf(r){let t=Lg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(A){return J(A,n)}function a(A){return Do(A,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Pg({...t,toBytes(A,D,v){let b=D.toAffine(),S=e.toBytes(b.x),C=ge;return jt("isCompressed",v),v?C(Uint8Array.from([D.hasEvenY()?2:3]),S):C(Uint8Array.from([4]),S,e.toBytes(b.y))},fromBytes(A){let D=A.length,v=A[0],b=A.subarray(1);if(D===o&&(v===2||v===3)){let S=me(b);if(!wn(S,wt,e.ORDER))throw new Error("Point is not on curve");let C=u(S),N;try{N=e.sqrt(C)}catch(q){let O=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+O)}let M=(N&wt)===wt;return(v&1)===1!==M&&(N=e.neg(N)),{x:S,y:N}}else if(D===s&&v===4){let S=e.fromBytes(b.subarray(0,e.BYTES)),C=e.fromBytes(b.subarray(e.BYTES,2*e.BYTES));return{x:S,y:C}}else{let S=o,C=s;throw new Error("invalid Point, expected length of "+S+", or uncompressed "+C+", got "+D)}}}),d=A=>pe(ke(A,t.nByteLength));function m(A){let D=n>>wt;return A>D}function p(A){return m(A)?i(-A):A}let g=(A,D,v)=>me(A.slice(D,v));class h{constructor(D,v,b){this.r=D,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(D){let v=t.nByteLength;return D=it("compactSignature",D,v*2),new h(g(D,0,v),g(D,v,2*v))}static fromDER(D){let{r:v,s:b}=ye.toSig(it("DER",D));return new h(v,b)}assertValidity(){Ot("r",this.r,wt,n),Ot("s",this.s,wt,n)}addRecoveryBit(D){return new h(this.r,this.s,D)}recoverPublicKey(D){let{r:v,s:b,recovery:S}=this,C=L(it("msgHash",D));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let N=S===2||S===3?v+t.n:v;if(N>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=(S&1)===0?"02":"03",U=c.fromHex(M+d(N)),q=a(N),O=i(-C*q),Y=i(b*q),et=c.BASE.multiplyAndAddUnsafe(U,O,Y);if(!et)throw new Error("point at infinify");return et.assertValidity(),et}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Xe(this.toDERHex())}toDERHex(){return ye.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(A){try{return l(A),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let A=la(t.n);return Pu(t.randomBytes(A),t.n)},precompute(A=8,D=c.BASE){return D._setWindowSize(A),D.multiply(BigInt(3)),D}};function x(A,D=!0){return c.fromPrivateKey(A).toRawBytes(D)}function y(A){let D=Le(A),v=typeof A=="string",b=(D||v)&&A.length;return D?b===o||b===s:v?b===2*o||b===2*s:A instanceof c}function E(A,D,v=!0){if(y(A))throw new Error("first arg must be private key");if(!y(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(l(A)).toRawBytes(v)}let _=t.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");let D=me(A),v=A.length*8-t.nBitLength;return v>0?D>>BigInt(v):D},L=t.bits2int_modN||function(A){return i(_(A))},I=bn(t.nBitLength);function P(A){return Ot("num < 2^"+t.nBitLength,A,we,I),ke(A,t.nByteLength)}function T(A,D,v=nt){if(["recovered","canonical"].some(yt=>yt in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:S}=t,{lowS:C,prehash:N,extraEntropy:M}=v;C==null&&(C=!0),A=it("msgHash",A),gf(v),N&&(A=it("prehashed msgHash",b(A)));let U=L(A),q=l(D),O=[P(q),P(U)];if(M!=null&&M!==!1){let yt=M===!0?S(e.BYTES):M;O.push(it("extraEntropy",yt))}let Y=ge(...O),et=U;function gt(yt){let xt=_(yt);if(!f(xt))return;let Et=a(xt),Bt=c.BASE.multiply(xt).toAffine(),Pt=i(Bt.x);if(Pt===we)return;let re=i(Et*i(et+Pt*q));if(re===we)return;let ce=(Bt.x===Pt?0:2)|Number(Bt.y&wt),cn=re;return C&&m(re)&&(cn=p(re),ce^=1),new h(Pt,cn,ce)}return{seed:Y,k2sig:gt}}let nt={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function K(A,D,v=nt){let{seed:b,k2sig:S}=T(A,D,v),C=t;return sa(C.hash.outputLen,C.nByteLength,C.hmac)(b,S)}c.BASE._setWindowSize(8);function ht(A,D,v,b=H){let S=A;D=it("msgHash",D),v=it("publicKey",v);let{lowS:C,prehash:N,format:M}=b;if(gf(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&M!=="compact"&&M!=="der")throw new Error("format must be compact or der");let U=typeof S=="string"||Le(S),q=!U&&!M&&typeof S=="object"&&S!==null&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!U&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,Y;try{if(q&&(O=new h(S.r,S.s)),U){try{M!=="compact"&&(O=h.fromDER(S))}catch(ce){if(!(ce instanceof ye.Err))throw ce}!O&&M!=="der"&&(O=h.fromCompact(S))}Y=c.fromHex(v)}catch{return!1}if(!O||C&&O.hasHighS())return!1;N&&(D=t.hash(D));let{r:et,s:gt}=O,yt=L(D),xt=a(gt),Et=i(yt*xt),Bt=i(et*xt),Pt=c.BASE.multiplyAndAddUnsafe(Y,Et,Bt)?.toAffine();return Pt?i(Pt.x)===et:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:K,verify:ht,ProjectivePoint:c,Signature:h,utils:w}}function Dg(r){return{hash:r,hmac:(t,...e)=>sc(r,t,Qi(...e)),randomBytes:Nr}}function bf(r,t){let e=n=>wf({...r,...Dg(n)});return{...e(t),create:e}}var Ef=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),xf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),kg=BigInt(1),ac=BigInt(2),vf=(r,t)=>(r+t/ac)/t;function Rg(r){let t=Ef,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=st(u,e,t)*u%t,d=st(f,e,t)*u%t,m=st(d,ac,t)*l%t,p=st(m,o,t)*m%t,g=st(p,s,t)*p%t,h=st(g,a,t)*g%t,w=st(h,c,t)*h%t,x=st(w,a,t)*g%t,y=st(x,e,t)*u%t,E=st(y,i,t)*p%t,_=st(E,n,t)*l%t,L=st(_,ac,t);if(!cc.eql(cc.sqr(L),r))throw new Error("Cannot find square root");return L}var cc=Re(Ef,void 0,void 0,{sqrt:Rg}),Ht=bf({a:BigInt(0),b:BigInt(7),Fp:cc,n:xf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=xf,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-kg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=vf(s*r,t),c=vf(-n*r,t),l=J(r-a*e-c*o,t),u=J(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},Ur),L2=BigInt(0);var D2=Ht.ProjectivePoint;function lc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Sf(r,t){let e=Or.digest(t instanceof Uint8Array?t:t.subarray());if(lc(e))return e.then(({digest:n})=>Ht.sign(n,r).toDERRawBytes()).catch(n=>{throw new Tn(String(n))});try{return Ht.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Tn(String(n))}}function Af(r,t,e){let n=Or.digest(e instanceof Uint8Array?e:e.subarray());if(lc(n))return n.then(({digest:o})=>Ht.verify(t,o,r)).catch(o=>{throw new Pn(String(o))});try{return Ht.verify(t,n.digest,r)}catch(o){throw new Pn(String(o))}}var kn=class{type="secp256k1";raw;_key;constructor(t){this._key=Cf(t),this.raw=_f(this._key)}toMultihash(){return de.digest(se(this))}toCID(){return ut.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:rt(this.raw,t.raw)}verify(t,e){return Af(this._key,e,t)}},Zo=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=If(t),this.publicKey=new kn(e??Tf(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:rt(this.raw,t.raw)}sign(t){return Sf(this.raw,t)}};function uc(r){return new kn(r)}async function Pf(){let r=Ng();return new Zo(r)}function _f(r){return Ht.ProjectivePoint.fromHex(r).toRawBytes(!0)}function If(r){try{return Ht.getPublicKey(r,!0),r}catch(t){throw new un(String(t))}}function Cf(r){try{return Ht.ProjectivePoint.fromHex(r),r}catch(t){throw new Er(String(t))}}function Tf(r){try{return Ht.getPublicKey(r,!0)}catch(t){throw new un(String(t))}}function Ng(){return Ht.utils.randomPrivateKey()}async function Lf(r,t){if(r==="Ed25519")return Ku();if(r==="secp256k1")return Pf();if(r==="RSA")return oc(t??2048);throw new Ie}function zr(r,t){let{Type:e,Data:n}=ie.decode(r),o=n??new Uint8Array;switch(e){case mt.RSA:return nc(o,t);case mt.Ed25519:return ga(o);case mt.secp256k1:return uc(o);default:throw new Ie}}function Df(r){let{Type:t,Data:e}=ie.decode(r.digest),n=e??new Uint8Array;switch(t){case mt.Ed25519:return ga(n);case mt.secp256k1:return uc(n);default:throw new Ie}}function se(r){return ie.encode({Type:mt[r.type],Data:r.raw})}var kf=Symbol.for("nodejs.util.inspect.custom"),Mg=114,Rn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[po]=!0;toString(){return this.string==null&&(this.string=G.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ut.createV1(Mg,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return rt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return rt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[kf](){return`PeerId(${this.toString()})`}},Nn=class extends Rn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Mn=class extends Rn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Bn=class extends Rn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Bg=2336,On=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=de.digest(k(this.url))}[kf](){return`PeerId(${this.url})`}[po]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ut.createV1(Bg,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=B(t)),t.toString()===this.toString())}};var Og=114,Rf=2336;function ae(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=qt(G.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Fn(ut.parse(r));if(t==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=qt(t.decode(r))}return Vr(e)}function fc(r){if(r.type==="Ed25519")return new Mn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Bn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Nn({multihash:r.toCID().multihash,publicKey:r});throw new Ie}function Nf(r){return fc(r.publicKey)}function Vr(r){if(Ug(r))return new Nn({multihash:r});if(Fg(r))try{let t=Df(r);if(t.type==="Ed25519")return new Mn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Bn({multihash:r,publicKey:t})}catch{let e=B(r.digest);return new On(new URL(e))}throw new wo("Supplied PeerID Multihash is invalid")}function Fn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Og&&r.code!==Rf)throw new yo("Supplied PeerID CID is invalid");if(r.code===Rf){let t=B(r.multihash.digest);return new On(new URL(t))}return Vr(r.multihash)}function Fg(r){return r.code===de.code}function Ug(r){return r.code===Or.code}var ft=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var hc=ln(Bf(),1);var Kn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},pc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Of=r=>globalThis.DOMException===void 0?new pc(r):new DOMException(r),Ff=r=>{let t=r.reason===void 0?Of("This operation was aborted."):r.reason;return t instanceof Error?t:Of(t)};function qn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:m}=t;m.aborted&&f(Ff(m)),a=()=>{f(Ff(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Kn;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}function mc(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var zn=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,id:e.id,run:t};if(this.size===0||this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=mc(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}setPriority(t,e){let n=this.#t.findIndex(s=>s.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[o]=this.#t.splice(n,1);this.enqueue(o.run,{priority:e,id:t})}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var Fe=class extends hc.default{#t;#e;#r=0;#a;#c;#p=0;#o;#l;#n;#m;#s=0;#u;#i;#g;#b=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:zn,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=t.interval,this.#n=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#x(){return this.#e||this.#r<this.#a}get#v(){return this.#s<this.#u}#E(){this.#s--,this.#f(),this.emit("next")}#S(){this.#w(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#o===void 0){let e=this.#p-t;if(e<0)this.#r=this.#t?this.#s:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#S()},e)),!0}return!1}#f(){if(this.#n.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 t=!this.#A;if(this.#x&&this.#v){let e=this.#n.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#r===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#t?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#d()}async#_(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#n.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#b++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=qn(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#_(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof Kn&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#E()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#d(),this):this}pause(){this.#i=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#h("empty")}async onSizeLessThan(t){this.#n.size<t||await this.#h("next",()=>this.#n.size<t)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#h("idle")}async#h(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#n.size}sizeBy(t){return this.#n.filter(t).length}get pending(){return this.#s}get isPaused(){return this.#i}};function Yo(r){let t=[Vt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var gc=60;function Qo(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(t=>({name:t.name,type:Vt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Vt[t.type],TTL:t.TTL??t.ttl??gc,data:t.data instanceof Uint8Array?B(t.data):t.data}))}}var zg=4;function yc(r,t={}){let e=new Fe({concurrency:t.queryConcurrency??zg});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Yo(o.types).forEach(a=>{s.append("type",Vt[a])}),o.onProgress?.(new ft("dns:query",{detail:n}));let i=await e.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=Qo(await a.json());return o.onProgress?.(new ft("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Uf(){return[yc("https://cloudflare-dns.com/dns-query"),yc("https://dns.google/resolve")]}var zf=ln(qf(),1);var wc=class{lru;constructor(t){this.lru=(0,zf.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Qo({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,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:Vt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??gc)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Vf(r){return new wc(r)}var Vg=1e3,Jo=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Vf(t.cacheSize??Vg),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Uf())}async query(t,e={}){let n=Yo(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new ft("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new ft("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Vt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Vt||(Vt={}));function $f(r={}){return new Jo(r)}var ts=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,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,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hf=45,$g=15,$r=new ts;function es(r){if(!(r.length>$g))return $r.new(r).parseWith(()=>$r.readIPv4Addr())}function rs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hf))return $r.new(r).parseWith(()=>$r.readIPv6Addr())}function rr(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Hf)return;let e=$r.new(r).parseWith(()=>$r.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function Gf(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function Wf(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function bc(r){switch(r.length){case nr:return r.join(".");case or:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function Xf(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function Zf(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var nr=4,or=16,dE=parseInt("0xFFFF",16),Hg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Vn(r,t){t.length===or&&r.length===nr&&Gf(t,0,11)&&(t=t.slice(12)),t.length===nr&&r.length===or&&Wf(r,Hg,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function jf(r,t){if(typeof t=="string"&&(t=rr(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function xc(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=nr,o=es(t);if(o==null&&(n=or,o=rs(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=vc(s,8*n);return{network:Vn(o,i),mask:i}}function vc(r,t){if(t!==8*nr&&t!==8*or)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Hr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=xc(t));else{let n=rr(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=rr(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=vc(o,8*n.length);this.network=Vn(n,this.mask)}}contains(t){return jf({network:this.network,mask:this.mask},t)}toString(){let t=Xf(this.mask),e=t!==-1?String(t):Zf(this.mask);return bc(this.network)+"/"+e}};function te(r){return!!es(r)}function Gr(r){return!!rs(r)}function ns(r){return!!rr(r)}var Yf=te,Gg=Gr,Ec=function(r){let t=0;if(r=r.toString().trim(),Yf(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Gg(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Yf(e[n]),i;s&&(i=Ec(e[n]),e[n]=B(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,B(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Qf=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Wr={},Sc={},Xg=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Xg.forEach(r=>{let t=Zg(...r);Sc[t.code]=t,Wr[t.name]=t});function Zg(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function $(r){if(typeof r=="number"){if(Sc[r]!=null)return Sc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Wr[r]!=null)return Wr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var jg=$("ip4"),Yg=$("ip6"),Qg=$("ipcidr");function Cc(r,t){switch($(r).code){case 4:case 41:return t0(t);case 42:return Ic(t);case 43:return B(t,"base10");case 6:case 273:case 33:case 132:return ed(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ic(t);case 421:return o0(t);case 444:return td(t);case 445:return td(t);case 466:return n0(t);case 481:return globalThis.encodeURIComponent(Ic(t));default:return B(t,"base16")}}function Tc(r,t){switch($(r).code){case 4:return Jf(t);case 41:return Jf(t);case 42:return _c(t);case 43:return k(t,"base10");case 6:case 273:case 33:case 132:return Lc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return _c(t);case 421:return e0(t);case 444:return s0(t);case 445:return i0(t);case 466:return r0(t);case 481:return _c(globalThis.decodeURIComponent(t));default:return k(t,"base16")}}function Pc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===jg.code||n===Yg.code)&&(e=o),n===Qg.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new Hr(e,t)}var Ac=Object.values(Sn).map(r=>r.decoder),Jg=function(){let r=Ac[0].or(Ac[1]);return Ac.slice(2).forEach(t=>r=r.or(t)),r}();function Jf(r){if(!ns(r))throw new Error("invalid ip address");return Ec(r)}function t0(r){let t=Qf(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ns(t))throw new Error("invalid ip address");return t}function Lc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ed(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function _c(r){let t=k(r),e=Uint8Array.from(_t(t.length));return Nt([e,t],e.length+t.length)}function Ic(r){let t=Qt(r);if(r=r.slice(dt(t)),r.length!==t)throw new Error("inconsistent lengths");return B(r)}function e0(r){let t;r[0]==="Q"||r[0]==="1"?t=qt(G.decode(`z${r}`)).bytes:t=ut.parse(r).multihash.bytes;let e=Uint8Array.from(_t(t.length));return Nt([e,t],e.length+t.length)}function r0(r){let t=Jg.decode(r),e=Uint8Array.from(_t(t.length));return Nt([e,t],e.length+t.length)}function n0(r){let t=Qt(r),e=r.slice(dt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+B(e,"base64url")}function o0(r){let t=Qt(r),e=r.slice(dt(t));if(e.length!==t)throw new Error("inconsistent lengths");return B(e,"base58btc")}function s0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Kt.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Lc(n);return Nt([e,o],e.length+o.length)}function i0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Kt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Lc(n);return Nt([e,o],e.length+o.length)}function td(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=B(t,"base32"),o=ed(e);return`${n}:${o}`}function rd(r){r=Dc(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=$(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new os("invalid address: "+r);if(a.path===!0){n=Dc(o.slice(s).join("/")),t.push([a.code,Tc(a.code,n)]),e.push([a.code,n]);break}let c=Tc(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Cc(a.code,c)])}return{string:nd(e),bytes:ss(t),tuples:t,stringTuples:e,path:n}}function kc(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Qt(r,o),i=dt(s),a=$(s),c=a0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new os("Invalid address Uint8Array: "+B(r,"base16"));t.push([s,l]);let u=Cc(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:nd(e),tuples:t,stringTuples:e,path:n}}function nd(r){let t=[];return r.map(e=>{let n=$(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Dc(t.join("/"))}function ss(r){return Nt(r.map(t=>{let e=$(t[0]),n=Uint8Array.from(_t(e.code));return t.length>1&&t[1]!=null&&(n=Nt([n,t[1]])),n}))}function a0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Qt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+dt(e)}}function Dc(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var os=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var c0=Symbol.for("nodejs.util.inspect.custom"),Nc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),l0=[$("dns").code,$("dns4").code,$("dns6").code,$("dnsaddr").code],Rc=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},is=class r{bytes;#t;#e;#r;#a;[Nc]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=kc(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=rd(t)}else if(Ue(t))e=kc(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=$("tcp"),a=$("udp"),c=$("ip4"),l=$("ip6"),u=$("dns6"),f=$("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(s=`%${p??""}`),l0.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${p??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=$(m).name==="tcp"?"tcp":"udp",o=parseInt(p??"")),(m===c.code||m===l.code)&&(e=$(m).name==="tcp"?"tcp":"udp",n=`${p??""}${s}`,t=m===l.code?6:4);if(t==null||e==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:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},$(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>$(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(ss(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Wr.p2p.code&&t.push([n,o]),n===Wr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?B(G.decode(`z${n}`),"base58btc"):B(ut.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return rt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Xr.get(e.name);if(n==null)throw new Rc(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>W(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[c0](){return`Multiaddr(${this.#t})`}};var Xr=new Map;function Ue(r){return!!r?.[Nc]}function W(r){return new is(r)}var u0=32,{code:f0}=$("dnsaddr"),Mc=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},sr=async function(t,e={}){let n=e.maxRecursiveDepth??u0;if(n===0)throw new Mc("Max recursive depth reached");let[,o]=t.stringTuples().find(([l])=>l===f0)??[],i=await(e?.dns??$f()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Vt.TXT]}),a=t.getPeerId(),c=[];for(let l of i.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let f=W(u);if(u.startsWith("/dnsaddr")){let d=await f.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var dd=ln(fd(),1),ls=dd.default;var y0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:sr}},transportManager:{faultTolerance:$e.FATAL_ALL}};async function hd(r){let t=ls(y0,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return t}function w0(r,t){try{if(typeof r=="string"&&r.length>0)return b0(r);if(typeof r=="number"&&isFinite(r))return t?.long?v0(r):x0(r);throw new Error("Value is not a string or number.")}catch(e){let n=E0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function b0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var fs=w0;function x0(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function v0(r){let t=Math.abs(r);return t>=864e5?us(r,t,864e5,"day"):t>=36e5?us(r,t,36e5,"hour"):t>=6e4?us(r,t,6e4,"minute"):t>=1e3?us(r,t,1e3,"second"):`${r} ms`}function us(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function E0(r){return typeof r=="object"&&r!==null&&"message"in r}function Oc(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=fs,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let w=g,x=Number(new Date),y=x-(f||x);w.diff=y,w.prev=f,w.curr=x,f=x,h[0]=e.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let E=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(L,I)=>{if(L==="%%")return"%";E++;let P=e.formatters[I];if(typeof P=="function"){let T=h[E];L=P.call(w,T),h.splice(E,1),E--}return L}),e.formatArgs.call(w,h),(w.log||e.log).apply(w,h)}return g.namespace=u,g.useColors=e.useColors(),g.color=e.selectColor(u),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==e.namespaces&&(m=e.namespaces,p=e.enabled(u)),p),set:h=>{d=h}}),typeof e.init=="function"&&e.init(g),g}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.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 e.setupFormatters(e.formatters),e.enable(e.load()),e}var ds=P0(),S0=["#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 A0(){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 _0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+fs(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var I0=console.debug??console.log??(()=>{});function C0(r){try{r?ds?.setItem("debug",r):ds?.removeItem("debug")}catch{}}function T0(){let r;try{r=ds?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function P0(){try{return localStorage}catch{}}function L0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var pd=Oc({formatArgs:_0,save:C0,load:T0,useColors:A0,setupFormatters:L0,colors:S0,storage:ds,log:I0});var Ut=pd;Ut.formatters.b=r=>r==null?"undefined":G.baseEncode(r);Ut.formatters.t=r=>r==null?"undefined":Kt.baseEncode(r);Ut.formatters.m=r=>r==null?"undefined":ka.baseEncode(r);Ut.formatters.p=r=>r==null?"undefined":r.toString();Ut.formatters.c=r=>r==null?"undefined":r.toString();Ut.formatters.k=r=>r==null?"undefined":r.toString();Ut.formatters.a=r=>r==null?"undefined":r.toString();Ut.formatters.e=r=>r==null?"undefined":md(r.stack)??md(r.message)??r.toString();function D0(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function hs(){return{forComponent(r){return k0(r)}}}function k0(r){let t=D0(`${r}:trace`);return Ut.enabled(`${r}:trace`)&&Ut.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Ut(`${r}:trace`)),Object.assign(Ut(r),{error:Ut(`${r}:error`),trace:t})}function md(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function ir(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function ps(r){let t=qt(G.decode(`z${r}`));return Vr(t)}var be=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return ir(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return ir(this.map.values(),t=>t.key)}values(){return ir(this.map.values(),t=>t.value)}get size(){return this.map.size}};var ar=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return ir(this.set.entries(),t=>{let e=ps(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=ps(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ir(this.set.values(),t=>ps(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var Fc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},gd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},yd=new globalThis.TextEncoder;function R0(r,t){let e=Fc[t],n=gd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function N0(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fc[t],o=gd[t],s=r;for(;s.length>0;){let i=yd.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Uc(r,{size:t=32,utf8Buffer:e}={}){if(!Fc[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return N0(r,t,e);r=yd.encode(r)}return R0(r,t)}var $n={hash:r=>Number(Uc(r,{size:32})),hashV:(r,t)=>M0($n.hash(r,t))};function M0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var Kc=64,ee=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Kc)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=lt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?rt(this.fp,t.fp):!1}};function cr(r,t){return Math.floor(Math.random()*(t-r))+r}var lr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");let e=cr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var B0=500,Hn=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??$n,this.seed=t.seed??cr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=k(t));let e=new ee(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new lr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new lr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize));for(let a=0;a<B0;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=k(t));let e=new ee(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=k(t));let e=new ee(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},O0={1:.5,2:.84,4:.95,8:.98};function F0(r=.001){return r>.002?2:r>1e-5?4:8}function wd(r,t=.001){let e=F0(t),n=O0[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Kc);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var ms=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??$n,this.seed=t.seed??cr(0,Math.pow(2,10)),this.filterSeries=[new Hn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=k(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Hn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=k(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=k(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Gn(r,t=.001,e){return new ms({...wd(r,t),...e??{}})}var Wn;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:lt(0),payloadType:lt(0),payload:lt(0),signature:lt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Wn||(Wn={}));var gs=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Yr=class r{static createFromProtobuf=async t=>{let e=Wn.decode(t),n=zr(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=bd(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new gs("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Wn.encode({publicKey:se(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return rt(this.marshal(),t.marshal())}async validate(t){let e=bd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},bd=(r,t,e)=>{let n=k(r),o=_t(n.byteLength),s=_t(t.length),i=_t(e.length);return new Q(o,n,s,t,i,e)};function xd(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var vd="libp2p-peer-record",Ed=Uint8Array.from([3,1]);var Xn;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Rt((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:lt(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=>kt(s,n.codec()),n.decode=(s,i)=>Dt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Rt((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:lt(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 er('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})),e),r.encode=n=>kt(n,r.codec()),r.decode=(n,o)=>Dt(n,r.codec(),o)})(Xn||(Xn={}));var ur=class r{static createFromProtobuf=t=>{let e=Xn.decode(t),n=Vr(qt(e.peerId)),o=(e.addresses??[]).map(i=>W(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=vd;static CODEC=Ed;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Xn.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!xd(this.multiaddrs,t.multiaddrs))}};function U0(r){return r[Symbol.asyncIterator]!=null}function K0(r){if(U0(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var Zn=K0;var Ke={},Qr=r=>{r.addEventListener("message",t=>{Qr.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{Qr.dispatchEvent("message",r,t)})};Qr.addEventListener=(r,t)=>{Ke[r]==null&&(Ke[r]=[]),Ke[r].push(t)};Qr.removeEventListener=(r,t)=>{Ke[r]!=null&&(Ke[r]=Ke[r].filter(e=>e===t))};Qr.dispatchEvent=function(r,t,e){Ke[r]!=null&&Ke[r].forEach(n=>n(t,e))};var qc=Qr;var zc="lock:worker:request-read",Vc="lock:worker:release-read",$c="lock:master:grant-read",Hc="lock:worker:request-write",Gc="lock:worker:release-write",Wc="lock:master:grant-write";var Sd=(r=21)=>Math.random().toString().substring(2);var Ad=(r,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)})}}}))},_d=(r,t,e,n)=>async()=>{let o=Sd();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},q0={singleProcess:!1},Id=r=>{if(r=Object.assign({},q0,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return qc.addEventListener("message",Ad(e,"requestReadLock",zc,Vc,$c)),qc.addEventListener("message",Ad(e,"requestWriteLock",Hc,Gc,Wc)),e}return{isWorker:!0,readLock:e=>_d(e,zc,$c,Vc),writeLock:e=>_d(e,Hc,Wc,Gc)}};var fr={},qe;async function Xc(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>qn((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var z0=(r,t)=>{if(qe.isWorker===!0)return{readLock:qe.readLock(r,t),writeLock:qe.writeLock(r,t)};let e=new Fe({concurrency:1}),n;return{async readLock(){if(n!=null)return Xc(n,t);n=new Fe({concurrency:t.concurrency,autoStart:!1});let o=n,s=Xc(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Xc(e,t)}}},V0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Zc(r){let t=Object.assign({},V0,r);return qe==null&&(qe=Id(t),qe.isWorker!==!0&&(qe.addEventListener("requestReadLock",e=>{fr[e.data.name]!=null&&fr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),qe.addEventListener("requestWriteLock",async e=>{fr[e.data.name]!=null&&fr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),fr[t.name]==null&&(fr[t.name]=z0(t.name,t)),fr[t.name]}var xe;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Rt((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:lt(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=>kt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Rt((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),ws.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=ws.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>kt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Rt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),ys.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 er('Decode error - map field "addresses" had too many elements');a.addresses.push(ys.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 er('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 In('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 In('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=>kt(o,r.codec()),r.decode=(o,s)=>Dt(o,r.codec(),s)})(xe||(xe={}));var ys;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:lt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ys||(ys={}));var ws;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>kt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ws||(ws={}));function $0(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=G.decode(`z${r}`);e=qt(o)}let n=zr(t.publicKey,e);return fc(n)}function bs(r,t,e){let n=xe.decode(t);return xs(r,n,e)}function xs(r,t,e){let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:$0(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:W(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function Cd(r,t){return H0(r.addresses,t.addresses)&&G0(r.protocols,t.protocols)&&W0(r.publicKey,t.publicKey)&&X0(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Z0(r.metadata,t.metadata)&&j0(r.tags,t.tags)}function H0(r,t){return Pd(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!rt(e.multiaddr,n.multiaddr)))}function G0(r,t){return Pd(r,t,(e,n)=>e===n)}function W0(r,t){return Td(r,t)}function X0(r,t){return Td(r,t)}function Z0(r,t){return Ld(r,t,(e,n)=>rt(e,n))}function j0(r,t){return Ld(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function Td(r,t){return r==null&&t==null?!0:r!=null&&t!=null?rt(r,t):!1}function Pd(r,t,e){if(r.length!==t.length)return!1;for(let n=0;n<r.length;n++)if(!e(r[n],t[n]))return!1;return!0}function Ld(r,t,e){if(r.size!==t.size)return!1;for(let[n,o]of r.entries()){let s=t.get(n);if(s==null||!e(o,s))return!1}return!0}var ve="/",Dd=new TextEncoder().encode(ve),vs=Dd[0],dr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=k(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==vs)throw new Error("Invalid key")}toString(t="utf8"){return B(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(ve))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Dd),this._buf[0]!==vs){let t=new Uint8Array(this._buf.byteLength+1);t.fill(vs,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===vs;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(ve).slice(1)}type(){return Y0(this.baseNamespace())}name(){return Q0(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(ve)||(t+=ve),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(ve):new r(t.slice(0,-1).join(ve))}child(t){return this.toString()===ve?t:t.toString()===ve?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...J0(t.map(e=>e.namespaces()))])}};function Y0(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Q0(r){let t=r.split(":");return t[t.length-1]}function J0(r){return[].concat(...r)}var jc="/peers/";function jn(r){if(!mo(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new dr(`${jc}${t}`)}async function kd(r,t,e,n){let o=new Map;for(let s of e){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=W(s.multiaddr)),!Ue(s.multiaddr))throw new R("Multiaddr was invalid");if(!await t(r,s.multiaddr))continue;let i=s.isCertified??!1,a=s.multiaddr.toString(),c=o.get(a);c!=null?s.isCertified=c.isCertified||i:o.set(a,{multiaddr:s.multiaddr,isCertified:i})}return[...o.values()].sort((s,i)=>s.multiaddr.toString().localeCompare(i.multiaddr.toString())).map(({isCertified:s,multiaddr:i})=>({isCertified:s,multiaddr:i.bytes}))}async function Ss(r,t,e,n){if(t==null)throw new R("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new R("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(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Es(d,{validate:Rd})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Es(d,{validate:Nd,map:Md})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[m,p]of d)p==null?a.delete(m):a.set(m,p);a=Es([...a.entries()],{validate:Rd})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),m=new Map(c);for(let[p,g]of d)g==null?m.delete(p):m.set(p,g);c=Es([...m.entries()],{validate:Nd,map:Md})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=se(o.id.publicKey):t.publicKey!=null?u=se(t.publicKey):r.publicKey!=null&&(u=se(r.publicKey));let f={addresses:await kd(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(m=>rt(m.multiaddr,m.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Es(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function Rd(r,t){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function Nd(r,t){if(typeof r!="string")throw new R("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new R("Tag value must be an integer");if(t.value<0||t.value>100)throw new R("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new R("Tag ttl must be an integer");if(t.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Md(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Bd(r){let t=r.toString().split("/")[2],e=ut.parse(t,Kt);return Fn(e)}function Yc(r,t,e){let n=Bd(r);return bs(n,t,e)}function ty(r,t){return{prefix:jc,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Yc(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Yc(n.key,n.value,t),Yc(o.key,o.value,t)))}}var As=class{peerId;datastore;lock;addressFilter;log;maxAddressAge;maxPeerAge;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=Zc({name:"peer-store",singleProcess:!0}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}async has(t){try{return await this.load(t),!0}catch(e){if(e.name!=="NotFoundError")throw e}return!1}async delete(t){this.peerId.equals(t)||await this.datastore.delete(jn(t))}async load(t){let e=jn(t),n=await this.datastore.get(e),o=xe.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new He;return xs(t,o,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e){let n=await this.#t(t),o=await Ss(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,o,n)}async patch(t,e){let n=await this.#t(t),o=await Ss(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#e(t,o,n)}async merge(t,e){let n=await this.#t(t),o=await Ss(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#e(t,o,n)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(ty(t??{},this.maxAddressAge))){let o=Bd(e);if(o.equals(this.peerId))continue;let s=xe.decode(n);if(this.#r(o,s)){await this.datastore.delete(e);continue}yield xs(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t){try{let e=jn(t),n=await this.datastore.get(e),o=xe.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new He;return{peerPB:o,peer:bs(t,n,this.maxAddressAge)}}catch(e){e.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",e)}}async#e(t,e,n){e.updated=Date.now();let o=xe.encode(e);return await this.datastore.put(jn(t),o),{peer:bs(t,o,this.maxAddressAge),previous:n?.peer,updated:n==null||!Cd(e,n.peerPB)}}#r(t,e){if(e.updated==null)return!0;if(this.peerId.equals(t))return!1;let n=e.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=e.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Qc=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new As(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Zn(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),e()}}async has(t){this.log.trace("has await read lock");let e=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),e()}}async get(t){this.log.trace("get await read lock");let e=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),e()}}async save(t,e){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await Yr.openAndCertify(t,ur.DOMAIN),o=Fn(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=ur.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await Yr.createFromProtobuf(i.peerRecordEnvelope),c=ur.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function Od(r,t={}){return new Qc(r,t)}var _s=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function ey(r){return r[Symbol.asyncIterator]!=null}function ry(r){if(ey(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Jc=ry;function ny(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Fd=ny;function oy(r){return r[Symbol.asyncIterator]!=null}function sy(r,t){let e=0;if(oy(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Fd(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var hr=sy;function iy(r){return r[Symbol.asyncIterator]!=null}function ay(r,t){return iy(r)?async function*(){yield*(await Zn(r)).sort(t)}():function*(){yield*Zn(r).sort(t)}()}var tl=ay;function cy(r){return r[Symbol.asyncIterator]!=null}function ly(r,t){return cy(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var el=ly;var Is=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await Jc(this.putMany(t,n)),t=[],await Jc(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=hr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>hr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=hr(n,()=>o++>=s)}return t.limit!=null&&(n=el(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=hr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>hr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=hr(n,()=>s++>=o)}return t.limit!=null&&(n=el(n,t.limit)),n}};var Cs=class extends Is{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new _s;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new dr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new dr(t)}};function Ud(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var qd=ln(Kd(),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 qd.Netmask(r));function rl(r){for(let t of fy)if(t.contains(r))return!0;return!1}function dy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function hy(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return rl(o)}function py(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function my(r){let t=r.split(":"),e=t[t.length-1];return rl(e)}function gy(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 ze(r){return te(r)?rl(r):dy(r)?hy(r):py(r)?my(r):Gr(r)?gy(r):void 0}var yy=r=>r.toString().split("/").slice(1),Jr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>Jr(e=>e===r).match(t),pattern:r}),pr=()=>({match:r=>Jr(t=>typeof t=="string").match(r),pattern:"{string}"}),Qn=()=>({match:r=>Jr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),tt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{G.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Jn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ra.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Tt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),V=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function at(...r){function t(o){let s=yy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Ps=V(z("dns4"),pr()),Ls=V(z("dns6"),pr()),Ds=V(z("dnsaddr"),pr()),ol=V(z("dns"),pr()),_6=at(Ps,Z(tt())),I6=at(Ls,Z(tt())),C6=at(Ds,Z(tt())),T6=at(Tt(ol,Ds,Ps,Ls),Z(tt())),zd=V(z("ip4"),Jr(te)),Vd=V(z("ip6"),Jr(Gr)),sl=Tt(zd,Vd),Ee=Tt(sl,ol,Ps,Ls,Ds),P6=at(Tt(sl,V(Tt(ol,Ds,Ps,Ls),Z(tt())))),il=at(zd),al=at(Vd),L6=at(sl),cl=V(Ee,z("tcp"),Qn()),to=V(Ee,z("udp"),Qn()),eo=at(V(cl,Z(tt()))),D6=at(to),ll=V(to,z("quic"),Z(tt())),ks=V(to,z("quic-v1"),Z(tt())),wy=Tt(ll,ks),k6=at(ll),$d=at(ks),nl=Tt(Ee,cl,to,ll,ks),Hd=Tt(V(nl,z("ws"),Z(tt()))),mr=at(Hd),Gd=Tt(V(nl,z("wss"),Z(tt())),V(nl,z("tls"),Z(V(z("sni"),pr())),z("ws"),Z(tt()))),ro=at(Gd),Wd=V(to,z("webrtc-direct"),Z(Jn()),Z(Jn()),Z(tt())),ul=at(Wd),Xd=V(ks,z("webtransport"),Z(Jn()),Z(Jn()),Z(tt())),fl=at(Xd),Ts=Tt(Hd,Gd,V(cl,Z(tt())),V(wy,Z(tt())),V(Ee,Z(tt())),Wd,Xd,tt()),R6=at(Ts),by=V(Ts,z("p2p-circuit"),tt()),no=at(by),xy=Tt(V(Ts,z("p2p-circuit"),z("webrtc"),Z(tt())),V(Ts,z("webrtc"),Z(tt())),V(z("webrtc"),Z(tt()))),dl=at(xy),vy=Tt(V(Ee,z("tcp"),Qn(),z("http"),Z(tt())),V(Ee,z("http"),Z(tt()))),N6=at(vy),Ey=Tt(V(Ee,z("tcp"),Tt(V(z("443"),z("http")),V(Qn(),z("https"))),Z(tt())),V(Ee,z("tls"),z("http"),Z(tt())),V(Ee,z("https"),Z(tt()))),M6=at(Ey),Sy=Tt(V(z("memory"),pr(),Z(tt()))),B6=at(Sy);var Zd=864e13;var Ay=448,hl=449,_y=53,Iy=54,Cy=55,Ty=56,Rs=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(t){let e=this.findHost(t);for(let n of this.mappings.values())if(n.domain===e)return!0;return!1}add(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t);let o=ze(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?Zd-Date.now():0,lastVerified:o?Zd-Date.now():void 0})})}remove(t){let e=this.findHost(t),n=!1;for(let[o,s]of this.mappings.entries())s.domain===e&&(this.log("removing %s to %s DNS mapping %e",o,s.domain,new Error("where")),this.mappings.delete(o),n=n||s.verified);return n}getAll(t){let e=[];for(let n=0;n<t.length;n++){let s=t[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)&&(t.splice(n,1),n--,e.push({multiaddr:W(`/${s.map(u=>[$(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===Ay&&t[n+1]?.[0]!==hl)return t.splice(n+1,0,[hl,e]),!0;return!1}confirm(t,e){let n=this.findHost(t),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()+e,i.lastVerified=Date.now());return o}unconfirm(t,e){let n=this.findHost(t),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()+e);return o}findHost(t){for(let e of t.stringTuples())if(e[0]===hl||e[0]===_y||e[0]===Iy||e[0]===Cy||e[0]===Ty)return e[1]}};var pl=4,ml=41,gl=6,Py=273,Ns=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(t){let e=t.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===e[0][1])return!0;return!1}add(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${s}`,a=this.mappings.get(i)??[],c={internalIp:t,internalPort:e,externalIp:n,externalPort:o,externalFamily:te(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(t){let e=t.stringTuples(),n=e[0][1]??"",o=e[1][0]===gl?"tcp":"udp",s=parseInt(e[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(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===pl||o[0][0]===ml)&&o[1][0]===gl?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===pl||o[0][0]===ml)&&o[1][0]===Py&&(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?pl:ml,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:W(`/${o.map(c=>[$(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return e}confirm(t,e){let o=t.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()+e,a.lastVerified=Date.now());return s}unconfirm(t,e){let n=t.stringTuples(),o=n[0][1]??"",s=n[1][0]===gl?"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()+e)}return a}};function jd(r){try{let[[t,e]]=r.stringTuples();if(e==null)return!1;if(t===4)return e.startsWith("169.254.");if(t===41)return e.toLowerCase().startsWith("fe80")}catch{}return!1}function Ms(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function gr(r){try{if(!Ms(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:ze(t)??!1}catch{}return!0}var Ly={maxObservedAddresses:10},Bs=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=e.maxObservedAddresses??Ly.maxObservedAddresses}has(t){return this.addresses.has(t.toString())}removePrefixed(t){for(let e of this.addresses.keys())e.toString().startsWith(t)&&this.addresses.delete(e)}add(t){this.addresses.size!==this.maxObservedAddresses&&(gr(t)||jd(t)||(this.log("adding observed address %a",t),this.addresses.set(t.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([t,e])=>({multiaddr:W(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){let e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){let n=t.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Dy=[4,41,53,54,55,56];function yl(r){try{let[[t]]=r.stringTuples();return Dy.includes(t)}catch{}return!1}var ky={maxObservedAddresses:10},Os=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=e.maxObservedAddresses??ky.maxObservedAddresses}get(t,e){if(gr(t))return{multiaddr:t,verified:!0,type:"transport",expires:Date.now()+e,lastVerified:Date.now()};let n=this.toKey(t),o=this.addresses.get(n);return o==null&&(o={verified:!yl(t),expires:0},this.addresses.set(n,o)),{multiaddr:t,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(t){let e=this.toKey(t);return this.addresses.has(e)}remove(t){let e=this.toKey(t),n=this.addresses.get(e)?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(e),n}confirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+e,this.addresses.set(n,o),s}toKey(t){if(yl(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Yd=6e4,Qd={maxObservedAddresses:10,addressVerificationTTL:Yd*10,addressVerificationRetry:Yd*5},Ry=r=>r;function wl(r,t){let e=r.getPeerId();return e!=null&&ae(e).equals(t)&&(r=r.decapsulate(W(`/p2p/${t.toString()}`))),r}var Fs=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.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 Bs(t,e),this.dnsMappings=new Rs(t,e),this.ipMappings=new Ns(t,e),this.transportAddresses=new Os(t,e),this.announceFilter=e.announceFilter??Ry,this.observedAddressFilter=Gn(1024),this.addressVerificationTTL=e.addressVerificationTTL??Qd.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Qd.addressVerificationRetry,this._updatePeerStoreAddresses=Ud(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>W(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>W(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>W(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){let e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=wl(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=wl(t,this.components.peerId);let n=!0;(e?.type==="transport"||this.transportAddresses.has(t))&&!this.transportAddresses.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="dns-mapping"||this.dnsMappings.has(t))&&!this.dnsMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="ip-mapping"||this.ipMappings.has(t))&&!this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="observed"||this.observed.has(t))&&(this.maybeUpgradeToIPMapping(t)?(this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(t,e){t=wl(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let t=new Set,e=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return t.has(o)?!1:(t.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(e.map(n=>{let o=W(n);return o.protos().pop()?.path===!0||o.getPeerId()===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(t)}),t.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];return e=e.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),e=e.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))),e=e.concat(this.observed.getAll()),e=e.concat(this.ipMappings.getAll(e)),e=e.concat(this.dnsMappings.getAll(e)),e}addDNSMapping(t,e){this.dnsMappings.add(t,e)}removeDNSMapping(t){this.dnsMappings.remove(W(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${te(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(W(`/ip${te(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(t){if(this.ipMappings.has(t))return!1;let e=t.toOptions();if(e.family===6||e.host==="127.0.0.1"||ze(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>mr.exactMatch(s)||ro.exactMatch(s),s=>eo.exactMatch(s),s=>$d.exactMatch(s)];for(let s of o){if(!s(t))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(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var Jd;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Jd||(Jd={}));var Us=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Ks=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},tn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},oo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},qs=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},zs=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},Vs=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},so=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},$s=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Hs=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Gs=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Ws=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Xs=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},yr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},wr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Zs=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var bl=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=hs())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>So(e)).map(async e=>{await e[t]?.()}))}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")}},My=["metrics","connectionProtector","dns"],By=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function th(r={}){let t=new bl(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!By.includes(o)){let i=t.components[o];if(i==null&&!My.includes(o))throw new Us(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function eh(r){let t={};for(let e of Object.values(r.components))for(let n of Oy(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Fy(e))if(t[n]!==!0)throw new Ks(`Service "${Uy(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Oy(r){return Array.isArray(r?.[dn])?r[dn]:[]}function Fy(r){return Array.isArray(r?.[qi])?r[qi]:[]}function Uy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Ky=4,qy=41;function rh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(mr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===Ky||e[0][0]===qy?!!ze(`${e[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}}var nh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},zy=new WeakMap;function Vy({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(nh());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(nh())},u=()=>{o&&o.removeEventListener("abort",l)},f=new Promise((d,m)=>{i=()=>{u(),d(n)},a=m,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",l,{once:!0}),zy.set(f,()=>{c(s),s=null,i()}),f}}var $y=Vy(),oh=$y;var js=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},Ys=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Qs=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new xl}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new js("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await oh(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},xl=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function Js(r){if(mo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let t;if(r.length>0){let e=r[0].getPeerId();t=e==null?void 0:ae(e),r.forEach(n=>{if(!Ue(n))throw new _e("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let s=ae(o);if(t?.equals(s)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:t,multiaddrs:r}}var Hy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function sh(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Hy;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var ih="last-dial-failure",ah="last-dial-success";var ti=100,ei=50;async function ch(r,t){let e=!1;for(let o of Xr.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}function io(r){try{let t;if(typeof r=="string"?t=W(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return Pc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Gy={maxConnections:ti,allow:[]},ri=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??Gy.maxConnections,this.allow=(e.allow??[]).map(n=>io(n)),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.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(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new be;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((u,f)=>u+f.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await sh(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(t,e){return t.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=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function X(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ni=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},en=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ni(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new ni(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var vl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function lh(r={}){return Wy(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Wy(r,t){t=t??{};let e=t.onEnd,n=new en,o,s,i,a=X(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(y){w(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=X()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new en,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new en,d(),{done:!0}),p=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,y;w!=null&&(x=new Promise((E,_)=>{y=()=>{_(new vl)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var El=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function rn(r,t,e,n){let o=new El(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var oi=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function bt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new oi(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new oi(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var si=class{deferred;signal;constructor(t){this.signal=t,this.deferred=X(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Wt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ii=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Xy(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Wt),this.cleanup())}async join(t={}){let e=new si(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await bt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var on=class extends ue{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ys;let n=new ii(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).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("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Wt)}),this.clear()}async onEmpty(t){this.size!==0&&await rn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await rn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await rn(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=lh({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Wt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ai=class extends on{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Se(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function uh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Sl(r){if(!Ms(r))return!1;let{address:t}=r.nodeAddress();return uh(t)}function Zy(r,t){let e=eo.exactMatch(r.multiaddr),n=eo.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=ro.exactMatch(r.multiaddr),s=ro.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=mr.exactMatch(r.multiaddr),a=mr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=dl.exactMatch(r.multiaddr),l=dl.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=ul.exactMatch(r.multiaddr),f=ul.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=fl.exactMatch(r.multiaddr),m=fl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function jy(r,t){let e=Sl(r.multiaddr),n=Sl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Yy(r,t){let e=gr(r.multiaddr),n=gr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Qy(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Jy(r,t){let e=no.exactMatch(r.multiaddr),n=no.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function fh(r){return r.sort(Zy).sort(Qy).sort(Jy).sort(Yy).sort(jy)}var ci={maxParallelDials:ei,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:sr}},li=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??ci.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??ci.maxDialQueueLength,this.dialTimeout=e.dialTimeout??ci.dialTimeout,this.connections=e.connections??new be,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,o]of Object.entries(e.resolvers??{}))Xr.set(n,o);this.queue=new ai({concurrency:e.maxParallelDials??ci.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Wt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=Js(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new ft("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new ft("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new _r("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new ft("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new ft("dial-queue:start-dial"));let c=Se([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Cl,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.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(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let m of d){if(s.has(m.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",m.multiaddr,n);continue}u.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(m=>m.multiaddr.toString())),t?.onProgress?.(new ft("dial-queue:calculated-addresses",u));for(let m of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,t.peerId),new _r("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(m.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",m.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[ah]:k(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return p}catch(p){if(this.log.error("dial failed to %a",m.multiaddr,p),s.add(m.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[ih]:k(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new xo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:W(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new _r("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new so("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);o.push(...f.addresses),this.log("loaded multiaddrs for %p",t,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",t);try{let f=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,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",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await ch(f.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(m=>({multiaddr:m,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{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 t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),m=a.get(d);if(m!=null){m.isCertified=m.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Gs("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?fh(l):l.sort(this.addressSorter);if(u.length===0)throw new so("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!no.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ui=class extends on{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var wh=ln(gh(),1);var ew=Object.prototype.toString,rw=r=>ew.call(r)==="[object Error]",nw=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 Tl(r){return r&&rw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:nw.has(r.message):!1}var Pl=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},yh=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Ll(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=wh.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Pl)throw c.originalError;if(c instanceof TypeError&&!Tl(c))throw c;if(yh(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){yh(l,a,t),i(),n(l)}}})})}var fi=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new ui({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.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(t){if(!this.started)return;let e=await this.peerStore.get(t);bh(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Ll(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(Ki)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>bh(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function bh(r){for(let t of r.tags.keys())if(t.startsWith(Ki))return!0;return!1}var Cl=50,Dl={maxConnections:ti,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},di=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??Dl.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new be,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>io(n)),this.deny=(e.deny??[]).map(n=>io(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Dl.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Qs({points:e.inboundConnectionThreshold??Dl.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ri({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>W(n))}),this.dialQueue=new li(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??ei,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:sr},connections:this.connections}),this.reconnectQueue=new fi({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};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))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Ql(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 Jl(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),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:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new le("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=Js(t);if(this.peerId.equals(n))throw new Ar("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new ft("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Cl});if(o.status!=="open")throw new Sr("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new _e("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>W(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var sn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(t){this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timeSpan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(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=t;this.previousTime=e}};var iw=1.2,aw=2,cw=2e3,hi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new sn(t.interval??5e3),this.failure=new sn(t.interval??5e3),this.next=new sn(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??aw,this.timeoutMultiplier=t.timeoutMultiplier??iw,this.minTimeout=t.minTimeout??cw,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=Se([t.signal,n]);return o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var kl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await bt(this.readNext.promise,e?.signal,e)}};function xh(){return new kl}var pi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function vh(r,t){let e=xh();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new Q;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await bt(n.next(),i?.signal);if(l===!0)throw new pi("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var lw=1e4,uw="1.0.0",fw="ping",dw="ipfs",Eh=32,hw=!0,mi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??dw}/${fw}/${uw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??lw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??hw,this.timeout=new hi({...e.pingTimeout??{},metrics:t.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(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=vh(o);e=Date.now(),await Promise.all([s.write(Kr(Eh),{signal:n}),s.read({bytes:Eh,signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):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 Rl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await bt(this.readNext.promise,e?.signal,e)}};function Sh(){return new Rl}function pw(r){return r[Symbol.asyncIterator]!=null}async function mw(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*gw(r){let t=Sh();mw(r,t).catch(()=>{}),yield*t}function*yw(r){for(let t of r)yield*t}function ww(...r){let t=[];for(let e of r)pw(e)||t.push(e);return t.length===r.length?yw(t):gw(r)}var ao=ww;var gi=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.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=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:B(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(t,e={}){if(this.routers.length===0)throw new tn("No content routers available");let n=this,o=new ar;for await(let s of ao(...n.routers.map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new tn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new tn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new le;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new le;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var yi=globalThis.CustomEvent??Event;async function*Nl(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=X(),a=X(),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===e&&(i=X(),await i.promise),u)break;let g={done:!1};s.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,o.dispatchEvent(new yi("task-complete"))},h=>{g.done=!0,g.err=h,o.dispatchEvent(new yi("task-complete"))})}c=!0,o.dispatchEvent(new yi("task-complete"))}catch(p){l=p,o.dispatchEvent(new yi("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*m(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=X(),await a.promise),l!=null)throw l;if(n?yield*d():yield*m(),c&&s.length===0)break}}var wi=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:B(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(t,e){if(this.routers.length===0)throw new oo("No peer routers available");if(t.toString()===this.peerId.toString())throw new qs("Should not try to find self");let n=this,o=ao(...this.routers.map(s=>async function*(){try{yield await s.findPeer(t,e)}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}),s;throw new He}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new oo("No peer routers available");let n=this,o=Gn(1024);for await(let s of Nl(async function*(){let i=ao(...n.routers.map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,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}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var bi=class extends ue{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.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(t){this.walking||this.startWalk(),this.walkers++;let e=Se([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=X(),yield(await rn(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.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 t=Se([this.walkController.signal,this.shutdownController.signal]);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Kr(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.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 bt(this.needNext.promise,t)),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()-e),this.walking=!1})}};var Ml=32,Bl=64,xi=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,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(t){let e=this.handlers.get(t);if(e==null)throw new zs(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&n?.force!==!0)throw new Vs(`Handler already registered for protocol ${t}`);let o=ls.bind({ignoreUndefined:!0})({maxInboundStreams:Ml,maxOutboundStreams:Bl},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,e){if(e==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Ol=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ah(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ol({name:t,metrics:e}):n=new Map,n}var vi=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=Ah({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??$e.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new R("Transport must have a valid tag");if(this.transports.has(e))throw new R(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new Zs(`No transport available for address ${String(t)}`);return e?.onProgress?.(new ft("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new le("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new $s)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);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})}),il.matches(c)?e.ipv4.attempts++:al.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),il.matches(c)&&e.ipv4.success++,al.matches(c)&&e.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),e.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(e)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===$e.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Hs(`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 ip=Object.create;var wo=Object.defineProperty;var ap=Object.getOwnPropertyDescriptor;var cp=Object.getOwnPropertyNames;var lp=Object.getPrototypeOf,up=Object.prototype.hasOwnProperty;var Ie=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Lt=(r,t)=>{for(var e in t)wo(r,e,{get:t[e],enumerable:!0})},cu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of cp(t))!up.call(r,o)&&o!==e&&wo(r,o,{get:()=>t[o],enumerable:!(n=ap(t,o))||n.enumerable});return r};var dn=(r,t,e)=>(e=r!=null?ip(lp(r)):{},cu(t||!r||!r.__esModule?wo(e,"default",{value:r,enumerable:!0}):e,r)),fp=r=>cu(wo({},"__esModule",{value:!0}),r);var Jf=Ie((vE,Ac)=>{"use strict";var m0=Object.prototype.hasOwnProperty,Ot="~";function $n(){}Object.create&&($n.prototype=Object.create(null),new $n().__proto__||(Ot=!1));function g0(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Qf(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new g0(e,n||r,o),i=Ot?Ot+t:t;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 es(r,t){--r._eventsCount===0?r._events=new $n:delete r._events[t]}function Ct(){this._events=new $n,this._eventsCount=0}Ct.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)m0.call(e,n)&&t.push(Ot?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ct.prototype.listeners=function(t){var e=Ot?Ot+t:t,n=this._events[e];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};Ct.prototype.listenerCount=function(t){var e=Ot?Ot+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Ct.prototype.emit=function(t,e,n,o,s,i){var a=Ot?Ot+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,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,m;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,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,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!u)for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c[f].fn.apply(c[f].context,u)}}return!0};Ct.prototype.on=function(t,e,n){return Qf(this,t,e,n,!1)};Ct.prototype.once=function(t,e,n){return Qf(this,t,e,n,!0)};Ct.prototype.removeListener=function(t,e,n,o){var s=Ot?Ot+t:t;if(!this._events[s])return this;if(!e)return es(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&es(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:es(this,s)}return this};Ct.prototype.removeAllListeners=function(t){var e;return t?(e=Ot?Ot+t:t,this._events[e]&&es(this,e)):(this._events=new $n,this._eventsCount=0),this};Ct.prototype.off=Ct.prototype.removeListener;Ct.prototype.addListener=Ct.prototype.on;Ct.prefixed=Ot;Ct.EventEmitter=Ct;typeof Ac<"u"&&(Ac.exports=Ct)});var od=Ie(($E,nd)=>{nd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Ed=Ie((yA,vd)=>{"use strict";vd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var Pd=Ie((Id,Cd)=>{"use strict";var ds=Ed(),{hasOwnProperty:Ad}=Object.prototype,{propertyIsEnumerable:q0}=Object,Qr=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),z0=Id,Sd={concatArrays:!1,ignoreUndefined:!1},hs=r=>{let t=[];for(let e in r)Ad.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)q0.call(r,n)&&t.push(n)}return t};function Jr(r){return Array.isArray(r)?V0(r):ds(r)?$0(r):r}function V0(r){let t=r.slice(0,0);return hs(r).forEach(e=>{Qr(t,e,Jr(r[e]))}),t}function $0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return hs(r).forEach(e=>{Qr(t,e,Jr(r[e]))}),t}var _d=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Qr(r,o,jc(r[o],t[o],n)):Qr(r,o,Jr(t[o])))}),r),H0=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Ad.call(s,a)&&(i.push(String(a)),s===r?Qr(n,o++,s[a]):Qr(n,o++,Jr(s[a])));n=_d(n,s,hs(s).filter(a=>!i.includes(a)),e)}),n};function jc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?H0(r,t,e):!ds(t)||!ds(r)?Jr(t):_d(r,t,hs(t),e)}Cd.exports=function(...r){let t=jc(Jr(Sd),this!==z0&&this||{},Sd),e={_:{}};for(let n of r)if(n!==void 0){if(!ds(n))throw new TypeError("`"+n+"` is not an Option Object");e=jc(e,{_:n},t)}return e._}});var nh=Ie(ro=>{(function(){var r,t,e,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,m,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=t(c),m=p[0],u=p[1],c=c.substring(u),l.push(m)}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")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var l,u,f,d,m;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")),m=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===m)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,m,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(g){throw f=g,new Error("Invalid mask: "+u)}for(d=m=32;m>=0;d=--m)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(g){throw f=g,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}(),ro.ip2long=i,ro.long2ip=a,ro.Netmask=r}).call(ro)});var Dh=Ie((O4,Lh)=>{function Wt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Lh.exports=Wt;Wt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Wt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Wt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Wt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Wt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Wt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Wt.prototype.start=Wt.prototype.try;Wt.prototype.errors=function(){return this._errors};Wt.prototype.attempts=function(){return this._attempts};Wt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var kh=Ie(Er=>{var Lw=Dh();Er.operation=function(r){var t=Er.timeouts(r);return new Lw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Er.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Er.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Er.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var l=Er.operation(t),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[s].options=t}}});var Mh=Ie((F4,Rh)=>{Rh.exports=kh()});var sb={};Lt(sb,{createLibp2p:()=>ob});var lu=Symbol.for("@libp2p/connection");var zi=Symbol.for("@libp2p/content-routing");var Vi=Symbol.for("@libp2p/peer-discovery");var bo=Symbol.for("@libp2p/peer-id");function xo(r){return!!r?.[bo]}var $i=Symbol.for("@libp2p/peer-routing");var Hi="keep-alive";var hb=Symbol.for("@libp2p/transport");var Ge;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ge||(Ge={}));var jt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},_r=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},hn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var vo=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Ir=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var We=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Cr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Ce=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Eo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},So=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},pn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Ao=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var _o=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},fe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Pr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Tr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Io=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Co=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Pe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var de=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Po(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function uu(...r){let t=[];for(let e of r)Po(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function fu(...r){let t=[];for(let e of r)Po(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var mn=Symbol.for("@libp2p/service-capabilities"),Gi=Symbol.for("@libp2p/service-dependencies");var Zi={};Lt(Zi,{base58btc:()=>z,base58flickr:()=>yp});var Kb=new Uint8Array(0);function du(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function he(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 hu(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}function dp(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[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 g=0,h=0,w=0,x=p.length;w!==x&&p[w]===0;)w++,g++;for(var y=(x-w)*u+1>>>0,E=new Uint8Array(y);w!==x;){for(var _=p[w],D=0,I=y-1;(_!==0||D<h)&&I!==-1;I--,D++)_+=256*E[I]>>>0,E[I]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=D,w++}for(var L=y-h;L!==y&&E[L]===0;)L++;for(var P=c.repeat(g);L<y;++L)P+=r.charAt(E[L]);return P}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var h=0,w=0;p[g]===c;)h++,g++;for(var x=(p.length-g)*l+1>>>0,y=new Uint8Array(x);p[g];){var E=e[p.charCodeAt(g)];if(E===255)return;for(var _=0,D=x-1;(E!==0||_<w)&&D!==-1;D--,_++)E+=a*y[D]>>>0,y[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=_,g++}if(p[g]!==" "){for(var I=x-w;I!==x&&y[I]===0;)I++;for(var L=new Uint8Array(h+(x-I)),P=h;I!==x;)L[P++]=y[I++];return L}}}function m(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var hp=dp,pp=hp,gu=pp;var Wi=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},ji=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return yu(this,t)}},Xi=class{decoders;constructor(t){this.decoders=t}or(t){return yu(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function yu(r,t){return new Xi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Yi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Wi(t,e,n),this.decoder=new ji(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Lr({name:r,prefix:t,encode:e,decode:n}){return new Yi(r,t,e,n)}function Te({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=gu(e,r);return Lr({prefix:t,name:r,encode:n,decode:s=>he(o(s))})}function mp(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function gp(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function lt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Lr({prefix:t,name:r,encode(o){return gp(o,n,e)},decode(o){return mp(o,n,e,r)}})}var z=Te({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yp=Te({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qi={};Lt(Qi,{base32:()=>qt,base32hex:()=>vp,base32hexpad:()=>Sp,base32hexpadupper:()=>Ap,base32hexupper:()=>Ep,base32pad:()=>bp,base32padupper:()=>xp,base32upper:()=>wp,base32z:()=>_p});var qt=lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),wp=lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bp=lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xp=lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vp=lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ep=lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Sp=lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ap=lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_p=lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ji={};Lt(Ji,{base36:()=>gn,base36upper:()=>Ip});var gn=Te({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ip=Te({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cp=xu,wu=128,Pp=127,Tp=~Pp,Lp=Math.pow(2,31);function xu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Lp;)t[e++]=r&255|wu,r/=128;for(;r&Tp;)t[e++]=r&255|wu,r>>>=7;return t[e]=r|0,xu.bytes=e-n+1,t}var Dp=ta,kp=128,bu=127;function ta(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ta.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&bu)<<o:(i&bu)*Math.pow(2,o),o+=7}while(i>=kp);return ta.bytes=s-n,e}var Rp=Math.pow(2,7),Mp=Math.pow(2,14),Np=Math.pow(2,21),Op=Math.pow(2,28),Bp=Math.pow(2,35),Fp=Math.pow(2,42),Up=Math.pow(2,49),Kp=Math.pow(2,56),qp=Math.pow(2,63),zp=function(r){return r<Rp?1:r<Mp?2:r<Np?3:r<Op?4:r<Bp?5:r<Fp?6:r<Up?7:r<Kp?8:r<qp?9:10},Vp={encode:Cp,decode:Dp,encodingLength:zp},$p=Vp,yn=$p;function wn(r,t=0){return[yn.decode(r,t),yn.decode.bytes]}function Dr(r,t,e=0){return yn.encode(r,t,e),t}function kr(r){return yn.encodingLength(r)}function Xt(r,t){let e=t.byteLength,n=kr(r),o=n+kr(e),s=new Uint8Array(o+e);return Dr(r,s,0),Dr(e,s,n),s.set(t,o),new Rr(r,e,t,s)}function zt(r){let t=he(r),[e,n]=wn(t),[o,s]=wn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Rr(e,o,i,t)}function vu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&du(r.bytes,e.bytes)}}var Rr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Eu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Gp(e,ea(r),t??z.encoder);default:return Wp(e,ea(r),t??qt.encoder)}}var Su=new WeakMap;function ea(r){let t=Su.get(r);if(t==null){let e=new Map;return Su.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==bn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==jp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Xt(t,e);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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&vu(t.multihash,n.multihash)}toString(t){return Eu(this,t)}toJSON(){return{"/":Eu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Au(n,o,s.bytes))}else if(e[Xp]===!0){let{version:n,multihash:o,code:s}=e,i=zt(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==bn)throw new Error(`Version 0 CID must use dag-pb (code: ${bn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Au(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,bn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=he(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Rr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=wn(t.subarray(e));return e+=d,f},o=n(),s=bn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Hp(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ea(s).set(n,t),s}};function Hp(r,t){switch(r[0]){case"Q":{let e=t??z;return[z.prefix,e.decode(`${z.prefix}${r}`)]}case z.prefix:{let e=t??z;return[z.prefix,e.decode(r)]}case qt.prefix:{let e=t??qt;return[qt.prefix,e.decode(r)]}case gn.prefix:{let e=t??gn;return[gn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Gp(r,t,e){let{prefix:n}=e;if(n!==z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Wp(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var bn=112,jp=18;function Au(r,t,e){let n=kr(r),o=n+kr(t),s=new Uint8Array(o+e.byteLength);return Dr(r,s,0),Dr(t,s,n),s.set(e,o),s}var Xp=Symbol.for("@ipld/js-cid/CID");var ra={};Lt(ra,{identity:()=>Yt});var _u=0,Yp="identity",Iu=he;function Zp(r){return Xt(_u,Iu(r))}var Yt={code:_u,name:Yp,encode:Iu,digest:Zp};function J(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ut(r=0){return new Uint8Array(r)}function St(r=0){return new Uint8Array(r)}function Dt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=St(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Pu=Symbol.for("@achingbrain/uint8arraylist");function Cu(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Lo(r){return!!r?.[Pu]}var H=class r{bufs;length;[Pu]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Lo(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Lo(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Cu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Cu(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Lo(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Dt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Dt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===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,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Lo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;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=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ut(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ut(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ut(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ut(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ut(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ut(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ut(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ut(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!J(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var na={};Lt(na,{base10:()=>Qp});var Qp=Te({prefix:"9",name:"base10",alphabet:"0123456789"});var oa={};Lt(oa,{base16:()=>Jp,base16upper:()=>tm});var Jp=lt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tm=lt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sa={};Lt(sa,{base2:()=>em});var em=lt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ia={};Lt(ia,{base256emoji:()=>im});var Tu=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}"),rm=Tu.reduce((r,t,e)=>(r[e]=t,r),[]),nm=Tu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function om(r){return r.reduce((t,e)=>(t+=rm[e],t),"")}function sm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=nm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var im=Lr({prefix:"\u{1F680}",name:"base256emoji",encode:om,decode:sm});var la={};Lt(la,{base64:()=>aa,base64pad:()=>am,base64url:()=>ca,base64urlpad:()=>cm});var aa=lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),am=lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ca=lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),cm=lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ua={};Lt(ua,{base8:()=>lm});var lm=lt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fa={};Lt(fa,{identity:()=>um});var um=Lr({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>hu(r)});var Sx=new TextEncoder,Ax=new TextDecoder;var pa={};Lt(pa,{sha256:()=>Mr,sha512:()=>hm});function ha({name:r,code:t,encode:e}){return new da(r,t,e)}var da=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Xt(this.code,e):e.then(n=>Xt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Du(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Mr=ha({name:"sha2-256",code:18,encode:Du("SHA-256")}),hm=ha({name:"sha2-512",code:19,encode:Du("SHA-512")});var xn={...fa,...sa,...ua,...na,...oa,...Qi,...Ji,...Zi,...la,...ia},Ox={...pa,...ra};function Ru(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ku=Ru("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ma=Ru("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=St(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),pm={utf8:ku,"utf-8":ku,hex:xn.base16,latin1:ma,ascii:ma,binary:ma,...xn},Do=pm;function T(r,t="utf8"){let e=Do[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function M(r,t="utf8"){let e=Do[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var mm=parseInt("11111",2),ga=parseInt("10000000",2),gm=parseInt("01111111",2),Mu={0:vn,1:vn,2:ym,3:xm,4:vm,5:bm,6:wm,16:vn,22:vn,48:vn};function pe(r,t={offset:0}){let e=r[t.offset]&mm;if(t.offset++,Mu[e]!=null)return Mu[e](r,t);throw new Error("No decoder for tag "+e)}function En(r,t){let e=0;if((r[t.offset]&ga)===ga){let n=r[t.offset]&gm,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function vn(r,t){En(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=pe(r,t);if(n===null)break;e.push(n)}return e}function ym(r,t){let e=En(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function wm(r,t){let e=En(r,t),n=t.offset+e,o=r[t.offset];t.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(;t.offset<n;){let l=r[t.offset];if(t.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 bm(r,t){return t.offset++,null}function xm(r,t){let e=En(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function vm(r,t){let e=En(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Em(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new H;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function ko(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Em(r.byteLength);return new H(Uint8Array.from([t.byteLength|ga]),t)}function kt(r){let t=new H,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new H(Uint8Array.from([2]),ko(t),t)}function Sn(r){let t=Uint8Array.from([0]),e=new H(t,r);return new H(Uint8Array.from([3]),ko(e),e)}function Nu(r){return new H(Uint8Array.from([4]),ko(r),r)}function Zt(r,t=48){let e=new H;for(let n of r)e.append(n);return new H(Uint8Array.from([t]),ko(e),e)}async function Ou(r="P-256"){let t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}async function Bu(r,t){let e=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]),n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Fu(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var Sm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Am=Uint8Array.from([6,5,43,129,4,0,34]),_m=Uint8Array.from([6,5,43,129,4,0,35]),Im={ext:!0,kty:"EC",crv:"P-256"},Cm={ext:!0,kty:"EC",crv:"P-384"},Pm={ext:!0,kty:"EC",crv:"P-521"},ya=32,wa=48,ba=66;function xa(r){let t=pe(r);return Uu(t)}function Uu(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===ya*2+1)return n=M(t.subarray(e,e+ya),"base64url"),o=M(t.subarray(e+ya),"base64url"),new je({...Im,key_ops:["verify"],x:n,y:o});if(t.byteLength===wa*2+1)return n=M(t.subarray(e,e+wa),"base64url"),o=M(t.subarray(e+wa),"base64url"),new je({...Cm,key_ops:["verify"],x:n,y:o});if(t.byteLength===ba*2+1)return n=M(t.subarray(e,e+ba),"base64url"),o=M(t.subarray(e+ba),"base64url"),new je({...Pm,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Ku(r){return Zt([kt(Uint8Array.from([1])),Nu(T(r.d??"","base64url")),Zt([zu(r.crv)],160),Zt([Sn(new H(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function qu(r){return Zt([kt(Uint8Array.from([1])),Zt([zu(r.crv)],160),Zt([Sn(new H(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function zu(r){if(r==="P-256")return Sm;if(r==="P-384")return Am;if(r==="P-521")return _m;throw new R(`Invalid curve ${r}`)}async function Vu(r="P-256"){let t=await Ou(r);return new Ro(t.privateKey)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=qu(this.jwk)),this._raw}toMultihash(){return Yt.digest(Ht(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}async verify(t,e){return Fu(this.jwk,e,t)}},Ro=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new je({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Ku(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}async sign(t){return Bu(this.jwk,t)}};function $u(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Tm(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Nr(r,...t){if(!Tm(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Hu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$u(r.outputLen),$u(r.blockLen)}function Or(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Gu(r,t){Nr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Xe=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Mo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Qt(r,t){return r<<32-t|r>>>t}function Wu(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function An(r){return typeof r=="string"&&(r=Wu(r)),Nr(r),r}function va(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Nr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Br=class{clone(){return this._cloneInto()}};function No(r){let t=n=>r().update(An(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Fr(r=32){if(Xe&&typeof Xe.getRandomValues=="function")return Xe.getRandomValues(new Uint8Array(r));if(Xe&&typeof Xe.randomBytes=="function")return Xe.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Lm(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function ju(r,t,e){return r&t^~r&e}function Xu(r,t,e){return r&t^r&e^t&e}var Ur=class extends Br{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Mo(this.buffer)}update(t){Or(this);let{view:e,buffer:n,blockLen:o}=this;t=An(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Mo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Or(this),Gu(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Lm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Mo(t),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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Oo=BigInt(4294967295),Ea=BigInt(32);function Yu(r,t=!1){return t?{h:Number(r&Oo),l:Number(r>>Ea&Oo)}:{h:Number(r>>Ea&Oo)|0,l:Number(r&Oo)|0}}function Dm(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Yu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var km=(r,t)=>BigInt(r>>>0)<<Ea|BigInt(t>>>0),Rm=(r,t,e)=>r>>>e,Mm=(r,t,e)=>r<<32-e|t>>>e,Nm=(r,t,e)=>r>>>e|t<<32-e,Om=(r,t,e)=>r<<32-e|t>>>e,Bm=(r,t,e)=>r<<64-e|t>>>e-32,Fm=(r,t,e)=>r>>>e-32|t<<64-e,Um=(r,t)=>t,Km=(r,t)=>r,qm=(r,t,e)=>r<<e|t>>>32-e,zm=(r,t,e)=>t<<e|r>>>32-e,Vm=(r,t,e)=>t<<e-32|r>>>64-e,$m=(r,t,e)=>r<<e-32|t>>>64-e;function Hm(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Gm=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Wm=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,jm=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Xm=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Ym=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Zm=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Qm={fromBig:Yu,split:Dm,toBig:km,shrSH:Rm,shrSL:Mm,rotrSH:Nm,rotrSL:Om,rotrBH:Bm,rotrBL:Fm,rotr32H:Um,rotr32L:Km,rotlSH:qm,rotlSL:zm,rotlBH:Vm,rotlBL:$m,add:Hm,add3L:Gm,add3H:Wm,add4L:jm,add4H:Xm,add5H:Zm,add5L:Ym},F=Qm;var[Jm,tg]=F.split(["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))),Le=new Uint32Array(80),De=new Uint32Array(80),Sa=class extends Ur{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:p,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,m,p,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,m,p,g,h){this.Ah=t|0,this.Al=e|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=m|0,this.Gl=p|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let y=0;y<16;y++,e+=4)Le[y]=t.getUint32(e),De[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let E=Le[y-15]|0,_=De[y-15]|0,D=F.rotrSH(E,_,1)^F.rotrSH(E,_,8)^F.shrSH(E,_,7),I=F.rotrSL(E,_,1)^F.rotrSL(E,_,8)^F.shrSL(E,_,7),L=Le[y-2]|0,P=De[y-2]|0,nt=F.rotrSH(L,P,19)^F.rotrBH(L,P,61)^F.shrSH(L,P,6),W=F.rotrSL(L,P,19)^F.rotrBL(L,P,61)^F.shrSL(L,P,6),K=F.add4L(I,W,De[y-7],De[y-16]),pt=F.add4H(K,D,nt,Le[y-7],Le[y-16]);Le[y]=pt|0,De[y]=K|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:p,Gh:g,Gl:h,Hh:w,Hl:x}=this;for(let y=0;y<80;y++){let E=F.rotrSH(f,d,14)^F.rotrSH(f,d,18)^F.rotrBH(f,d,41),_=F.rotrSL(f,d,14)^F.rotrSL(f,d,18)^F.rotrBL(f,d,41),D=f&m^~f&g,I=d&p^~d&h,L=F.add5L(x,_,I,tg[y],De[y]),P=F.add5H(L,w,E,D,Jm[y],Le[y]),nt=L|0,W=F.rotrSH(n,o,28)^F.rotrBH(n,o,34)^F.rotrBH(n,o,39),K=F.rotrSL(n,o,28)^F.rotrBL(n,o,34)^F.rotrBL(n,o,39),pt=n&s^n&a^s&a,A=o&i^o&c^i&c;w=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=F.add(l|0,u|0,P|0,nt|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let k=F.add3L(nt,K,A);n=F.add3H(k,P,W,pt),o=k|0}({h:n,l:o}=F.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=F.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=F.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=F.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=F.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:p}=F.add(this.Fh|0,this.Fl|0,m|0,p|0),{h:g,l:h}=F.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=F.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,m,p,g,h,w,x)}roundClean(){Le.fill(0),De.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Zu=No(()=>new Sa);var Uo={};Lt(Uo,{aInRange:()=>Ft,abool:()=>Jt,abytes:()=>Kr,bitGet:()=>ig,bitLen:()=>Ca,bitMask:()=>In,bitSet:()=>ag,bytesToHex:()=>ge,bytesToNumberBE:()=>ye,bytesToNumberLE:()=>Re,concatBytes:()=>we,createHmacDrbg:()=>Pa,ensureBytes:()=>ct,equalBytes:()=>og,hexToBytes:()=>Ze,hexToNumber:()=>Ia,inRange:()=>_n,isBytes:()=>ke,memoized:()=>Je,notImplemented:()=>lg,numberToBytesBE:()=>Me,numberToBytesLE:()=>Qe,numberToHexUnpadded:()=>Ye,numberToVarBytesBE:()=>ng,utf8ToBytes:()=>sg,validateObject:()=>ae});var Bo=BigInt(0),Fo=BigInt(1),eg=BigInt(2);function ke(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Kr(r){if(!ke(r))throw new Error("Uint8Array expected")}function Jt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var rg=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ge(r){Kr(r);let t="";for(let e=0;e<r.length;e++)t+=rg[r[e]];return t}function Ye(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Ia(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Bo:BigInt("0x"+r)}var me={_0:48,_9:57,A:65,F:70,a:97,f:102};function Qu(r){if(r>=me._0&&r<=me._9)return r-me._0;if(r>=me.A&&r<=me.F)return r-(me.A-10);if(r>=me.a&&r<=me.f)return r-(me.a-10)}function Ze(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Qu(r.charCodeAt(s)),a=Qu(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 ye(r){return Ia(ge(r))}function Re(r){return Kr(r),Ia(ge(Uint8Array.from(r).reverse()))}function Me(r,t){return Ze(r.toString(16).padStart(t*2,"0"))}function Qe(r,t){return Me(r,t).reverse()}function ng(r){return Ze(Ye(r))}function ct(r,t,e){let n;if(typeof t=="string")try{n=Ze(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(ke(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function we(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Kr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function og(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function sg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Aa=r=>typeof r=="bigint"&&Bo<=r;function _n(r,t,e){return Aa(r)&&Aa(t)&&Aa(e)&&t<=r&&r<e}function Ft(r,t,e,n){if(!_n(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Ca(r){let t;for(t=0;r>Bo;r>>=Fo,t+=1);return t}function ig(r,t){return r>>BigInt(t)&Fo}function ag(r,t,e){return r|(e?Fo:Bo)<<BigInt(t)}var In=r=>(eg<<BigInt(r-1))-Fo,_a=r=>new Uint8Array(r),Ju=r=>Uint8Array.from(r);function Pa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=_a(r),o=_a(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=_a())=>{o=a(Ju([0]),f),n=a(),f.length!==0&&(o=a(Ju([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let m=n.slice();d.push(m),f+=n.length}return we(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var cg={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||ke(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ae(r,t,e={}){let n=(o,s,i)=>{let a=cg[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var lg=()=>{throw new Error("not implemented")};function Je(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var mt=BigInt(0),ot=BigInt(1),tr=BigInt(2),ug=BigInt(3),Ta=BigInt(4),tf=BigInt(5),ef=BigInt(8),fg=BigInt(9),dg=BigInt(16);function et(r,t){let e=r%t;return e>=mt?e:t+e}function hg(r,t,e){if(t<mt)throw new Error("invalid exponent, negatives unsupported");if(e<=mt)throw new Error("invalid modulus");if(e===ot)return mt;let n=ot;for(;t>mt;)t&ot&&(n=n*r%e),r=r*r%e,t>>=ot;return n}function st(r,t,e){let n=r;for(;t-- >mt;)n*=n,n%=e;return n}function Ko(r,t){if(r===mt)throw new Error("invert: expected non-zero number");if(t<=mt)throw new Error("invert: expected positive modulus, got "+t);let e=et(r,t),n=t,o=mt,s=ot,i=ot,a=mt;for(;e!==mt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ot)throw new Error("invert: does not exist");return et(o,t)}function pg(r){let t=(r-ot)/tr,e,n,o;for(e=r-ot,n=0;e%tr===mt;e/=tr,n++);for(o=tr;o<r&&hg(o,t,r)!==r-ot;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ot)/Ta;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ot)/tr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let p=a.pow(u,ot<<BigInt(l-m-1));u=a.sqr(p),f=a.mul(f,p),d=a.mul(d,u),l=m}return f}}function mg(r){if(r%Ta===ug){let t=(r+ot)/Ta;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%ef===tf){let t=(r-tf)/ef;return function(n,o){let s=n.mul(o,tr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,tr),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%dg,pg(r)}var rf=(r,t)=>(et(r,t)&ot)===ot,gg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function La(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=gg.reduce((n,o)=>(n[o]="function",n),t);return ae(r,e)}function yg(r,t,e){if(e<mt)throw new Error("invalid exponent, negatives unsupported");if(e===mt)return r.ONE;if(e===ot)return t;let n=r.ONE,o=t;for(;e>mt;)e&ot&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ot;return n}function wg(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Da(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ne(r,t,e=!1,n={}){if(r<=mt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Da(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:In(o),ZERO:mt,ONE:ot,create:c=>et(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return mt<=c&&c<r},is0:c=>c===mt,isOdd:c=>(c&ot)===ot,neg:c=>et(-c,r),eql:(c,l)=>c===l,sqr:c=>et(c*c,r),add:(c,l)=>et(c+l,r),sub:(c,l)=>et(c-l,r),mul:(c,l)=>et(c*l,r),pow:(c,l)=>yg(a,c,l),div:(c,l)=>et(c*Ko(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Ko(c,r),sqrt:n.sqrt||(c=>(i||(i=mg(r)),i(a,c))),invertBatch:c=>wg(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Qe(c,s):Me(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Re(c):ye(c)}});return Object.freeze(a)}function nf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function ka(r){let t=nf(r);return t+Math.ceil(t/2)}function of(r,t,e=!1){let n=r.length,o=nf(t),s=ka(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Re(r):ye(r),a=et(i,t-ot)+ot;return e?Qe(a,o):Me(a,o)}var sf=BigInt(0),qo=BigInt(1);function Ra(r,t){let e=t.negate();return r?e:t}function af(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ma(r,t){af(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function bg(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function xg(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Na=new WeakMap,cf=new WeakMap;function Oa(r){return cf.get(r)||1}function zo(r,t){return{constTimeNegate:Ra,hasPrecomputes(e){return Oa(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>sf;)n&qo&&(o=o.add(s)),s=s.double(),n>>=qo;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Ma(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=Ma(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let m=d*i,p=Number(o&l);o>>=f,p>i&&(p-=u,o+=qo);let g=m,h=m+Math.abs(p)-1,w=d%2!==0,x=p<0;p===0?c=c.add(Ra(w,n[g])):a=a.add(Ra(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Ma(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===sf)break;let m=Number(o&c);if(o>>=u,m>a&&(m-=l,o+=qo),m===0)continue;let p=n[d+Math.abs(m)-1];m<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(e,n,o){let s=Na.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Na.set(n,o(s))),s},wNAFCached(e,n,o){let s=Oa(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Oa(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){af(n,t),cf.set(e,n),Na.delete(e)}}}function Vo(r,t,e,n){if(bg(e,r),xg(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=Ca(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let p=n[m],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[m])}let d=o;for(let m=c.length-1,p=o;m>0;m--)p=p.add(c[m]),d=d.add(p);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function Cn(r){return La(r.Fp),ae(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Da(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var te=BigInt(0),Ut=BigInt(1),$o=BigInt(2),vg=BigInt(8),Eg={zip215:!0};function Sg(r){let t=Cn(r);return ae(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function lf(r){let t=Sg(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=$o<<BigInt(a*8)-Ut,u=e.create,f=Ne(t.n,t.nBitLength),d=t.uvRatio||((v,b)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(b))}}catch{return{isValid:!1,value:te}}}),m=t.adjustScalarBytes||(v=>v),p=t.domain||((v,b,S)=>{if(Jt("phflag",S),b.length||S)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b){Ft("coordinate "+v,b,te,l)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let w=Je((v,b)=>{let{ex:S,ey:C,ez:N}=v,O=v.is0();b==null&&(b=O?vg:e.inv(N));let U=u(S*b),q=u(C*b),B=u(N*b);if(O)return{x:te,y:Ut};if(B!==Ut)throw new Error("invZ was invalid");return{x:U,y:q}}),x=Je(v=>{let{a:b,d:S}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:C,ey:N,ez:O,et:U}=v,q=u(C*C),B=u(N*N),Q=u(O*O),rt=u(Q*Q),gt=u(q*b),yt=u(Q*u(gt+B)),xt=u(rt+u(S*u(q*B)));if(yt!==xt)throw new Error("bad point: equation left != right (1)");let Et=u(C*N),Bt=u(O*U);if(Et!==Bt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(b,S,C,N){this.ex=b,this.ey=S,this.ez=C,this.et=N,g("x",b),g("y",S),g("z",C),g("t",N),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof y)throw new Error("extended point not allowed");let{x:S,y:C}=b||{};return g("x",S),g("y",C),new y(S,C,Ut,u(S*C))}static normalizeZ(b){let S=e.invertBatch(b.map(C=>C.ez));return b.map((C,N)=>C.toAffine(S[N])).map(y.fromAffine)}static msm(b,S){return Vo(y,f,b,S)}_setWindowSize(b){D.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:S,ey:C,ez:N}=this,{ex:O,ey:U,ez:q}=b,B=u(S*q),Q=u(O*N),rt=u(C*q),gt=u(U*N);return B===Q&&rt===gt}is0(){return this.equals(y.ZERO)}negate(){return new y(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:b}=t,{ex:S,ey:C,ez:N}=this,O=u(S*S),U=u(C*C),q=u($o*u(N*N)),B=u(b*O),Q=S+C,rt=u(u(Q*Q)-O-U),gt=B+U,yt=gt-q,xt=B-U,Et=u(rt*yt),Bt=u(gt*xt),Tt=u(rt*xt),se=u(yt*gt);return new y(Et,Bt,se,Tt)}add(b){h(b);let{a:S,d:C}=t,{ex:N,ey:O,ez:U,et:q}=this,{ex:B,ey:Q,ez:rt,et:gt}=b;if(S===BigInt(-1)){let eu=u((O-N)*(Q+B)),ru=u((O+N)*(Q-B)),qi=u(ru-eu);if(qi===te)return this.double();let nu=u(U*$o*gt),ou=u(q*$o*rt),su=ou+nu,iu=ru+eu,au=ou-nu,rp=u(su*qi),np=u(iu*au),op=u(su*au),sp=u(qi*iu);return new y(rp,np,sp,op)}let yt=u(N*B),xt=u(O*Q),Et=u(q*C*gt),Bt=u(U*rt),Tt=u((N+O)*(B+Q)-yt-xt),se=Bt-Et,ue=Bt+Et,fn=u(xt-S*yt),Qh=u(Tt*se),Jh=u(ue*fn),tp=u(Tt*fn),ep=u(se*ue);return new y(Qh,Jh,ep,tp)}subtract(b){return this.add(b.negate())}wNAF(b){return D.wNAFCached(this,b,y.normalizeZ)}multiply(b){let S=b;Ft("scalar",S,Ut,n);let{p:C,f:N}=this.wNAF(S);return y.normalizeZ([C,N])[0]}multiplyUnsafe(b,S=y.ZERO){let C=b;return Ft("scalar",C,te,n),C===te?_:this.is0()||C===Ut?this:D.wNAFCachedUnsafe(this,C,y.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=t;return b===Ut?this:this.multiplyUnsafe(b)}static fromHex(b,S=!1){let{d:C,a:N}=t,O=e.BYTES;b=ct("pointHex",b,O),Jt("zip215",S);let U=b.slice(),q=b[O-1];U[O-1]=q&-129;let B=Re(U),Q=S?l:e.ORDER;Ft("pointHex.y",B,te,Q);let rt=u(B*B),gt=u(rt-Ut),yt=u(C*rt-N),{isValid:xt,value:Et}=d(gt,yt);if(!xt)throw new Error("Point.fromHex: invalid y coordinate");let Bt=(Et&Ut)===Ut,Tt=(q&128)!==0;if(!S&&Et===te&&Tt)throw new Error("Point.fromHex: x=0 and x_0=1");return Tt!==Bt&&(Et=u(-Et)),y.fromAffine({x:Et,y:B})}static fromPrivateKey(b){return P(b).point}toRawBytes(){let{x:b,y:S}=this.toAffine(),C=Qe(S,e.BYTES);return C[C.length-1]|=b&Ut?128:0,C}toHex(){return ge(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,Ut,u(t.Gx*t.Gy)),y.ZERO=new y(te,Ut,Ut,te);let{BASE:E,ZERO:_}=y,D=zo(y,a*8);function I(v){return et(v,n)}function L(v){return I(Re(v))}function P(v){let b=e.BYTES;v=ct("private key",v,b);let S=ct("hashed private key",s(v),2*b),C=m(S.slice(0,b)),N=S.slice(b,2*b),O=L(C),U=E.multiply(O),q=U.toRawBytes();return{head:C,prefix:N,scalar:O,point:U,pointBytes:q}}function nt(v){return P(v).pointBytes}function W(v=new Uint8Array,...b){let S=we(...b);return L(s(p(S,ct("context",v),!!o)))}function K(v,b,S={}){v=ct("message",v),o&&(v=o(v));let{prefix:C,scalar:N,pointBytes:O}=P(b),U=W(S.context,C,v),q=E.multiply(U).toRawBytes(),B=W(S.context,q,O,v),Q=I(U+B*N);Ft("signature.s",Q,te,n);let rt=we(q,Qe(Q,e.BYTES));return ct("result",rt,e.BYTES*2)}let pt=Eg;function A(v,b,S,C=pt){let{context:N,zip215:O}=C,U=e.BYTES;v=ct("signature",v,2*U),b=ct("message",b),S=ct("publicKey",S,U),O!==void 0&&Jt("zip215",O),o&&(b=o(b));let q=Re(v.slice(U,2*U)),B,Q,rt;try{B=y.fromHex(S,O),Q=y.fromHex(v.slice(0,U),O),rt=E.multiplyUnsafe(q)}catch{return!1}if(!O&&B.isSmallOrder())return!1;let gt=W(N,Q.toRawBytes(),B.toRawBytes(),b);return Q.add(B.multiplyUnsafe(gt)).subtract(rt).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:nt,sign:K,verify:A,ExtendedPoint:y,utils:{getExtendedPublicKey:P,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,b=y.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var Ba=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),uf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),B1=BigInt(0),Ag=BigInt(1),ff=BigInt(2),F1=BigInt(3),_g=BigInt(5),Ig=BigInt(8);function Cg(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ba,a=r*r%s*r%s,c=st(a,ff,s)*a%s,l=st(c,Ag,s)*r%s,u=st(l,_g,s)*l%s,f=st(u,t,s)*u%s,d=st(f,e,s)*f%s,m=st(d,n,s)*d%s,p=st(m,o,s)*m%s,g=st(p,o,s)*m%s,h=st(g,t,s)*u%s;return{pow_p_5_8:st(h,ff,s)*r%s,b2:a}}function Pg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Tg(r,t){let e=Ba,n=et(t*t*t,e),o=et(n*n*t,e),s=Cg(r*o).pow_p_5_8,i=et(r*n*s,e),a=et(t*i*i,e),c=i,l=et(i*uf,e),u=a===r,f=a===et(-r,e),d=a===et(-r*uf,e);return u&&(i=c),(f||d)&&(i=l),rf(i,e)&&(i=et(-i,e)),{isValid:u||f,value:i}}var Lg=Ne(Ba,void 0,!0),Dg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Lg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ig,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Zu,randomBytes:Fr,adjustScalarBytes:Pg,uvRatio:Tg},Pn=lf(Dg);var Ho=32,Go=64,Fa=32;function df(){let r=Pn.utils.randomPrivateKey(),t=Pn.getPublicKey(r);return{privateKey:kg(r,t),publicKey:t}}function hf(r,t){let e=r.subarray(0,Fa);return Pn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function pf(r,t,e){return Pn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function kg(r,t){let e=new Uint8Array(Go);for(let n=0;n<Fa;n++)e[n]=r[n],e[Fa+n]=t[n];return e}var Tn=class{type="Ed25519";raw;constructor(t){this.raw=jo(t,Ho)}toMultihash(){return Yt.digest(Ht(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}verify(t,e){return pf(this.raw,e,t)}},Wo=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=jo(t,Go),this.publicKey=new Tn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}sign(t){return hf(this.raw,t)}};function Ua(r){return r=jo(r,Ho),new Tn(r)}async function gf(){let{privateKey:r,publicKey:t}=df();return new Wo(r,t)}function jo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Rg=Math.pow(2,7),Mg=Math.pow(2,14),Ng=Math.pow(2,21),Ka=Math.pow(2,28),qa=Math.pow(2,35),za=Math.pow(2,42),Va=Math.pow(2,49),Z=128,At=127;function ht(r){if(r<Rg)return 1;if(r<Mg)return 2;if(r<Ng)return 3;if(r<Ka)return 4;if(r<qa)return 5;if(r<za)return 6;if(r<Va)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $a(r,t,e=0){switch(ht(r)){case 8:t[e++]=r&255|Z,r/=128;case 7:t[e++]=r&255|Z,r/=128;case 6:t[e++]=r&255|Z,r/=128;case 5:t[e++]=r&255|Z,r/=128;case 4:t[e++]=r&255|Z,r>>>=7;case 3:t[e++]=r&255|Z,r>>>=7;case 2:t[e++]=r&255|Z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Og(r,t,e=0){switch(ht(r)){case 8:t.set(e++,r&255|Z),r/=128;case 7:t.set(e++,r&255|Z),r/=128;case 6:t.set(e++,r&255|Z),r/=128;case 5:t.set(e++,r&255|Z),r/=128;case 4:t.set(e++,r&255|Z),r>>>=7;case 3:t.set(e++,r&255|Z),r>>>=7;case 2:t.set(e++,r&255|Z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ha(r,t){let e=r[t],n=0;if(n+=e&At,e<Z||(e=r[t+1],n+=(e&At)<<7,e<Z)||(e=r[t+2],n+=(e&At)<<14,e<Z)||(e=r[t+3],n+=(e&At)<<21,e<Z)||(e=r[t+4],n+=(e&At)*Ka,e<Z)||(e=r[t+5],n+=(e&At)*qa,e<Z)||(e=r[t+6],n+=(e&At)*za,e<Z)||(e=r[t+7],n+=(e&At)*Va,e<Z))return n;throw new RangeError("Could not decode varint")}function Bg(r,t){let e=r.get(t),n=0;if(n+=e&At,e<Z||(e=r.get(t+1),n+=(e&At)<<7,e<Z)||(e=r.get(t+2),n+=(e&At)<<14,e<Z)||(e=r.get(t+3),n+=(e&At)<<21,e<Z)||(e=r.get(t+4),n+=(e&At)*Ka,e<Z)||(e=r.get(t+5),n+=(e&At)*qa,e<Z)||(e=r.get(t+6),n+=(e&At)*za,e<Z)||(e=r.get(t+7),n+=(e&At)*Va,e<Z))return n;throw new RangeError("Could not decode varint")}function _t(r,t,e=0){return t==null&&(t=St(ht(r))),t instanceof Uint8Array?$a(r,t,e):Og(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Ha(r,t):Bg(r,t)}var Ga=new Float32Array([-0]),Oe=new Uint8Array(Ga.buffer);function yf(r,t,e){Ga[0]=r,t[e]=Oe[0],t[e+1]=Oe[1],t[e+2]=Oe[2],t[e+3]=Oe[3]}function wf(r,t){return Oe[0]=r[t],Oe[1]=r[t+1],Oe[2]=r[t+2],Oe[3]=r[t+3],Ga[0]}var Wa=new Float64Array([-0]),It=new Uint8Array(Wa.buffer);function bf(r,t,e){Wa[0]=r,t[e]=It[0],t[e+1]=It[1],t[e+2]=It[2],t[e+3]=It[3],t[e+4]=It[4],t[e+5]=It[5],t[e+6]=It[6],t[e+7]=It[7]}function xf(r,t){return It[0]=r[t],It[1]=r[t+1],It[2]=r[t+2],It[3]=r[t+3],It[4]=r[t+4],It[5]=r[t+5],It[6]=r[t+6],It[7]=r[t+7],Wa[0]}var Fg=BigInt(Number.MAX_SAFE_INTEGER),Ug=BigInt(Number.MIN_SAFE_INTEGER),Vt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return rr;if(t<Fg&&t>Ug)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>vf&&(o=0n,++n>vf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return rr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):rr}},rr=new Vt(0,0);rr.toBigInt=function(){return 0n};rr.zzEncode=rr.zzDecode=function(){return this};rr.length=function(){return 1};var vf=4294967296n;function Ef(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Sf(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 ja(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function re(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Xo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Xa=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,re(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw re(this,4);return Xo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw re(this,4);return Xo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw re(this,4);let t=wf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw re(this,4);let t=xf(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw re(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Sf(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw re(this,t);this.pos+=t}else do if(this.pos>=this.len)throw re(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Vt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw re(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw re(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw re(this,8);let t=Xo(this.buf,this.pos+=4),e=Xo(this.buf,this.pos+=4);return new Vt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ha(this.buf,this.pos);return this.pos+=ht(t),t}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 Ya(r){return new Xa(r instanceof Uint8Array?r:r.subarray())}function Rt(r,t,e){let n=Ya(r);return t.decode(n,void 0,e)}function Za(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return St(i);o+i>t&&(n=St(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var nr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Qa(){}var tc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Kg=Za();function qg(r){return globalThis.Buffer!=null?St(r):Kg(r)}var Dn=class{len;head;tail;states;constructor(){this.len=0,this.head=new nr(Qa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new nr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ec((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Yo,10,Vt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Vt.fromBigInt(t);return this._push(Yo,e.length(),e)}uint64Number(t){return this._push($a,ht(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Vt.fromBigInt(t).zzEncode();return this._push(Yo,e.length(),e)}sint64Number(t){let e=Vt.fromNumber(t).zzEncode();return this._push(Yo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ja,1,t?1:0)}fixed32(t){return this._push(Ln,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Vt.fromBigInt(t);return this._push(Ln,4,e.lo)._push(Ln,4,e.hi)}fixed64Number(t){let e=Vt.fromNumber(t);return this._push(Ln,4,e.lo)._push(Ln,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(yf,4,t)}double(t){return this._push(bf,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ja,1,0):this.uint32(e)._push(Vg,e,t)}string(t){let e=Ef(t);return e!==0?this.uint32(e)._push(ja,e,t):this._push(Ja,1,0)}fork(){return this.states=new tc(this),this.head=this.tail=new nr(Qa,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 nr(Qa,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=qg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ja(r,t,e){t[e]=r&255}function zg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ec=class extends nr{next;constructor(t,e){super(zg,t,e),this.next=void 0}};function Yo(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Ln(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Vg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Dn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push($g,t,r),this},Dn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Hg,t,r),this});function $g(r,t,e){t.set(r,e)}function Hg(r,t,e){r.length<40?ja(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(T(r),e)}function rc(){return new Dn}function Mt(r,t){let e=rc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var qr;(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"})(qr||(qr={}));function Zo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function nc(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Zo("enum",qr.VARINT,e,n)}function Nt(r,t){return Zo("message",qr.LENGTH_DELIMITED,r,t)}var or=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},kn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ft||(ft={}));var oc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(oc||(oc={}));(function(r){r.codec=()=>nc(oc)})(ft||(ft={}));var ce;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(ce||(ce={}));var sc;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(sc||(sc={}));function zr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Fr(r)}var Rn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Mn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Qo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var If={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Qo("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 t}};var Be=If;var On={};Lt(On,{MAX_RSA_KEY_SIZE:()=>ac,generateRSAKeyPair:()=>gc,jwkToJWKKeyPair:()=>Lf,jwkToPkcs1:()=>Yg,jwkToPkix:()=>fc,jwkToRSAPrivateKey:()=>mc,pkcs1MessageToJwk:()=>lc,pkcs1MessageToRSAPrivateKey:()=>dc,pkcs1ToJwk:()=>Xg,pkcs1ToRSAPrivateKey:()=>Tf,pkixMessageToJwk:()=>uc,pkixMessageToRSAPublicKey:()=>pc,pkixToJwk:()=>Zg,pkixToRSAPublicKey:()=>hc});var Gg=new Uint32Array([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]),Fe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ue=new Uint32Array(64),ic=class extends Ur{constructor(){super(64,32,8,!1),this.A=Fe[0]|0,this.B=Fe[1]|0,this.C=Fe[2]|0,this.D=Fe[3]|0,this.E=Fe[4]|0,this.F=Fe[5]|0,this.G=Fe[6]|0,this.H=Fe[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|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(t,e){for(let f=0;f<16;f++,e+=4)Ue[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Ue[f-15],m=Ue[f-2],p=Qt(d,7)^Qt(d,18)^d>>>3,g=Qt(m,17)^Qt(m,19)^m>>>10;Ue[f]=g+Ue[f-7]+p+Ue[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=Qt(a,6)^Qt(a,11)^Qt(a,25),m=u+d+ju(a,c,l)+Gg[f]+Ue[f]|0,g=(Qt(n,2)^Qt(n,13)^Qt(n,22))+Xu(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|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(){Ue.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Vr=No(()=>new ic);var $r=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=On.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return at.createV1(114,this._multihash)}toString(){return z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}verify(t,e){return Pf(this.jwk,e,t)}},Nn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=On.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}sign(t){return Cf(this.jwk,t)}};var ac=8192,cc=18,Wg=1062,jg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Xg(r){let t=pe(r);return lc(t)}function lc(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function Yg(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 R("JWK was missing components");return Zt([kt(Uint8Array.from([0])),kt(T(r.n,"base64url")),kt(T(r.e,"base64url")),kt(T(r.d,"base64url")),kt(T(r.p,"base64url")),kt(T(r.q,"base64url")),kt(T(r.dp,"base64url")),kt(T(r.dq,"base64url")),kt(T(r.qi,"base64url"))]).subarray()}function Zg(r){let t=pe(r,{offset:0});return uc(t)}function uc(r){let t=pe(r[1],{offset:0});return{kty:"RSA",n:M(t[0],"base64url"),e:M(t[1],"base64url")}}function fc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Zt([jg,Sn(Zt([kt(T(r.n,"base64url")),kt(T(r.e,"base64url"))]))]).subarray()}function Tf(r){let t=pe(r);return dc(t)}function dc(r){let t=lc(r);return mc(t)}function hc(r,t){if(r.byteLength>=Wg)throw new _r("Key size is too large");let e=pe(r,{offset:0});return pc(e,r,t)}function pc(r,t,e){let n=uc(r);if(e==null){let o=Vr(ce.encode({Type:ft.RSA,Data:t}));e=Xt(cc,o)}return new $r(n,e)}function mc(r){if(kf(r)>ac)throw new R("Key size is too large");let t=Lf(r),e=Vr(ce.encode({Type:ft.RSA,Data:fc(t.publicKey)})),n=Xt(cc,e);return new Nn(t.privateKey,new $r(t.publicKey,n))}async function gc(r){if(r>ac)throw new R("Key size is too large");let t=await Df(r),e=Vr(ce.encode({Type:ft.RSA,Data:fc(t.publicKey)})),n=Xt(cc,e);return new Nn(t.privateKey,new $r(t.publicKey,n))}function Lf(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Df(r){let t=await Be.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Qg(t);return{privateKey:e[0],publicKey:e[1]}}async function Cf(r,t){let e=await Be.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Be.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Pf(r,t,e){let n=await Be.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Be.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Qg(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([Be.get().subtle.exportKey("jwk",r.privateKey),Be.get().subtle.exportKey("jwk",r.publicKey)])}function kf(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return T(r.n,"base64url").length*8}var Jo=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Hu(t);let n=An(e);if(this.iHash=t.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?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Or(this),this.iHash.update(t),this}digestInto(t){Or(this),Nr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},yc=(r,t,e)=>new Jo(r,t).update(e).digest();yc.create=(r,t)=>new Jo(r,t);function Rf(r){r.lowS!==void 0&&Jt("lowS",r.lowS),r.prehash!==void 0&&Jt("prehash",r.prehash)}function Jg(r){let t=Cn(r);ae(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:t0,hexToBytes:e0}=Uo,wc=class extends Error{constructor(t=""){super(t)}},be={Err:wc,_tlv:{encode:(r,t)=>{let{Err:e}=be;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Ye(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Ye(o.length/2|128):"";return Ye(r)+s+o+t},decode(r,t){let{Err:e}=be,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=be;if(r<xe)throw new t("integer: negative integers are not allowed");let e=Ye(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=be;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return t0(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=be,o=typeof r=="string"?e0(r):r;Kr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("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 t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=be,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},xe=BigInt(0),wt=BigInt(1),hv=BigInt(2),Mf=BigInt(3),pv=BigInt(4);function r0(r){let t=Jg(r),{Fp:e}=t,n=Ne(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let x=h.toAffine();return we(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=t,x=e.sqr(g),y=e.mul(x,g);return e.add(e.add(y,e.mul(g,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return _n(g,wt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=t;if(h&&typeof g!="bigint"){if(ke(g)&&(g=ge(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let E;try{E=typeof g=="bigint"?g:ye(ct("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=et(E,y)),Ft("private key",E,wt,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=Je((g,h)=>{let{px:w,py:x,pz:y}=g;if(e.eql(y,e.ONE))return{x:w,y:x};let E=g.is0();h==null&&(h=E?e.ONE:e.inv(y));let _=e.mul(w,h),D=e.mul(x,h),I=e.mul(y,h);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(I,e.ONE))throw new Error("invZ was invalid");return{x:_,y:D}}),f=Je(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let x=e.sqr(w),y=i(h);if(!e.eql(x,y))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!e.isValid(w)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let y=E=>e.eql(E,e.ZERO);return y(w)&&y(x)?d.ZERO:new d(w,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(w[y])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(ct("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return Vo(d,n,h,w)}_setWindowSize(h){p.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:D}=h,I=e.eql(e.mul(w,D),e.mul(E,y)),L=e.eql(e.mul(x,D),e.mul(_,y));return I&&L}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,x=e.mul(w,Mf),{px:y,py:E,pz:_}=this,D=e.ZERO,I=e.ZERO,L=e.ZERO,P=e.mul(y,y),nt=e.mul(E,E),W=e.mul(_,_),K=e.mul(y,E);return K=e.add(K,K),L=e.mul(y,_),L=e.add(L,L),D=e.mul(h,L),I=e.mul(x,W),I=e.add(D,I),D=e.sub(nt,I),I=e.add(nt,I),I=e.mul(D,I),D=e.mul(K,D),L=e.mul(x,L),W=e.mul(h,W),K=e.sub(P,W),K=e.mul(h,K),K=e.add(K,L),L=e.add(P,P),P=e.add(L,P),P=e.add(P,W),P=e.mul(P,K),I=e.add(I,P),W=e.mul(E,_),W=e.add(W,W),P=e.mul(W,K),D=e.sub(D,P),L=e.mul(W,nt),L=e.add(L,L),L=e.add(L,L),new d(D,I,L)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:D}=h,I=e.ZERO,L=e.ZERO,P=e.ZERO,nt=t.a,W=e.mul(t.b,Mf),K=e.mul(w,E),pt=e.mul(x,_),A=e.mul(y,D),k=e.add(w,x),v=e.add(E,_);k=e.mul(k,v),v=e.add(K,pt),k=e.sub(k,v),v=e.add(w,y);let b=e.add(E,D);return v=e.mul(v,b),b=e.add(K,A),v=e.sub(v,b),b=e.add(x,y),I=e.add(_,D),b=e.mul(b,I),I=e.add(pt,A),b=e.sub(b,I),P=e.mul(nt,v),I=e.mul(W,A),P=e.add(I,P),I=e.sub(pt,P),P=e.add(pt,P),L=e.mul(I,P),pt=e.add(K,K),pt=e.add(pt,K),A=e.mul(nt,A),v=e.mul(W,v),pt=e.add(pt,A),A=e.sub(K,A),A=e.mul(nt,A),v=e.add(v,A),K=e.mul(pt,v),L=e.add(L,K),K=e.mul(b,v),I=e.mul(k,I),I=e.sub(I,K),K=e.mul(k,pt),P=e.mul(b,P),P=e.add(P,K),new d(I,L,P)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return p.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:x}=t;Ft("scalar",h,xe,x);let y=d.ZERO;if(h===xe)return y;if(this.is0()||h===wt)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:D,k2:I}=w.splitScalar(h),L=y,P=y,nt=this;for(;_>xe||I>xe;)_&wt&&(L=L.add(nt)),I&wt&&(P=P.add(nt)),nt=nt.double(),_>>=wt,I>>=wt;return E&&(L=L.negate()),D&&(P=P.negate()),P=new d(e.mul(P.px,w.beta),P.py,P.pz),L.add(P)}multiply(h){let{endo:w,n:x}=t;Ft("scalar",h,wt,x);let y,E;if(w){let{k1neg:_,k1:D,k2neg:I,k2:L}=w.splitScalar(h),{p:P,f:nt}=this.wNAF(D),{p:W,f:K}=this.wNAF(L);P=p.constTimeNegate(_,P),W=p.constTimeNegate(I,W),W=new d(e.mul(W.px,w.beta),W.py,W.pz),y=P.add(W),E=nt.add(K)}else{let{p:_,f:D}=this.wNAF(h);y=_,E=D}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(D,I)=>I===xe||I===wt||!D.equals(y)?D.multiplyUnsafe(I):D.multiply(I),_=E(this,w).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===wt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===wt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Jt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Jt("isCompressed",h),ge(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,p=zo(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function n0(r){let t=Cn(r);return ae(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Nf(r){let t=n0(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(A){return et(A,n)}function a(A){return Ko(A,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=r0({...t,toBytes(A,k,v){let b=k.toAffine(),S=e.toBytes(b.x),C=we;return Jt("isCompressed",v),v?C(Uint8Array.from([k.hasEvenY()?2:3]),S):C(Uint8Array.from([4]),S,e.toBytes(b.y))},fromBytes(A){let k=A.length,v=A[0],b=A.subarray(1);if(k===o&&(v===2||v===3)){let S=ye(b);if(!_n(S,wt,e.ORDER))throw new Error("Point is not on curve");let C=u(S),N;try{N=e.sqrt(C)}catch(q){let B=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+B)}let O=(N&wt)===wt;return(v&1)===1!==O&&(N=e.neg(N)),{x:S,y:N}}else if(k===s&&v===4){let S=e.fromBytes(b.subarray(0,e.BYTES)),C=e.fromBytes(b.subarray(e.BYTES,2*e.BYTES));return{x:S,y:C}}else{let S=o,C=s;throw new Error("invalid Point, expected length of "+S+", or uncompressed "+C+", got "+k)}}}),d=A=>ge(Me(A,t.nByteLength));function m(A){let k=n>>wt;return A>k}function p(A){return m(A)?i(-A):A}let g=(A,k,v)=>ye(A.slice(k,v));class h{constructor(k,v,b){this.r=k,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(k){let v=t.nByteLength;return k=ct("compactSignature",k,v*2),new h(g(k,0,v),g(k,v,2*v))}static fromDER(k){let{r:v,s:b}=be.toSig(ct("DER",k));return new h(v,b)}assertValidity(){Ft("r",this.r,wt,n),Ft("s",this.s,wt,n)}addRecoveryBit(k){return new h(this.r,this.s,k)}recoverPublicKey(k){let{r:v,s:b,recovery:S}=this,C=D(ct("msgHash",k));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let N=S===2||S===3?v+t.n:v;if(N>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let O=(S&1)===0?"02":"03",U=c.fromHex(O+d(N)),q=a(N),B=i(-C*q),Q=i(b*q),rt=c.BASE.multiplyAndAddUnsafe(U,B,Q);if(!rt)throw new Error("point at infinify");return rt.assertValidity(),rt}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ze(this.toDERHex())}toDERHex(){return be.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ze(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(A){try{return l(A),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let A=ka(t.n);return of(t.randomBytes(A),t.n)},precompute(A=8,k=c.BASE){return k._setWindowSize(A),k.multiply(BigInt(3)),k}};function x(A,k=!0){return c.fromPrivateKey(A).toRawBytes(k)}function y(A){let k=ke(A),v=typeof A=="string",b=(k||v)&&A.length;return k?b===o||b===s:v?b===2*o||b===2*s:A instanceof c}function E(A,k,v=!0){if(y(A))throw new Error("first arg must be private key");if(!y(k))throw new Error("second arg must be public key");return c.fromHex(k).multiply(l(A)).toRawBytes(v)}let _=t.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");let k=ye(A),v=A.length*8-t.nBitLength;return v>0?k>>BigInt(v):k},D=t.bits2int_modN||function(A){return i(_(A))},I=In(t.nBitLength);function L(A){return Ft("num < 2^"+t.nBitLength,A,xe,I),Me(A,t.nByteLength)}function P(A,k,v=nt){if(["recovered","canonical"].some(yt=>yt in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:S}=t,{lowS:C,prehash:N,extraEntropy:O}=v;C==null&&(C=!0),A=ct("msgHash",A),Rf(v),N&&(A=ct("prehashed msgHash",b(A)));let U=D(A),q=l(k),B=[L(q),L(U)];if(O!=null&&O!==!1){let yt=O===!0?S(e.BYTES):O;B.push(ct("extraEntropy",yt))}let Q=we(...B),rt=U;function gt(yt){let xt=_(yt);if(!f(xt))return;let Et=a(xt),Bt=c.BASE.multiply(xt).toAffine(),Tt=i(Bt.x);if(Tt===xe)return;let se=i(Et*i(rt+Tt*q));if(se===xe)return;let ue=(Bt.x===Tt?0:2)|Number(Bt.y&wt),fn=se;return C&&m(se)&&(fn=p(se),ue^=1),new h(Tt,fn,ue)}return{seed:Q,k2sig:gt}}let nt={lowS:t.lowS,prehash:!1},W={lowS:t.lowS,prehash:!1};function K(A,k,v=nt){let{seed:b,k2sig:S}=P(A,k,v),C=t;return Pa(C.hash.outputLen,C.nByteLength,C.hmac)(b,S)}c.BASE._setWindowSize(8);function pt(A,k,v,b=W){let S=A;k=ct("msgHash",k),v=ct("publicKey",v);let{lowS:C,prehash:N,format:O}=b;if(Rf(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(O!==void 0&&O!=="compact"&&O!=="der")throw new Error("format must be compact or der");let U=typeof S=="string"||ke(S),q=!U&&!O&&typeof S=="object"&&S!==null&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!U&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let B,Q;try{if(q&&(B=new h(S.r,S.s)),U){try{O!=="compact"&&(B=h.fromDER(S))}catch(ue){if(!(ue instanceof be.Err))throw ue}!B&&O!=="der"&&(B=h.fromCompact(S))}Q=c.fromHex(v)}catch{return!1}if(!B||C&&B.hasHighS())return!1;N&&(k=t.hash(k));let{r:rt,s:gt}=B,yt=D(k),xt=a(gt),Et=i(yt*xt),Bt=i(rt*xt),Tt=c.BASE.multiplyAndAddUnsafe(Q,Et,Bt)?.toAffine();return Tt?i(Tt.x)===rt:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:K,verify:pt,ProjectivePoint:c,Signature:h,utils:w}}function o0(r){return{hash:r,hmac:(t,...e)=>yc(r,t,va(...e)),randomBytes:Fr}}function Of(r,t){let e=n=>Nf({...r,...o0(n)});return{...e(t),create:e}}var Uf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Bf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),s0=BigInt(1),bc=BigInt(2),Ff=(r,t)=>(r+t/bc)/t;function i0(r){let t=Uf,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=st(u,e,t)*u%t,d=st(f,e,t)*u%t,m=st(d,bc,t)*l%t,p=st(m,o,t)*m%t,g=st(p,s,t)*p%t,h=st(g,a,t)*g%t,w=st(h,c,t)*h%t,x=st(w,a,t)*g%t,y=st(x,e,t)*u%t,E=st(y,i,t)*p%t,_=st(E,n,t)*l%t,D=st(_,bc,t);if(!xc.eql(xc.sqr(D),r))throw new Error("Cannot find square root");return D}var xc=Ne(Uf,void 0,void 0,{sqrt:i0}),Gt=Of({a:BigInt(0),b:BigInt(7),Fp:xc,n:Bf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Bf,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-s0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Ff(s*r,t),c=Ff(-n*r,t),l=et(r-a*e-c*o,t),u=et(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},Vr),Sv=BigInt(0);var Av=Gt.ProjectivePoint;function vc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Kf(r,t){let e=Mr.digest(t instanceof Uint8Array?t:t.subarray());if(vc(e))return e.then(({digest:n})=>Gt.sign(n,r).toDERRawBytes()).catch(n=>{throw new Rn(String(n))});try{return Gt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Rn(String(n))}}function qf(r,t,e){let n=Mr.digest(e instanceof Uint8Array?e:e.subarray());if(vc(n))return n.then(({digest:o})=>Gt.verify(t,o,r)).catch(o=>{throw new Mn(String(o))});try{return Gt.verify(t,n.digest,r)}catch(o){throw new Mn(String(o))}}var Bn=class{type="secp256k1";raw;_key;constructor(t){this._key=$f(t),this.raw=zf(this._key)}toMultihash(){return Yt.digest(Ht(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}verify(t,e){return qf(this._key,e,t)}},ts=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Vf(t),this.publicKey=new Bn(e??Hf(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:J(this.raw,t.raw)}sign(t){return Kf(this.raw,t)}};function Ec(r){return new Bn(r)}async function Gf(){let r=a0();return new ts(r)}function zf(r){return Gt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Vf(r){try{return Gt.getPublicKey(r,!0),r}catch(t){throw new hn(String(t))}}function $f(r){try{return Gt.ProjectivePoint.fromHex(r),r}catch(t){throw new _r(String(t))}}function Hf(r){try{return Gt.getPublicKey(r,!0)}catch(t){throw new hn(String(t))}}function a0(){return Gt.utils.randomPrivateKey()}async function Wf(r,t){if(r==="Ed25519")return gf();if(r==="secp256k1")return Gf();if(r==="RSA")return gc(c0(t));if(r==="ECDSA")return Vu(l0(t));throw new Pe}function Hr(r,t){let{Type:e,Data:n}=ce.decode(r),o=n??new Uint8Array;switch(e){case ft.RSA:return hc(o,t);case ft.Ed25519:return Ua(o);case ft.secp256k1:return Ec(o);case ft.ECDSA:return xa(o);default:throw new Pe}}function jf(r){let{Type:t,Data:e}=ce.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return Ua(n);case ft.secp256k1:return Ec(n);case ft.ECDSA:return xa(n);default:throw new Pe}}function Ht(r){return ce.encode({Type:ft[r.type],Data:r.raw})}function c0(r){return r==null?2048:parseInt(r,10)}function l0(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 R("Unsupported curve, should be P-256, P-384 or P-521")}var Xf=Symbol.for("nodejs.util.inspect.custom"),u0=114,Fn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bo]=!0;toString(){return this.string==null&&(this.string=z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(u0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return J(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return J(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Xf](){return`PeerId(${this.toString()})`}},Un=class extends Fn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Kn=class extends Fn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},qn=class extends Fn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},f0=2336,zn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Yt.digest(T(this.url))}[Xf](){return`PeerId(${this.url})`}[bo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(f0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}};var d0=114,Yf=2336;function le(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=zt(z.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Vn(at.parse(r));if(t==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=zt(t.decode(r))}return Gr(e)}function Sc(r){if(r.type==="Ed25519")return new Kn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new qn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Un({multihash:r.toCID().multihash,publicKey:r});throw new Pe}function Zf(r){return Sc(r.publicKey)}function Gr(r){if(p0(r))return new Un({multihash:r});if(h0(r))try{let t=jf(r);if(t.type==="Ed25519")return new Kn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new qn({multihash:r,publicKey:t})}catch{let e=M(r.digest);return new zn(new URL(e))}throw new So("Supplied PeerID Multihash is invalid")}function Vn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==d0&&r.code!==Yf)throw new Eo("Supplied PeerID CID is invalid");if(r.code===Yf){let t=M(r.multihash.digest);return new zn(new URL(t))}return Gr(r.multihash)}function h0(r){return r.code===Yt.code}function p0(r){return r.code===Mr.code}var dt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var _c=dn(Jf(),1);var Hn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Ic=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},td=r=>globalThis.DOMException===void 0?new Ic(r):new DOMException(r),ed=r=>{let t=r.reason===void 0?td("This operation was aborted."):r.reason;return t instanceof Error?t:td(t)};function Gn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:m}=t;m.aborted&&f(ed(m)),a=()=>{f(ed(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Hn;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}function Cc(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var Wn=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,id:e.id,run:t};if(this.size===0||this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Cc(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}setPriority(t,e){let n=this.#t.findIndex(s=>s.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[o]=this.#t.splice(n,1);this.enqueue(o.run,{priority:e,id:t})}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var Ke=class extends _c.default{#t;#e;#r=0;#a;#c;#p=0;#o;#l;#n;#m;#s=0;#u;#i;#g;#b=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Wn,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=t.interval,this.#n=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#x(){return this.#e||this.#r<this.#a}get#v(){return this.#s<this.#u}#E(){this.#s--,this.#f(),this.emit("next")}#S(){this.#w(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#o===void 0){let e=this.#p-t;if(e<0)this.#r=this.#t?this.#s:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#S()},e)),!0}return!1}#f(){if(this.#n.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 t=!this.#A;if(this.#x&&this.#v){let e=this.#n.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#r===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#t?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#d()}async#_(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#n.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#b++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=Gn(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#_(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof Hn&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#E()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#d(),this):this}pause(){this.#i=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#h("empty")}async onSizeLessThan(t){this.#n.size<t||await this.#h("next",()=>this.#n.size<t)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#h("idle")}async#h(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#n.size}sizeBy(t){return this.#n.filter(t).length}get pending(){return this.#s}get isPaused(){return this.#i}};function rs(r){let t=[$t.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Pc=60;function ns(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(t=>({name:t.name,type:$t[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:$t[t.type],TTL:t.TTL??t.ttl??Pc,data:t.data instanceof Uint8Array?M(t.data):t.data}))}}var y0=4;function Tc(r,t={}){let e=new Ke({concurrency:t.queryConcurrency??y0});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),rs(o.types).forEach(a=>{s.append("type",$t[a])}),o.onProgress?.(new dt("dns:query",{detail:n}));let i=await e.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=ns(await a.json());return o.onProgress?.(new dt("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function rd(){return[Tc("https://cloudflare-dns.com/dns-query"),Tc("https://dns.google/resolve")]}var sd=dn(od(),1);var Lc=class{lru;constructor(t){this.lru=(0,sd.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return ns({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,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:$t[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Pc)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function id(r){return new Lc(r)}var w0=1e3,os=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=id(t.cacheSize??w0),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=rd())}async query(t,e={}){let n=rs(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new dt("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new dt("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var $t;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})($t||($t={}));function ad(r={}){return new os(r)}var ss=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,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,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[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];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var cd=45,b0=15,Wr=new ss;function is(r){if(!(r.length>b0))return Wr.new(r).parseWith(()=>Wr.readIPv4Addr())}function as(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>cd))return Wr.new(r).parseWith(()=>Wr.readIPv6Addr())}function sr(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>cd)return;let e=Wr.new(r).parseWith(()=>Wr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function ld(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function ud(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function Dc(r){switch(r.length){case ir:return r.join(".");case ar:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function fd(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function dd(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var ir=4,ar=16,cS=parseInt("0xFFFF",16),x0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function jn(r,t){t.length===ar&&r.length===ir&&ld(t,0,11)&&(t=t.slice(12)),t.length===ir&&r.length===ar&&ud(r,x0,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function hd(r,t){if(typeof t=="string"&&(t=sr(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function kc(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=ir,o=is(t);if(o==null&&(n=ar,o=as(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Rc(s,8*n);return{network:jn(o,i),mask:i}}function Rc(r,t){if(t!==8*ir&&t!==8*ar)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var jr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=kc(t));else{let n=sr(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=sr(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Rc(o,8*n.length);this.network=jn(n,this.mask)}}contains(t){return hd({network:this.network,mask:this.mask},t)}toString(){let t=fd(this.mask),e=t!==-1?String(t):dd(this.mask);return Dc(this.network)+"/"+e}};function ne(r){return!!is(r)}function Xr(r){return!!as(r)}function cs(r){return!!sr(r)}var pd=ne,v0=Xr,Mc=function(r){let t=0;if(r=r.toString().trim(),pd(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(v0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=pd(e[n]),i;s&&(i=Mc(e[n]),e[n]=M(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,M(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},md=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Yr={},Nc={},S0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];S0.forEach(r=>{let t=A0(...r);Nc[t.code]=t,Yr[t.name]=t});function A0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function G(r){if(typeof r=="number"){if(Nc[r]!=null)return Nc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Yr[r]!=null)return Yr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var _0=G("ip4"),I0=G("ip6"),C0=G("ipcidr");function Uc(r,t){switch(G(r).code){case 4:case 41:return T0(t);case 42:return Fc(t);case 43:return M(t,"base10");case 6:case 273:case 33:case 132:return wd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fc(t);case 421:return R0(t);case 444:return yd(t);case 445:return yd(t);case 466:return k0(t);case 481:return globalThis.encodeURIComponent(Fc(t));default:return M(t,"base16")}}function Kc(r,t){switch(G(r).code){case 4:return gd(t);case 41:return gd(t);case 42:return Bc(t);case 43:return T(t,"base10");case 6:case 273:case 33:case 132:return zc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Bc(t);case 421:return L0(t);case 444:return M0(t);case 445:return N0(t);case 466:return D0(t);case 481:return Bc(globalThis.decodeURIComponent(t));default:return T(t,"base16")}}function qc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===_0.code||n===I0.code)&&(e=o),n===C0.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new jr(e,t)}var Oc=Object.values(xn).map(r=>r.decoder),P0=function(){let r=Oc[0].or(Oc[1]);return Oc.slice(2).forEach(t=>r=r.or(t)),r}();function gd(r){if(!cs(r))throw new Error("invalid ip address");return Mc(r)}function T0(r){let t=md(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!cs(t))throw new Error("invalid ip address");return t}function zc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function wd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Bc(r){let t=T(r),e=Uint8Array.from(_t(t.length));return Dt([e,t],e.length+t.length)}function Fc(r){let t=ee(r);if(r=r.slice(ht(t)),r.length!==t)throw new Error("inconsistent lengths");return M(r)}function L0(r){let t;r[0]==="Q"||r[0]==="1"?t=zt(z.decode(`z${r}`)).bytes:t=at.parse(r).multihash.bytes;let e=Uint8Array.from(_t(t.length));return Dt([e,t],e.length+t.length)}function D0(r){let t=P0.decode(r),e=Uint8Array.from(_t(t.length));return Dt([e,t],e.length+t.length)}function k0(r){let t=ee(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+M(e,"base64url")}function R0(r){let t=ee(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return M(e,"base58btc")}function M0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=qt.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=zc(n);return Dt([e,o],e.length+o.length)}function N0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=qt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=zc(n);return Dt([e,o],e.length+o.length)}function yd(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=M(t,"base32"),o=wd(e);return`${n}:${o}`}function bd(r){r=Vc(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=G(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new ls("invalid address: "+r);if(a.path===!0){n=Vc(o.slice(s).join("/")),t.push([a.code,Kc(a.code,n)]),e.push([a.code,n]);break}let c=Kc(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Uc(a.code,c)])}return{string:xd(e),bytes:us(t),tuples:t,stringTuples:e,path:n}}function $c(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=ht(s),a=G(s),c=O0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new ls("Invalid address Uint8Array: "+M(r,"base16"));t.push([s,l]);let u=Uc(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:xd(e),tuples:t,stringTuples:e,path:n}}function xd(r){let t=[];return r.map(e=>{let n=G(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Vc(t.join("/"))}function us(r){return Dt(r.map(t=>{let e=G(t[0]),n=Uint8Array.from(_t(e.code));return t.length>1&&t[1]!=null&&(n=Dt([n,t[1]])),n}))}function O0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ht(e)}}function Vc(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ls=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var B0=Symbol.for("nodejs.util.inspect.custom"),Gc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),F0=[G("dns").code,G("dns4").code,G("dns6").code,G("dnsaddr").code],Hc=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},fs=class r{bytes;#t;#e;#r;#a;[Gc]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=$c(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=bd(t)}else if(qe(t))e=$c(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=G("tcp"),a=G("udp"),c=G("ip4"),l=G("ip6"),u=G("dns6"),f=G("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(s=`%${p??""}`),F0.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${p??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=G(m).name==="tcp"?"tcp":"udp",o=parseInt(p??"")),(m===c.code||m===l.code)&&(e=G(m).name==="tcp"?"tcp":"udp",n=`${p??""}${s}`,t=m===l.code?6:4);if(t==null||e==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:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},G(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>G(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(us(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Yr.p2p.code&&t.push([n,o]),n===Yr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?M(z.decode(`z${n}`),"base58btc"):M(at.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return J(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Zr.get(e.name);if(n==null)throw new Hc(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>j(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[B0](){return`Multiaddr(${this.#t})`}};var Zr=new Map;function qe(r){return!!r?.[Gc]}function j(r){return new fs(r)}var U0=32,{code:K0}=G("dnsaddr"),Wc=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},cr=async function(t,e={}){let n=e.maxRecursiveDepth??U0;if(n===0)throw new Wc("Max recursive depth reached");let[,o]=t.stringTuples().find(([l])=>l===K0)??[],i=await(e?.dns??ad()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[$t.TXT]}),a=t.getPeerId(),c=[];for(let l of i.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let f=j(u);if(u.startsWith("/dnsaddr")){let d=await f.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var Td=dn(Pd(),1),ps=Td.default;var G0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:cr}},transportManager:{faultTolerance:Ge.FATAL_ALL}};async function Ld(r){let t=ps(G0,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return t}function W0(r,t){try{if(typeof r=="string"&&r.length>0)return j0(r);if(typeof r=="number"&&isFinite(r))return t?.long?Y0(r):X0(r);throw new Error("Value is not a string or number.")}catch(e){let n=Z0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function j0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var gs=W0;function X0(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Y0(r){let t=Math.abs(r);return t>=864e5?ms(r,t,864e5,"day"):t>=36e5?ms(r,t,36e5,"hour"):t>=6e4?ms(r,t,6e4,"minute"):t>=1e3?ms(r,t,1e3,"second"):`${r} ms`}function ms(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function Z0(r){return typeof r=="object"&&r!==null&&"message"in r}function Xc(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=gs,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let w=g,x=Number(new Date),y=x-(f||x);w.diff=y,w.prev=f,w.curr=x,f=x,h[0]=e.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let E=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(D,I)=>{if(D==="%%")return"%";E++;let L=e.formatters[I];if(typeof L=="function"){let P=h[E];D=L.call(w,P),h.splice(E,1),E--}return D}),e.formatArgs.call(w,h),(w.log||e.log).apply(w,h)}return g.namespace=u,g.useColors=e.useColors(),g.color=e.selectColor(u),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==e.namespaces&&(m=e.namespaces,p=e.enabled(u)),p),set:h=>{d=h}}),typeof e.init=="function"&&e.init(g),g}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.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 e.setupFormatters(e.formatters),e.enable(e.load()),e}var ys=oy(),Q0=["#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 J0(){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 ty(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gs(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var ey=console.debug??console.log??(()=>{});function ry(r){try{r?ys?.setItem("debug",r):ys?.removeItem("debug")}catch{}}function ny(){let r;try{r=ys?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function oy(){try{return localStorage}catch{}}function sy(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Dd=Xc({formatArgs:ty,save:ry,load:ny,useColors:J0,setupFormatters:sy,colors:Q0,storage:ys,log:ey});var Kt=Dd;Kt.formatters.b=r=>r==null?"undefined":z.baseEncode(r);Kt.formatters.t=r=>r==null?"undefined":qt.baseEncode(r);Kt.formatters.m=r=>r==null?"undefined":aa.baseEncode(r);Kt.formatters.p=r=>r==null?"undefined":r.toString();Kt.formatters.c=r=>r==null?"undefined":r.toString();Kt.formatters.k=r=>r==null?"undefined":r.toString();Kt.formatters.a=r=>r==null?"undefined":r.toString();Kt.formatters.e=r=>r==null?"undefined":kd(r.stack)??kd(r.message)??r.toString();function iy(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function ws(){return{forComponent(r){return ay(r)}}}function ay(r){let t=iy(`${r}:trace`);return Kt.enabled(`${r}:trace`)&&Kt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Kt(`${r}:trace`)),Object.assign(Kt(r),{error:Kt(`${r}:error`),trace:t})}function kd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function lr(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function bs(r){let t=zt(z.decode(`z${r}`));return Gr(t)}var ve=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return lr(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return lr(this.map.values(),t=>t.key)}values(){return lr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var ur=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return lr(this.set.entries(),t=>{let e=bs(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=bs(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return lr(this.set.values(),t=>bs(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var Yc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Rd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Md=new globalThis.TextEncoder;function cy(r,t){let e=Yc[t],n=Rd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function ly(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Yc[t],o=Rd[t],s=r;for(;s.length>0;){let i=Md.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Zc(r,{size:t=32,utf8Buffer:e}={}){if(!Yc[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return ly(r,t,e);r=Md.encode(r)}return cy(r,t)}var Xn={hash:r=>Number(Zc(r,{size:32})),hashV:(r,t)=>uy(Xn.hash(r,t))};function uy(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),T(t,"base16")}var Qc=64,oe=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Qc)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ut(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?J(this.fp,t.fp):!1}};function fr(r,t){return Math.floor(Math.random()*(t-r))+r}var dr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");let e=fr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var fy=500,Yn=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Xn,this.seed=t.seed??fr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=T(t));let e=new oe(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new dr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new dr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[fr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new dr(this.bucketSize));for(let a=0;a<fy;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new dr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=T(t));let e=new oe(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=T(t));let e=new oe(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dy={1:.5,2:.84,4:.95,8:.98};function hy(r=.001){return r>.002?2:r>1e-5?4:8}function Nd(r,t=.001){let e=hy(t),n=dy[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Qc);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var xs=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Xn,this.seed=t.seed??fr(0,Math.pow(2,10)),this.filterSeries=[new Yn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=T(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Yn({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=T(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=T(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Zn(r,t=.001,e){return new xs({...Nd(r,t),...e??{}})}var Qn;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ut(0),payloadType:ut(0),payload:ut(0),signature:ut(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Qn||(Qn={}));var vs=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var tn=class r{static createFromProtobuf=async t=>{let e=Qn.decode(t),n=Hr(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=Od(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new vs("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Qn.encode({publicKey:Ht(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return J(this.marshal(),t.marshal())}async validate(t){let e=Od(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},Od=(r,t,e)=>{let n=T(r),o=_t(n.byteLength),s=_t(t.length),i=_t(e.length);return new H(o,n,s,t,i,e)};function Bd(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var Fd="libp2p-peer-record",Ud=Uint8Array.from([3,1]);var Jn;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Nt((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:ut(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=>Mt(s,n.codec()),n.decode=(s,i)=>Rt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Nt((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:ut(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 or('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})),e),r.encode=n=>Mt(n,r.codec()),r.decode=(n,o)=>Rt(n,r.codec(),o)})(Jn||(Jn={}));var hr=class r{static createFromProtobuf=t=>{let e=Jn.decode(t),n=Gr(zt(e.peerId)),o=(e.addresses??[]).map(i=>j(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Fd;static CODEC=Ud;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Jn.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!Bd(this.multiaddrs,t.multiaddrs))}};function py(r){return r[Symbol.asyncIterator]!=null}function my(r){if(py(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var to=my;var ze={},en=r=>{r.addEventListener("message",t=>{en.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{en.dispatchEvent("message",r,t)})};en.addEventListener=(r,t)=>{ze[r]==null&&(ze[r]=[]),ze[r].push(t)};en.removeEventListener=(r,t)=>{ze[r]!=null&&(ze[r]=ze[r].filter(e=>e===t))};en.dispatchEvent=function(r,t,e){ze[r]!=null&&ze[r].forEach(n=>n(t,e))};var Jc=en;var tl="lock:worker:request-read",el="lock:worker:release-read",rl="lock:master:grant-read",nl="lock:worker:request-write",ol="lock:worker:release-write",sl="lock:master:grant-write";var Kd=(r=21)=>Math.random().toString().substring(2);var qd=(r,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)})}}}))},zd=(r,t,e,n)=>async()=>{let o=Kd();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},gy={singleProcess:!1},Vd=r=>{if(r=Object.assign({},gy,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return Jc.addEventListener("message",qd(e,"requestReadLock",tl,el,rl)),Jc.addEventListener("message",qd(e,"requestWriteLock",nl,ol,sl)),e}return{isWorker:!0,readLock:e=>zd(e,tl,rl,el),writeLock:e=>zd(e,nl,sl,ol)}};var pr={},Ve;async function il(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>Gn((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var yy=(r,t)=>{if(Ve.isWorker===!0)return{readLock:Ve.readLock(r,t),writeLock:Ve.writeLock(r,t)};let e=new Ke({concurrency:1}),n;return{async readLock(){if(n!=null)return il(n,t);n=new Ke({concurrency:t.concurrency,autoStart:!1});let o=n,s=il(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,il(e,t)}}},wy={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function al(r){let t=Object.assign({},wy,r);return Ve==null&&(Ve=Vd(t),Ve.isWorker!==!0&&(Ve.addEventListener("requestReadLock",e=>{pr[e.data.name]!=null&&pr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),Ve.addEventListener("requestWriteLock",async e=>{pr[e.data.name]!=null&&pr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),pr[t.name]==null&&(pr[t.name]=yy(t.name,t)),pr[t.name]}var Ee;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Nt((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:ut(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=>Mt(i,o.codec()),o.decode=(i,a)=>Rt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Nt((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),Ss.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=Ss.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Rt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Nt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Es.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 or('Decode error - map field "addresses" had too many elements');a.addresses.push(Es.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 or('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 kn('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 kn('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=>Mt(o,r.codec()),r.decode=(o,s)=>Rt(o,r.codec(),s)})(Ee||(Ee={}));var Es;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ut(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Es||(Es={}));var Ss;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Ss||(Ss={}));function by(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=z.decode(`z${r}`);e=zt(o)}let n=Hr(t.publicKey,e);return Sc(n)}function As(r,t,e){let n=Ee.decode(t);return _s(r,n,e)}function _s(r,t,e){let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:by(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function $d(r,t){return xy(r.addresses,t.addresses)&&vy(r.protocols,t.protocols)&&Ey(r.publicKey,t.publicKey)&&Sy(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Ay(r.metadata,t.metadata)&&_y(r.tags,t.tags)}function xy(r,t){return Gd(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!J(e.multiaddr,n.multiaddr)))}function vy(r,t){return Gd(r,t,(e,n)=>e===n)}function Ey(r,t){return Hd(r,t)}function Sy(r,t){return Hd(r,t)}function Ay(r,t){return Wd(r,t,(e,n)=>J(e,n))}function _y(r,t){return Wd(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function Hd(r,t){return r==null&&t==null?!0:r!=null&&t!=null?J(r,t):!1}function Gd(r,t,e){if(r.length!==t.length)return!1;for(let n=0;n<r.length;n++)if(!e(r[n],t[n]))return!1;return!0}function Wd(r,t,e){if(r.size!==t.size)return!1;for(let[n,o]of r.entries()){let s=t.get(n);if(s==null||!e(o,s))return!1}return!0}var Se="/",jd=new TextEncoder().encode(Se),Is=jd[0],mr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=T(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Is)throw new Error("Invalid key")}toString(t="utf8"){return M(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Se))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=jd),this._buf[0]!==Is){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Is,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Is;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Se).slice(1)}type(){return Iy(this.baseNamespace())}name(){return Cy(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Se)||(t+=Se),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Se):new r(t.slice(0,-1).join(Se))}child(t){return this.toString()===Se?t:t.toString()===Se?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Py(t.map(e=>e.namespaces()))])}};function Iy(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Cy(r){let t=r.split(":");return t[t.length-1]}function Py(r){return[].concat(...r)}var cl="/peers/";function eo(r){if(!xo(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new mr(`${cl}${t}`)}async function Xd(r,t,e,n){let o=new Map;for(let s of e){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=j(s.multiaddr)),!qe(s.multiaddr))throw new R("Multiaddr was invalid");if(!await t(r,s.multiaddr))continue;let i=s.isCertified??!1,a=s.multiaddr.toString(),c=o.get(a);c!=null?s.isCertified=c.isCertified||i:o.set(a,{multiaddr:s.multiaddr,isCertified:i})}return[...o.values()].sort((s,i)=>s.multiaddr.toString().localeCompare(i.multiaddr.toString())).map(({isCertified:s,multiaddr:i})=>({isCertified:s,multiaddr:i.bytes}))}async function Ps(r,t,e,n){if(t==null)throw new R("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new R("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(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Cs(d,{validate:Yd})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Cs(d,{validate:Zd,map:Qd})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[m,p]of d)p==null?a.delete(m):a.set(m,p);a=Cs([...a.entries()],{validate:Yd})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),m=new Map(c);for(let[p,g]of d)g==null?m.delete(p):m.set(p,g);c=Cs([...m.entries()],{validate:Zd,map:Qd})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Ht(o.id.publicKey):t.publicKey!=null?u=Ht(t.publicKey):r.publicKey!=null&&(u=Ht(r.publicKey));let f={addresses:await Xd(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(m=>J(m.multiaddr,m.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Cs(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function Yd(r,t){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function Zd(r,t){if(typeof r!="string")throw new R("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new R("Tag value must be an integer");if(t.value<0||t.value>100)throw new R("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new R("Tag ttl must be an integer");if(t.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Qd(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Jd(r){let t=r.toString().split("/")[2],e=at.parse(t,qt);return Vn(e)}function ll(r,t,e){let n=Jd(r);return As(n,t,e)}function Ty(r,t){return{prefix:cl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(ll(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(ll(n.key,n.value,t),ll(o.key,o.value,t)))}}var Ts=class{peerId;datastore;lock;addressFilter;log;maxAddressAge;maxPeerAge;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=al({name:"peer-store",singleProcess:!0}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}async has(t){try{return await this.load(t),!0}catch(e){if(e.name!=="NotFoundError")throw e}return!1}async delete(t){this.peerId.equals(t)||await this.datastore.delete(eo(t))}async load(t){let e=eo(t),n=await this.datastore.get(e),o=Ee.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new We;return _s(t,o,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e){let n=await this.#t(t),o=await Ps(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,o,n)}async patch(t,e){let n=await this.#t(t),o=await Ps(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#e(t,o,n)}async merge(t,e){let n=await this.#t(t),o=await Ps(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#e(t,o,n)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(Ty(t??{},this.maxAddressAge))){let o=Jd(e);if(o.equals(this.peerId))continue;let s=Ee.decode(n);if(this.#r(o,s)){await this.datastore.delete(e);continue}yield _s(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t){try{let e=eo(t),n=await this.datastore.get(e),o=Ee.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new We;return{peerPB:o,peer:As(t,n,this.maxAddressAge)}}catch(e){e.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",e)}}async#e(t,e,n){e.updated=Date.now();let o=Ee.encode(e);return await this.datastore.put(eo(t),o),{peer:As(t,o,this.maxAddressAge),previous:n?.peer,updated:n==null||!$d(e,n.peerPB)}}#r(t,e){if(e.updated==null)return!0;if(this.peerId.equals(t))return!1;let n=e.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=e.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var ul=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Ts(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await to(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),e()}}async has(t){this.log.trace("has await read lock");let e=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),e()}}async get(t){this.log.trace("get await read lock");let e=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),e()}}async save(t,e){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await tn.openAndCertify(t,hr.DOMAIN),o=Vn(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=hr.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await tn.createFromProtobuf(i.peerRecordEnvelope),c=hr.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function th(r,t={}){return new ul(r,t)}var Ls=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function Ly(r){return r[Symbol.asyncIterator]!=null}function Dy(r){if(Ly(r))return(async()=>{for await(let t of r);})();for(let t of r);}var fl=Dy;function ky(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var eh=ky;function Ry(r){return r[Symbol.asyncIterator]!=null}function My(r,t){let e=0;if(Ry(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=eh(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var gr=My;function Ny(r){return r[Symbol.asyncIterator]!=null}function Oy(r,t){return Ny(r)?async function*(){yield*(await to(r)).sort(t)}():function*(){yield*to(r).sort(t)}()}var dl=Oy;function By(r){return r[Symbol.asyncIterator]!=null}function Fy(r,t){return By(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var hl=Fy;var Ds=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await fl(this.putMany(t,n)),t=[],await fl(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=gr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>gr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>dl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=gr(n,()=>o++>=s)}return t.limit!=null&&(n=hl(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=gr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>gr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>dl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=gr(n,()=>s++>=o)}return t.limit!=null&&(n=hl(n,t.limit)),n}};var ks=class extends Ds{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new Ls;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new mr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new mr(t)}};function rh(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var oh=dn(nh(),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"],Ky=Uy.map(r=>new oh.Netmask(r));function pl(r){for(let t of Ky)if(t.contains(r))return!0;return!1}function qy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function zy(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return pl(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 $y(r){let t=r.split(":"),e=t[t.length-1];return pl(e)}function Hy(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 $e(r){return ne(r)?pl(r):qy(r)?zy(r):Vy(r)?$y(r):Xr(r)?Hy(r):void 0}var Gy=r=>r.toString().split("/").slice(1),rn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),V=r=>({match:t=>rn(e=>e===r).match(t),pattern:r}),yr=()=>({match:r=>rn(t=>typeof t=="string").match(r),pattern:"{string}"}),no=()=>({match:r=>rn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),tt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{z.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),oo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ca.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Pt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),$=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function it(...r){function t(o){let s=Gy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Wy=tt(),sh=it(Wy),Ms=$(V("dns4"),yr()),Ns=$(V("dns6"),yr()),Os=$(V("dnsaddr"),yr()),gl=$(V("dns"),yr()),vI=it(Ms,Y(tt())),EI=it(Ns,Y(tt())),SI=it(Os,Y(tt())),AI=it(Pt(gl,Os,Ms,Ns),Y(tt())),ih=$(V("ip4"),rn(ne)),ah=$(V("ip6"),rn(Xr)),yl=Pt(ih,ah),Ae=Pt(yl,gl,Ms,Ns,Os),_I=it(Pt(yl,$(Pt(gl,Os,Ms,Ns),Y(tt())))),wl=it(ih),bl=it(ah),II=it(yl),xl=$(Ae,V("tcp"),no()),so=$(Ae,V("udp"),no()),io=it($(xl,Y(tt()))),CI=it(so),vl=$(so,V("quic"),Y(tt())),Bs=$(so,V("quic-v1"),Y(tt())),jy=Pt(vl,Bs),PI=it(vl),ch=it(Bs),ml=Pt(Ae,xl,so,vl,Bs),lh=Pt($(ml,V("ws"),Y(tt()))),wr=it(lh),uh=Pt($(ml,V("wss"),Y(tt())),$(ml,V("tls"),Y($(V("sni"),yr())),V("ws"),Y(tt()))),ao=it(uh),fh=$(so,V("webrtc-direct"),Y(oo()),Y(oo()),Y(tt())),El=it(fh),dh=$(Bs,V("webtransport"),Y(oo()),Y(oo()),Y(tt())),Sl=it(dh),Rs=Pt(lh,uh,$(xl,Y(tt())),$(jy,Y(tt())),$(Ae,Y(tt())),fh,dh,tt()),TI=it(Rs),Xy=$(Rs,V("p2p-circuit"),tt()),co=it(Xy),Yy=Pt($(Rs,V("p2p-circuit"),V("webrtc"),Y(tt())),$(Rs,V("webrtc"),Y(tt())),$(V("webrtc"),Y(tt()))),Al=it(Yy),Zy=Pt($(Ae,V("tcp"),no(),V("http"),Y(tt())),$(Ae,V("http"),Y(tt()))),LI=it(Zy),Qy=Pt($(Ae,V("tcp"),Pt($(V("443"),V("http")),$(no(),V("https"))),Y(tt())),$(Ae,V("tls"),V("http"),Y(tt())),$(Ae,V("https"),Y(tt()))),DI=it(Qy),Jy=Pt($(V("memory"),yr(),Y(tt()))),kI=it(Jy);var hh=864e13;var tw=448,_l=449,ew=53,rw=54,nw=55,ow=56,Fs=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(t){let e=this.findHost(t);for(let n of this.mappings.values())if(n.domain===e)return!0;return!1}add(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t);let o=$e(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?hh-Date.now():0,lastVerified:o?hh-Date.now():void 0})})}remove(t){let e=this.findHost(t),n=!1;for(let[o,s]of this.mappings.entries())s.domain===e&&(this.log("removing %s to %s DNS mapping %e",o,s.domain,new Error("where")),this.mappings.delete(o),n=n||s.verified);return n}getAll(t){let e=[];for(let n=0;n<t.length;n++){let s=t[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)&&(t.splice(n,1),n--,e.push({multiaddr:j(`/${s.map(u=>[G(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===tw&&t[n+1]?.[0]!==_l)return t.splice(n+1,0,[_l,e]),!0;return!1}confirm(t,e){let n=this.findHost(t),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()+e,i.lastVerified=Date.now());return o}unconfirm(t,e){let n=this.findHost(t),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()+e);return o}findHost(t){for(let e of t.stringTuples())if(e[0]===_l||e[0]===ew||e[0]===rw||e[0]===nw||e[0]===ow)return e[1]}};var Il=4,Cl=41,Pl=6,sw=273,Us=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(t){let e=t.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===e[0][1])return!0;return!1}add(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${s}`,a=this.mappings.get(i)??[],c={internalIp:t,internalPort:e,externalIp:n,externalPort:o,externalFamily:ne(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(t){let e=t.stringTuples(),n=e[0][1]??"",o=e[1][0]===Pl?"tcp":"udp",s=parseInt(e[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(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===Il||o[0][0]===Cl)&&o[1][0]===Pl?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Il||o[0][0]===Cl)&&o[1][0]===sw&&(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?Il:Cl,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:j(`/${o.map(c=>[G(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return e}confirm(t,e){let o=t.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()+e,a.lastVerified=Date.now());return s}unconfirm(t,e){let n=t.stringTuples(),o=n[0][1]??"",s=n[1][0]===Pl?"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()+e)}return a}};function ph(r){try{let[[t,e]]=r.stringTuples();if(e==null)return!1;if(t===4)return e.startsWith("169.254.");if(t===41)return e.toLowerCase().startsWith("fe80")}catch{}return!1}function Ks(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function br(r){try{if(!Ks(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:$e(t)??!1}catch{}return!0}var iw={maxObservedAddresses:10},qs=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=e.maxObservedAddresses??iw.maxObservedAddresses}has(t){return this.addresses.has(t.toString())}removePrefixed(t){for(let e of this.addresses.keys())e.toString().startsWith(t)&&this.addresses.delete(e)}add(t){this.addresses.size!==this.maxObservedAddresses&&(br(t)||ph(t)||(this.log("adding observed address %a",t),this.addresses.set(t.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([t,e])=>({multiaddr:j(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){let e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){let n=t.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var aw=[4,41,53,54,55,56];function Tl(r){try{let[[t]]=r.stringTuples();return aw.includes(t)}catch{}return!1}var cw={maxObservedAddresses:10},zs=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=e.maxObservedAddresses??cw.maxObservedAddresses}get(t,e){if(br(t))return{multiaddr:t,verified:!0,type:"transport",expires:Date.now()+e,lastVerified:Date.now()};let n=this.toKey(t),o=this.addresses.get(n);return o==null&&(o={verified:!Tl(t),expires:0},this.addresses.set(n,o)),{multiaddr:t,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(t){let e=this.toKey(t);return this.addresses.has(e)}remove(t){let e=this.toKey(t),n=this.addresses.get(e)?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(e),n}confirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+e,this.addresses.set(n,o),s}toKey(t){if(Tl(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var mh=6e4,gh={maxObservedAddresses:10,addressVerificationTTL:mh*10,addressVerificationRetry:mh*5},lw=r=>r;function Ll(r,t){let e=r.getPeerId();return e!=null&&le(e).equals(t)&&(r=r.decapsulate(j(`/p2p/${t.toString()}`))),r}var Vs=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.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 qs(t,e),this.dnsMappings=new Fs(t,e),this.ipMappings=new Us(t,e),this.transportAddresses=new zs(t,e),this.announceFilter=e.announceFilter??lw,this.observedAddressFilter=Zn(1024),this.addressVerificationTTL=e.addressVerificationTTL??gh.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??gh.addressVerificationRetry,this._updatePeerStoreAddresses=rh(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>j(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>j(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>j(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){let e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=Ll(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=Ll(t,this.components.peerId);let n=!0;(e?.type==="transport"||this.transportAddresses.has(t))&&!this.transportAddresses.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="dns-mapping"||this.dnsMappings.has(t))&&!this.dnsMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="ip-mapping"||this.ipMappings.has(t))&&!this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="observed"||this.observed.has(t))&&(this.maybeUpgradeToIPMapping(t)?(this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(t,e){t=Ll(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let t=new Set,e=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return t.has(o)?!1:(t.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(e.map(n=>{let o=j(n);return o.protos().pop()?.path===!0||o.getPeerId()===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(t)}),t.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];return e=e.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),e=e.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))),e=e.concat(this.observed.getAll()),e=e.concat(this.ipMappings.getAll(e)),e=e.concat(this.dnsMappings.getAll(e)),e}addDNSMapping(t,e){this.dnsMappings.add(t,e)}removeDNSMapping(t){this.dnsMappings.remove(j(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${ne(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(j(`/ip${ne(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(t){if(this.ipMappings.has(t))return!1;let e=t.toOptions();if(e.family===6||e.host==="127.0.0.1"||$e(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>wr.exactMatch(s)||ao.exactMatch(s),s=>io.exactMatch(s),s=>ch.exactMatch(s)];for(let s of o){if(!s(t))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(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var yh;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(yh||(yh={}));var $s=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Hs=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},nn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},lo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Gs=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Ws=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},js=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},uo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Xs=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Ys=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Zs=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Qs=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Js=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},xr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},vr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},ti=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var Dl=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=ws())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Po(e)).map(async e=>{await e[t]?.()}))}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")}},fw=["metrics","connectionProtector","dns"],dw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function wh(r={}){let t=new Dl(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!dw.includes(o)){let i=t.components[o];if(i==null&&!fw.includes(o))throw new $s(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function bh(r){let t={};for(let e of Object.values(r.components))for(let n of hw(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of pw(e))if(t[n]!==!0)throw new Hs(`Service "${mw(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function hw(r){return Array.isArray(r?.[mn])?r[mn]:[]}function pw(r){return Array.isArray(r?.[Gi])?r[Gi]:[]}function mw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var gw=4,yw=41;function xh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(wr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===gw||e[0][0]===yw?!!$e(`${e[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}}var vh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},ww=new WeakMap;function bw({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(vh());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(vh())},u=()=>{o&&o.removeEventListener("abort",l)},f=new Promise((d,m)=>{i=()=>{u(),d(n)},a=m,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",l,{once:!0}),ww.set(f,()=>{c(s),s=null,i()}),f}}var xw=bw(),Eh=xw;var ei=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},ri=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ni=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new kl}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ei("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Eh(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},kl=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function oi(r){if(xo(r))return{peerId:r,multiaddrs:[]};let t=Array.isArray(r)?r:[r],e;if(t.length>0){let n=t[0].getPeerId();e=n==null?void 0:le(n),t.forEach(o=>{if(!qe(o))throw new Ce("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=le(s);if(e?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!sh.exactMatch(n)),{peerId:e,multiaddrs:t}}var vw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Sh(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??vw;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var Ah="last-dial-failure",_h="last-dial-success";var si=100,ii=50;async function Ih(r,t){let e=!1;for(let o of Zr.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}function fo(r){try{let t;if(typeof r=="string"?t=j(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return qc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Ew={maxConnections:si,allow:[]},ai=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??Ew.maxConnections,this.allow=(e.allow??[]).map(n=>fo(n)),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.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(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new ve;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((u,f)=>u+f.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await Sh(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(t,e){return t.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=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};function X(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ci=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},on=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ci(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new ci(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Rl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ch(r={}){return Sw(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Sw(r,t){t=t??{};let e=t.onEnd,n=new on,o,s,i,a=X(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(y){w(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=X()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new on,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new on,d(),{done:!0}),p=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,y;w!=null&&(x=new Promise((E,_)=>{y=()=>{_(new Rl)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var Ml=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function sn(r,t,e,n){let o=new Ml(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var li=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function bt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new li(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new li(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var ui=class{deferred;signal;constructor(t){this.signal=t,this.deferred=X(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Aw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var fi=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Aw(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new jt),this.cleanup())}async join(t={}){let e=new ui(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await bt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var cn=class extends de{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ri;let n=new fi(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).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("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new jt)}),this.clear()}async onEmpty(t){this.size!==0&&await sn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await sn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await sn(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Ch({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var di=class extends cn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function _e(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function Ph(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Nl(r){if(!Ks(r))return!1;let{address:t}=r.nodeAddress();return Ph(t)}function _w(r,t){let e=io.exactMatch(r.multiaddr),n=io.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=ao.exactMatch(r.multiaddr),s=ao.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=wr.exactMatch(r.multiaddr),a=wr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Al.exactMatch(r.multiaddr),l=Al.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=El.exactMatch(r.multiaddr),f=El.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Sl.exactMatch(r.multiaddr),m=Sl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function Iw(r,t){let e=Nl(r.multiaddr),n=Nl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Cw(r,t){let e=br(r.multiaddr),n=br(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Pw(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Tw(r,t){let e=co.exactMatch(r.multiaddr),n=co.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Th(r){return r.sort(_w).sort(Pw).sort(Tw).sort(Cw).sort(Iw)}var hi={maxParallelDials:ii,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:cr}},pi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??hi.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??hi.maxDialQueueLength,this.dialTimeout=e.dialTimeout??hi.dialTimeout,this.connections=e.connections??new ve,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,o]of Object.entries(e.resolvers??{}))Zr.set(n,o);this.queue=new di({concurrency:e.maxParallelDials??hi.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==jt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=oi(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new dt("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Pr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new dt("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new dt("dial-queue:start-dial"));let c=_e([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Ul,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.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(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let m of d){if(s.has(m.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",m.multiaddr,n);continue}u.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(m=>m.multiaddr.toString())),t?.onProgress?.(new dt("dial-queue:calculated-addresses",u));for(let m of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,t.peerId),new Pr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(m.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",m.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[_h]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return p}catch(p){if(this.log.error("dial failed to %a",m.multiaddr,p),s.add(m.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Ah]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new _o(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:j(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Pr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new uo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);o.push(...f.addresses),this.log("loaded multiaddrs for %p",t,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",t);try{let f=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,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",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Ih(f.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(m=>({multiaddr:m,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{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 t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),m=a.get(d);if(m!=null){m.isCertified=m.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Zs("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?Th(l):l.sort(this.addressSorter);if(u.length===0)throw new uo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!co.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var mi=class extends cn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Oh=dn(Mh(),1);var Dw=Object.prototype.toString,kw=r=>Dw.call(r)==="[object Error]",Rw=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 Kl(r){return r&&kw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Rw.has(r.message):!1}var ql=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},Nh=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function zl(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=Oh.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof ql)throw c.originalError;if(c instanceof TypeError&&!Kl(c))throw c;if(Nh(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Nh(l,a,t),i(),n(l)}}})})}var gi=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new mi({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.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(t){if(!this.started)return;let e=await this.peerStore.get(t);Bh(e)&&(this.queue.has(t)||this.queue.add(async n=>{await zl(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(Hi)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>Bh(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function Bh(r){for(let t of r.tags.keys())if(t.startsWith(Hi))return!0;return!1}var Ul=50,Vl={maxConnections:si,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},yi=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??Vl.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new ve,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>fo(n)),this.deny=(e.deny??[]).map(n=>fo(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Vl.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ni({points:e.inboundConnectionThreshold??Vl.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ai({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>j(n))}),this.dialQueue=new pi(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??ii,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:cr},connections:this.connections}),this.reconnectQueue=new gi({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};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))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await uu(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 fu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),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:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new fe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=oi(t);if(this.peerId.equals(n))throw new Cr("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new dt("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Ul});if(o.status!=="open")throw new Ir("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Ce("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>j(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var ln=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(t){this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timeSpan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(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=t;this.previousTime=e}};var Ow=1.2,Bw=2,Fw=2e3,wi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new ln(t.interval??5e3),this.failure=new ln(t.interval??5e3),this.next=new ln(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??Bw,this.timeoutMultiplier=t.timeoutMultiplier??Ow,this.minTimeout=t.minTimeout??Fw,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=_e([t.signal,n]);return o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var $l=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await bt(this.readNext.promise,e?.signal,e)}};function Fh(){return new $l}var bi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Uh(r,t){let e=Fh();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new H;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await bt(n.next(),i?.signal);if(l===!0)throw new bi("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Uw=1e4,Kw="1.0.0",qw="ping",zw="ipfs",Kh=32,Vw=!0,xi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??zw}/${qw}/${Kw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Uw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Vw,this.timeout=new wi({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[mn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Uh(o);e=Date.now(),await Promise.all([s.write(zr(Kh),{signal:n}),s.read({bytes:Kh,signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):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 Hl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await bt(this.readNext.promise,e?.signal,e)}};function qh(){return new Hl}function $w(r){return r[Symbol.asyncIterator]!=null}async function Hw(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*Gw(r){let t=qh();Hw(r,t).catch(()=>{}),yield*t}function*Ww(r){for(let t of r)yield*t}function jw(...r){let t=[];for(let e of r)$w(e)||t.push(e);return t.length===r.length?Ww(t):Gw(r)}var ho=jw;var vi=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.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=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:M(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(t,e={}){if(this.routers.length===0)throw new nn("No content routers available");let n=this,o=new ur;for await(let s of ho(...n.routers.map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new nn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new nn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new fe;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new fe;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var Ei=globalThis.CustomEvent??Event;async function*Gl(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=X(),a=X(),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===e&&(i=X(),await i.promise),u)break;let g={done:!1};s.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,o.dispatchEvent(new Ei("task-complete"))},h=>{g.done=!0,g.err=h,o.dispatchEvent(new Ei("task-complete"))})}c=!0,o.dispatchEvent(new Ei("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ei("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*m(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=X(),await a.promise),l!=null)throw l;if(n?yield*d():yield*m(),c&&s.length===0)break}}var Si=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:M(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(t,e){if(this.routers.length===0)throw new lo("No peer routers available");if(t.toString()===this.peerId.toString())throw new Gs("Should not try to find self");let n=this,o=ho(...this.routers.map(s=>async function*(){try{yield await s.findPeer(t,e)}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}),s;throw new We}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new lo("No peer routers available");let n=this,o=Zn(1024);for await(let s of Gl(async function*(){let i=ho(...n.routers.map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,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}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Ai=class extends de{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.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(t){this.walking||this.startWalk(),this.walkers++;let e=_e([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=X(),yield(await sn(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.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 t=_e([this.walkController.signal,this.shutdownController.signal]);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=zr(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.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 bt(this.needNext.promise,t)),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()-e),this.walking=!1})}};var Wl=32,jl=64,_i=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,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(t){let e=this.handlers.get(t);if(e==null)throw new Ws(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&n?.force!==!0)throw new js(`Handler already registered for protocol ${t}`);let o=ps.bind({ignoreUndefined:!0})({maxInboundStreams:Wl,maxOutboundStreams:jl},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(t,e){if(e==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Xl=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function zh(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Xl({name:t,metrics:e}):n=new Map,n}var Ii=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=zh({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??Ge.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new R("Transport must have a valid tag");if(this.transports.has(e))throw new R(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new ti(`No transport available for address ${String(t)}`);return e?.onProgress?.(new dt("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new fe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new Xs)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);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})}),wl.matches(c)?e.ipv4.attempts++:bl.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),wl.matches(c)&&e.ipv4.success++,bl.matches(c)&&e.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),e.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(e)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Ge.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Ys(`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
3
|
${[...e.errors.entries()].map(([s,i])=>`
|
|
4
4
|
${s}: ${`${i.stack??i}`.split(`
|
|
5
5
|
`).join(`
|
|
6
6
|
`)}
|
|
7
|
-
`).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var vt="/multistream/1.0.0";var
|
|
8
|
-
`);async function
|
|
9
|
-
`),i=
|
|
10
|
-
`);await
|
|
11
|
-
`),e),e.log.trace("select: reading protocol response");let l=await
|
|
12
|
-
`;yield new
|
|
13
|
-
`),_t(
|
|
14
|
-
`),
|
|
15
|
-
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',vt,t)}finally{c=!0,l=!1,u.resolve()}}async function w(){if(d){await m.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let x=await
|
|
16
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',vt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await
|
|
17
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new
|
|
18
|
-
`))),
|
|
19
|
-
`));e.log.trace('handle: respond with "%s" for %s',t,o),await
|
|
20
|
-
`),e),e.log('handle: responded with "na" for "%s"',o)}}var Aw=500,zl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Yl]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new go("the connection is being closed");if(this.status==="closed")throw new Sr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Ir("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(Aw);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}};function Lh(r){return new zl(r)}function Iw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Ml}function Cw(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??Bl}function Dh(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var ki=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Ws(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Se([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(t),!n)throw new Xs("Connection denied");await this.shouldBlockConnection("denyInboundConnection",t),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ae(n),await this.shouldBlockConnection("denyOutboundConnection",o,t));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let l=t;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(t.log("protecting the %s connection",e),l=await u.protect(t,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new ft(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,u)}else{let u=t.remoteAddr.getPeerId();if(u==null)throw new _e(`${e} connection that skipped encryption must have a peer id`);let f=ae(u);c="native",s=f}if(s.equals(this.components.peerId)){let u=new Ar("Can not dial self");throw t.abort(u),u}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new ft(`upgrader:multiplex-${e}-connection`));let u=await(e==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,u),u}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),h=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await fo(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=Iw(x,this.components.registrar);if(Dh(x,"inbound",f)===y){let _=new vo(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=w.source,p.sink=w.sink,p.protocol=x,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:x})}).catch(async g=>{f.log.error("error handling incoming stream id %s - %e",p.id,g),p.timeline.close==null&&await p.close()})}}),u=async(p,g={})=>{if(l==null)throw new yr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await l.newStream();f.log.trace("started new stream %s for protocols %s",h.id,p);try{if(g.signal==null){h.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}h.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:x}=await lo(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=Cw(x,this.components.registrar,g),E=Dh(x,"outbound",f);if(E>=y){let _=new Eo(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw h.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),h.source=w.source,h.sink=w.sink,h.protocol=x,w.closeWrite!=null&&(h.closeWrite=w.closeWrite),w.closeRead!=null&&(h.closeRead=w.closeRead),w.close!=null&&(h.close=w.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(w){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",t.maConn.remoteAddr,p,w),h.timeline.close==null&&h.abort(w),w}},Promise.all([l.sink(s.source),s.sink(l.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let m=()=>{throw new yr("Connection is not multiplexed")};return f=Lh({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:u??m,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Ir("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await fo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new wr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new wr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await lo(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new wr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new wr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await lo(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new yr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await fo(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new yr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Ri="2.8.2-b2124c2db",Ni="js-libp2p";function Rh(r,t){return`${r??Ni}/${t??Ri} browser/${globalThis.navigator.userAgent}`}var Mi=class extends ue{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new ue,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??hs(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ni,s=t.nodeInfo?.version??Ri,i=this.components=th({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Rh(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Cs,connectionGater:rh(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",Od(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),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})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new ki(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(t.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new vi(this.components,t.transportManager)),this.configureComponent("connectionManager",new di(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new mi(this.components,t.connectionMonitor)),this.configureComponent("registrar",new xi(this.components)),this.configureComponent("addressManager",new Fs(this.components,t.addresses));let a=(t.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new wi(this.components,{routers:a}));let c=(t.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new gi(this.components,{routers:c})),this.configureComponent("randomWalk",new bi(this.components)),(t.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),t.services!=null)for(let l of Object.keys(t.services)){let u=t.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[Oi]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Oi])),f[Ui]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ui])),f[Fi]!=null&&(this.log("registering service %s for peer discovery",l),f[Fi].addEventListener?.("peer",d=>{this.#t(d)}))}eh(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}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(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}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(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new ar;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new R("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new R("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){Ue(t)&&(t=ae(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Nt([k("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=zr(o);return await this.peerStore.patch(t,{publicKey:s}),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Tw(r={}){r.privateKey??=await Lf("Ed25519");let t=new Mi({...await hd(r),peerId:Nf(r.privateKey)});return r.start!==!1&&await t.start(),t}return Wh(Pw);})();
|
|
7
|
+
`).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var vt="/multistream/1.0.0";var Yl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=X(),this.haveNext=X()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=X(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=X(),await bt(this.readNext.promise,e?.signal,e)}};function Vh(){return new Yl}var Ci=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function $h(r,t){let e=Vh();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new H;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await bt(n.next(),i?.signal);if(l===!0)throw new Ci("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Pi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ti=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Li=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function po(r,t={}){let e=$h(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ht(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??_t;return{read:async i=>{let a=-1,c=new H;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Pi("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Li("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ti("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new H(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new H(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var Xw=T(`
|
|
8
|
+
`);async function Sr(r,t,e){await r.write(t,e)}async function Hh(r,t,e){await r.writeV(t,e)}async function Yw(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==Xw[0])throw t.log.error("Invalid mss message - missing newline",e),new Ao("Missing newline");return e.sublist(0,-1)}async function He(r,t){let e=await Yw(r,t);return M(e.subarray())}async function mo(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return Zw(r,t[0],e);let n=po(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',vt,o);let s=T(`${vt}
|
|
9
|
+
`),i=T(`${o}
|
|
10
|
+
`);await Hh(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await He(n,e);if(e.log.trace('select: read "%s"',a),a===vt&&(e.log.trace("select: reading protocol response"),a=await He(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Sr(n,T(`${c}
|
|
11
|
+
`),e),e.log.trace("select: reading protocol response");let l=await He(n,e);if(e.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:n.unwrap(),protocol:c}}throw new pn("protocol selection failed")}function Zw(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=X(),c=!1,l=!1,u=X(),f=!1,d=!1,m=X(),p=po({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async x=>{let{sink:y}=p.unwrap();await y(async function*(){let E=!1;for await(let _ of x){if(l&&await u.promise,c)yield _;else{l=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',vt,t,_.byteLength);let D=`${t}
|
|
12
|
+
`;yield new H(Uint8Array.from([19]),T(`${vt}
|
|
13
|
+
`),_t(D.length),T(D),_).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',vt,t,_.byteLength),c=!0,l=!1,u.resolve(),g().catch(I=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,I)})}E=!0}E||await g()}())};async function g(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await h()),f||(e.log.trace("optimistic: doing read protocol for %s stream",t),await w())}finally{i=!1,s=!0,a.resolve()}}async function h(){if(l){await u.promise;return}l=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',vt,t),await p.writeV([T(`${vt}
|
|
14
|
+
`),T(`${t}
|
|
15
|
+
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',vt,t)}finally{c=!0,l=!1,u.resolve()}}async function w(){if(d){await m.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let x=await He(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',x),x===vt&&(x=await He(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',x,t),x!==t)throw new pn("protocol selection failed")}finally{f=!0,d=!1,m.resolve()}}if(r.source=async function*(){await g(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let x=r.closeRead.bind(r);r.closeRead=async y=>{s||await g().catch(E=>{e.log.error("could not negotiate protocol before close read",E)}),await x(y)}}if(r.closeWrite!=null){let x=r.closeWrite.bind(r);r.closeWrite=async y=>{s||await g().catch(E=>{e.log.error("could not negotiate protocol before close write",E)}),await x(y)}}if(r.close!=null){let x=r.close.bind(r);r.close=async y=>{let E=[];l&&E.push(u.promise),d&&E.push(m.promise),E.length>0?await bt(Promise.all(E),y?.signal):(s=!0,i=!1,a.resolve()),await x(y)}}return{stream:r,protocol:t}}var Di=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},un=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ki=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},go=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ri(r){return r[Symbol.asyncIterator]!=null}function Wh(r,t){if(r.byteLength>t)throw new un("Message length too long")}var Ni=r=>{let t=ht(r),e=St(t);return _t(r,e),Ni.bytes=t,e};Ni.bytes=0;function Oi(r,t){t=t??{};let e=t.lengthEncoder??Ni,n=t?.maxDataLength??4194304;function*o(s){Wh(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ri(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}Oi.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ni,n=t?.maxDataLength??4194304;return Wh(r,n),new H(e(r.byteLength),r)};var Ar;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ar||(Ar={}));var Jl=r=>{let t=ee(r);return Jl.bytes=ht(t),t};Jl.bytes=0;function Ql(r,t){let e=new H,n=Ar.LENGTH,o=-1,s=t?.lengthDecoder??Jl,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ar.LENGTH)try{if(o=s(e),o<0)throw new Di("Invalid message length");if(o>a)throw new un("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=Ar.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new ki("Message length length too long");break}throw l}if(n===Ar.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=Ar.LENGTH}}}return Ri(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new go("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new go("Unexpected end of input")}()}Ql.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Ql(n,{...t??{},onLength:s=>{e=s}})};async function yo(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=po(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await He(n,e);if(e.log.trace('handle: read "%s"',o),o===vt){e.log.trace('handle: respond with "%s" for "%s"',vt,o),await Sr(n,T(`${vt}
|
|
16
|
+
`),e),e.log.trace('handle: responded with "%s" for "%s"',vt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Sr(n,T(`${o}
|
|
17
|
+
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new H(...t.map(i=>Oi.single(T(`${i}
|
|
18
|
+
`))),T(`
|
|
19
|
+
`));e.log.trace('handle: respond with "%s" for %s',t,o),await Sr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log.trace('handle: respond with "na" for "%s"',o),await Sr(n,T(`na
|
|
20
|
+
`),e),e.log('handle: responded with "na" for "%s"',o)}}var tb=500,tu=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[lu]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new vo("the connection is being closed");if(this.status==="closed")throw new Ir("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Tr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(tb);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}};function jh(r){return new tu(r)}function rb(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Wl}function nb(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??jl}function Xh(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Bi=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Qs(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=_e([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(t),!n)throw new Js("Connection denied");await this.shouldBlockConnection("denyInboundConnection",t),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=le(n),await this.shouldBlockConnection("denyOutboundConnection",o,t));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let l=t;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(t.log("protecting the %s connection",e),l=await u.protect(t,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,u)}else{let u=t.remoteAddr.getPeerId();if(u==null)throw new Ce(`${e} connection that skipped encryption must have a peer id`);let f=le(u);c="native",s=f}if(s.equals(this.components.peerId)){let u=new Cr("Can not dial self");throw t.abort(u),u}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let u=await(e==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,u),u}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),h=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await yo(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=rb(x,this.components.registrar);if(Xh(x,"inbound",f)===y){let _=new Io(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=w.source,p.sink=w.sink,p.protocol=x,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:x})}).catch(async g=>{f.log.error("error handling incoming stream id %s - %e",p.id,g),p.timeline.close==null&&await p.close()})}}),u=async(p,g={})=>{if(l==null)throw new xr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await l.newStream();f.log.trace("started new stream %s for protocols %s",h.id,p);try{if(g.signal==null){h.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}h.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:x}=await mo(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=nb(x,this.components.registrar,g),E=Xh(x,"outbound",f);if(E>=y){let _=new Co(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw h.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),h.source=w.source,h.sink=w.sink,h.protocol=x,w.closeWrite!=null&&(h.closeWrite=w.closeWrite),w.closeRead!=null&&(h.closeRead=w.closeRead),w.close!=null&&(h.close=w.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(w){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",t.maConn.remoteAddr,p,w),h.timeline.close==null&&h.abort(w),w}},Promise.all([l.sink(s.source),s.sink(l.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let m=()=>{throw new xr("Connection is not multiplexed")};return f=jh({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:u??m,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Tr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await yo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new vr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new vr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await mo(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new vr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new vr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await mo(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new xr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await yo(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new xr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Fi="2.8.2-da4e9da82",Ui="js-libp2p";function Zh(r,t){return`${r??Ui}/${t??Fi} browser/${globalThis.navigator.userAgent}`}var Ki=class extends de{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new de,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??ws(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ui,s=t.nodeInfo?.version??Fi,i=this.components=wh({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Zh(o,s)},logger:this.logger,events:e,datastore:t.datastore??new ks,connectionGater:xh(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",th(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),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})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Bi(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(t.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Ii(this.components,t.transportManager)),this.configureComponent("connectionManager",new yi(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new xi(this.components,t.connectionMonitor)),this.configureComponent("registrar",new _i(this.components)),this.configureComponent("addressManager",new Vs(this.components,t.addresses));let a=(t.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Si(this.components,{routers:a}));let c=(t.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new vi(this.components,{routers:c})),this.configureComponent("randomWalk",new Ai(this.components)),(t.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),t.services!=null)for(let l of Object.keys(t.services)){let u=t.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[zi]!=null&&(this.log("registering service %s for content routing",l),c.push(f[zi])),f[$i]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[$i])),f[Vi]!=null&&(this.log("registering service %s for peer discovery",l),f[Vi].addEventListener?.("peer",d=>{this.#t(d)}))}bh(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}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(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}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(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new ur;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new R("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new R("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){qe(t)&&(t=le(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Dt([T("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Hr(o);return await this.peerStore.patch(t,{publicKey:s}),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function ob(r={}){r.privateKey??=await Wf("Ed25519");let t=new Ki({...await Ld(r),peerId:Zf(r.privateKey)});return r.start!==!1&&await t.start(),t}return fp(sb);})();
|
|
21
21
|
/*! Bundled license information:
|
|
22
22
|
|
|
23
23
|
@noble/hashes/esm/utils.js:
|