libp2p 2.8.1 → 2.8.2-71267286
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -1
- package/dist/index.min.js +11 -11
- package/dist/src/connection-monitor.d.ts.map +1 -1
- package/dist/src/connection-monitor.js +2 -1
- package/dist/src/connection-monitor.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.d.ts.map +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +11 -11
- package/src/connection-monitor.ts +2 -1
- package/src/version.ts +1 -1
- package/dist/typedoc-urls.json +0 -21
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 Fh=Object.create;var ho=Object.defineProperty;var Uh=Object.getOwnPropertyDescriptor;var Kh=Object.getOwnPropertyNames;var qh=Object.getPrototypeOf,zh=Object.prototype.hasOwnProperty;var Se=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Pt=(r,t)=>{for(var e in t)ho(r,e,{get:t[e],enumerable:!0})},Yl=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kh(t))!zh.call(r,o)&&o!==e&&ho(r,o,{get:()=>t[o],enumerable:!(n=Uh(t,o))||n.enumerable});return r};var ln=(r,t,e)=>(e=r!=null?Fh(qh(r)):{},Yl(t||!r||!r.__esModule?ho(e,"default",{value:r,enumerable:!0}):e,r)),Vh=r=>Yl(ho({},"__esModule",{value:!0}),r);var Of=Se((vv,hc)=>{"use strict";var Bg=Object.prototype.hasOwnProperty,Mt="~";function Un(){}Object.create&&(Un.prototype=Object.create(null),new Un().__proto__||(Mt=!1));function Og(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Bf(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new Og(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 It(){this._events=new Un,this._eventsCount=0}It.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Bg.call(e,n)&&t.push(Mt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};It.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};It.prototype.listenerCount=function(t){var e=Mt?Mt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};It.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],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){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,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}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),u){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(!l)for(m=1,l=new Array(u-1);m<u;m++)l[m-1]=arguments[m];c[f].fn.apply(c[f].context,l)}}return!0};It.prototype.on=function(t,e,n){return Bf(this,t,e,n,!1)};It.prototype.once=function(t,e,n){return Bf(this,t,e,n,!0)};It.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=[],u=i.length;a<u;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};It.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};It.prototype.off=It.prototype.removeListener;It.prototype.addListener=It.prototype.on;It.prefixed=Mt;It.EventEmitter=It;typeof hc<"u"&&(hc.exports=It)});var zf=Se(($v,qf)=>{qf.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 id=Se((yS,sd)=>{"use strict";sd.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var dd=Se((ud,fd)=>{"use strict";var as=id(),{hasOwnProperty:cd}=Object.prototype,{propertyIsEnumerable:c0}=Object,Zr=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),l0=ud,ad={concatArrays:!1,ignoreUndefined:!1},cs=r=>{let t=[];for(let e in r)cd.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)c0.call(r,n)&&t.push(n)}return t};function jr(r){return Array.isArray(r)?u0(r):as(r)?f0(r):r}function u0(r){let t=r.slice(0,0);return cs(r).forEach(e=>{Zr(t,e,jr(r[e]))}),t}function f0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return cs(r).forEach(e=>{Zr(t,e,jr(r[e]))}),t}var ld=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Zr(r,o,Oc(r[o],t[o],n)):Zr(r,o,jr(t[o])))}),r),d0=(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++)cd.call(s,a)&&(i.push(String(a)),s===r?Zr(n,o++,s[a]):Zr(n,o++,jr(s[a])));n=ld(n,s,cs(s).filter(a=>!i.includes(a)),e)}),n};function Oc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?d0(r,t,e):!as(t)||!as(r)?jr(t):ld(r,t,cs(t),e)}fd.exports=function(...r){let t=Oc(jr(ad),this!==l0&&this||{},ad),e={_:{}};for(let n of r)if(n!==void 0){if(!as(n))throw new TypeError("`"+n+"` is not an Option Object");e=Oc(e,{_:n},t)}return e._}});var qd=Se(Yn=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[u,l,f,d].join(".")},i=function(c){var u,l,f,d,m,p;for(u=[],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],l=p[1],c=c.substring(l),u.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[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 u,l,f,d,m;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),m=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(e(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(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(u,l){var f,d,m,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=i(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=m=32;m>=0;d=--m)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,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(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);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(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=i(this.first),f=i(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Yn.ip2long=i,Yn.long2ip=a,Yn.Netmask=r}).call(Yn)});var hh=Se((NI,dh)=>{function Ht(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=Ht;Ht.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ht.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ht.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};Ht.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)};Ht.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ht.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ht.prototype.start=Ht.prototype.try;Ht.prototype.errors=function(){return this._errors};Ht.prototype.attempts=function(){return this._attempts};Ht.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=Se(wr=>{var jy=hh();wr.operation=function(r){var t=wr.timeouts(r);return new jy(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};wr.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};wr.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};wr.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 u=wr.operation(t),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){c.apply(r,l)})}.bind(r,i),r[s].options=t}}});var gh=Se((OI,mh)=>{mh.exports=ph()});var _b={};Pt(_b,{createLibp2p:()=>Ab});var Ql=Symbol.for("@libp2p/connection");var Fi=Symbol.for("@libp2p/content-routing");var Ui=Symbol.for("@libp2p/peer-discovery");var po=Symbol.for("@libp2p/peer-id");function mo(r){return!!r?.[po]}var Ki=Symbol.for("@libp2p/peer-routing");var qi="keep-alive";var Rb=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 Gt=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"}},Ae=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"}},bo=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"}},wo=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"}},ce=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"}},_e=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var le=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 Jl(...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 tu(...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"),zi=Symbol.for("@libp2p/service-dependencies");var Wi={};Pt(Wi,{base58btc:()=>G,base58flickr:()=>Zh});var iw=new Uint8Array(0);function eu(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 ue(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 ru(r){return new TextEncoder().encode(r)}function nu(r){return new TextDecoder().decode(r)}function $h(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),u=Math.log(a)/Math.log(256),l=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,b=0,x=p.length;b!==x&&p[b]===0;)b++,g++;for(var y=(x-b)*l+1>>>0,E=new Uint8Array(y);b!==x;){for(var _=p[b],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,b++}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,b=0;p[g]===c;)h++,g++;for(var x=(p.length-g)*u+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||_<b)&&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");b=_,g++}if(p[g]!==" "){for(var I=x-b;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 Hh=$h,Gh=Hh,su=Gh;var Vi=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")}},$i=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 iu(this,t)}},Hi=class{decoders;constructor(t){this.decoders=t}or(t){return iu(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 iu(r,t){return new Hi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Gi=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 Vi(t,e,n),this.decoder=new $i(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 Gi(r,t,e,n)}function Ie({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=su(e,r);return Cr({prefix:t,name:r,encode:n,decode:s=>ue(o(s))})}function Wh(r,t,e,n){let o={};for(let l=0;l<t.length;++l)o[t[l]]=l;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let f=o[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function Xh(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 at({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Cr({prefix:t,name:r,encode(o){return Xh(o,n,e)},decode(o){return Wh(o,n,e,r)}})}var G=Ie({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Zh=Ie({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Xi={};Pt(Xi,{base32:()=>Ut,base32hex:()=>Jh,base32hexpad:()=>ep,base32hexpadupper:()=>rp,base32hexupper:()=>tp,base32pad:()=>Yh,base32padupper:()=>Qh,base32upper:()=>jh,base32z:()=>np});var Ut=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jh=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yh=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Qh=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Jh=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tp=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ep=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rp=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),np=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zi={};Pt(Zi,{base36:()=>hn,base36upper:()=>op});var hn=Ie({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),op=Ie({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sp=lu,au=128,ip=127,ap=~ip,cp=Math.pow(2,31);function lu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=cp;)t[e++]=r&255|au,r/=128;for(;r≈)t[e++]=r&255|au,r>>>=7;return t[e]=r|0,lu.bytes=e-n+1,t}var lp=ji,up=128,cu=127;function ji(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ji.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&cu)<<o:(i&cu)*Math.pow(2,o),o+=7}while(i>=up);return ji.bytes=s-n,e}var fp=Math.pow(2,7),dp=Math.pow(2,14),hp=Math.pow(2,21),pp=Math.pow(2,28),mp=Math.pow(2,35),gp=Math.pow(2,42),yp=Math.pow(2,49),bp=Math.pow(2,56),wp=Math.pow(2,63),xp=function(r){return r<fp?1:r<dp?2:r<hp?3:r<pp?4:r<mp?5:r<gp?6:r<yp?7:r<bp?8:r<wp?9:10},vp={encode:sp,decode:lp,encodingLength:xp},Ep=vp,pn=Ep;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 Wt(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 Kt(r){let t=ue(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 uu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&eu(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 fu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ap(e,Yi(r),t??G.encoder);default:return _p(e,Yi(r),t??Ut.encoder)}}var du=new WeakMap;function Yi(r){let t=du.get(r);if(t==null){let e=new Map;return du.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!==Ip)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=Wt(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&&uu(t.multihash,n.multihash)}toString(t){return fu(this,t)}toJSON(){return{"/":fu(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??hu(n,o,s.bytes))}else if(e[Cp]===!0){let{version:n,multihash:o,code:s}=e,i=Kt(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=hu(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=ue(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(),u=e+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,o]=Sp(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 Yi(s).set(n,t),s}};function Sp(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 Ut.prefix:{let e=t??Ut;return[Ut.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 Ap(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 _p(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,Ip=18;function hu(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 Cp=Symbol.for("@ipld/js-cid/CID");var Qi={};Pt(Qi,{identity:()=>fe});var pu=0,Tp="identity",mu=ue;function Pp(r){return Wt(pu,mu(r))}var fe={code:pu,name:Tp,encode:mu,digest:Pp};function et(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 gu(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Lp(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Dr(r,...t){if(!Lp(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 yu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");gu(r.outputLen),gu(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 bu(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 Xt(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 Ji(...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 Mr(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 Dp(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,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function xu(r,t,e){return r&t^~r&e}function vu(r,t,e){return r&t^r&e^t&e}var Nr=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),bu(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;Dp(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 u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[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),ta=BigInt(32);function Eu(r,t=!1){return t?{h:Number(r&Co),l:Number(r>>ta&Co)}:{h:Number(r>>ta&Co)|0,l:Number(r&Co)|0}}function kp(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}=Eu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Rp=(r,t)=>BigInt(r>>>0)<<ta|BigInt(t>>>0),Mp=(r,t,e)=>r>>>e,Np=(r,t,e)=>r<<32-e|t>>>e,Bp=(r,t,e)=>r>>>e|t<<32-e,Op=(r,t,e)=>r<<32-e|t>>>e,Fp=(r,t,e)=>r<<64-e|t>>>e-32,Up=(r,t,e)=>r>>>e-32|t<<64-e,Kp=(r,t)=>t,qp=(r,t)=>r,zp=(r,t,e)=>r<<e|t>>>32-e,Vp=(r,t,e)=>t<<e|r>>>32-e,$p=(r,t,e)=>t<<e-32|r>>>64-e,Hp=(r,t,e)=>r<<e-32|t>>>64-e;function Gp(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Wp=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Xp=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Zp=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),jp=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Yp=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Qp=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Jp={fromBig:Eu,split:kp,toBig:Rp,shrSH:Mp,shrSL:Np,rotrSH:Bp,rotrSL:Op,rotrBH:Fp,rotrBL:Up,rotr32H:Kp,rotr32L:qp,rotlSH:zp,rotlSL:Vp,rotlBH:$p,rotlBL:Hp,add:Gp,add3L:Wp,add3H:Xp,add4L:Zp,add4H:jp,add5H:Qp,add5L:Yp},F=Jp;var[tm,em]=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))),Ce=new Uint32Array(80),Te=new Uint32Array(80),ea=class extends Nr{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:u,El:l,Fh:f,Fl:d,Gh:m,Gl:p,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,u,l,f,d,m,p,g,h]}set(t,e,n,o,s,i,a,c,u,l,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=u|0,this.El=l|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)Ce[y]=t.getUint32(e),Te[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let E=Ce[y-15]|0,_=Te[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=Ce[y-2]|0,T=Te[y-2]|0,rt=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,Te[y-7],Te[y-16]),ht=F.add4H(K,L,rt,Ce[y-7],Ce[y-16]);Ce[y]=ht|0,Te[y]=K|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:m,Fl:p,Gh:g,Gl:h,Hh:b,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,em[y],Te[y]),T=F.add5H(P,b,E,L,tm[y],Ce[y]),rt=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;b=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=F.add(u|0,l|0,T|0,rt|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=F.add3L(rt,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:u,l}=F.add(this.Dh|0,this.Dl|0,u|0,l|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:b,l:x}=F.add(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,s,i,a,c,u,l,f,d,m,p,g,h,b,x)}roundClean(){Ce.fill(0),Te.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 Su=Io(()=>new ea);var Lo={};Pt(Lo,{aInRange:()=>Bt,abool:()=>Zt,abytes:()=>Br,bitGet:()=>am,bitLen:()=>sa,bitMask:()=>wn,bitSet:()=>cm,bytesToHex:()=>he,bytesToNumberBE:()=>pe,bytesToNumberLE:()=>Le,concatBytes:()=>me,createHmacDrbg:()=>ia,ensureBytes:()=>st,equalBytes:()=>sm,hexToBytes:()=>Xe,hexToNumber:()=>oa,inRange:()=>bn,isBytes:()=>Pe,memoized:()=>je,notImplemented:()=>um,numberToBytesBE:()=>De,numberToBytesLE:()=>Ze,numberToHexUnpadded:()=>We,numberToVarBytesBE:()=>om,utf8ToBytes:()=>im,validateObject:()=>ne});var To=BigInt(0),Po=BigInt(1),rm=BigInt(2);function Pe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Br(r){if(!Pe(r))throw new Error("Uint8Array expected")}function Zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var nm=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function he(r){Br(r);let t="";for(let e=0;e<r.length;e++)t+=nm[r[e]];return t}function We(r){let t=r.toString(16);return t.length&1?"0"+t:t}function oa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?To:BigInt("0x"+r)}var de={_0:48,_9:57,A:65,F:70,a:97,f:102};function Au(r){if(r>=de._0&&r<=de._9)return r-de._0;if(r>=de.A&&r<=de.F)return r-(de.A-10);if(r>=de.a&&r<=de.f)return r-(de.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=Au(r.charCodeAt(s)),a=Au(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 pe(r){return oa(he(r))}function Le(r){return Br(r),oa(he(Uint8Array.from(r).reverse()))}function De(r,t){return Xe(r.toString(16).padStart(t*2,"0"))}function Ze(r,t){return De(r,t).reverse()}function om(r){return Xe(We(r))}function st(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(Pe(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 me(...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 sm(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 im(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var ra=r=>typeof r=="bigint"&&To<=r;function bn(r,t,e){return ra(r)&&ra(t)&&ra(e)&&t<=r&&r<e}function Bt(r,t,e,n){if(!bn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function sa(r){let t;for(t=0;r>To;r>>=Po,t+=1);return t}function am(r,t){return r>>BigInt(t)&Po}function cm(r,t,e){return r|(e?Po:To)<<BigInt(t)}var wn=r=>(rm<<BigInt(r-1))-Po,na=r=>new Uint8Array(r),_u=r=>Uint8Array.from(r);function ia(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=na(r),o=na(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=na())=>{o=a(_u([0]),f),n=a(),f.length!==0&&(o=a(_u([1]),f),n=a())},u=()=>{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 me(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(u()));)c();return i(),m}}var lm={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"||Pe(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 ne(r,t,e={}){let n=(o,s,i)=>{let a=lm[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 um=()=>{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),nt=BigInt(1),Ye=BigInt(2),fm=BigInt(3),aa=BigInt(4),Iu=BigInt(5),Cu=BigInt(8),dm=BigInt(9),hm=BigInt(16);function Y(r,t){let e=r%t;return e>=pt?e:t+e}function pm(r,t,e){if(t<pt)throw new Error("invalid exponent, negatives unsupported");if(e<=pt)throw new Error("invalid modulus");if(e===nt)return pt;let n=nt;for(;t>pt;)t&nt&&(n=n*r%e),r=r*r%e,t>>=nt;return n}function ot(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=Y(r,t),n=t,o=pt,s=nt,i=nt,a=pt;for(;e!==pt;){let u=n/e,l=n%e,f=o-i*u,d=s-a*u;n=e,e=l,o=i,s=a,i=f,a=d}if(n!==nt)throw new Error("invert: does not exist");return Y(o,t)}function mm(r){let t=(r-nt)/Ye,e,n,o;for(e=r-nt,n=0;e%Ye===pt;e/=Ye,n++);for(o=Ye;o<r&&pm(o,t,r)!==r-nt;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+nt)/aa;return function(c,u){let l=c.pow(u,i);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let s=(e+nt)/Ye;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=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<u&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let p=a.pow(l,nt<<BigInt(u-m-1));l=a.sqr(p),f=a.mul(f,p),d=a.mul(d,l),u=m}return f}}function gm(r){if(r%aa===fm){let t=(r+nt)/aa;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%Cu===Iu){let t=(r-Iu)/Cu;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),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%hm,mm(r)}var Tu=(r,t)=>(Y(r,t)&nt)===nt,ym=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ca(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=ym.reduce((n,o)=>(n[o]="function",n),t);return ne(r,e)}function bm(r,t,e){if(e<pt)throw new Error("invalid exponent, negatives unsupported");if(e===pt)return r.ONE;if(e===nt)return t;let n=r.ONE,o=t;for(;e>pt;)e&nt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=nt;return n}function wm(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 la(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function ke(r,t,e=!1,n={}){if(r<=pt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=la(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:wn(o),ZERO:pt,ONE:nt,create:c=>Y(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&nt)===nt,neg:c=>Y(-c,r),eql:(c,u)=>c===u,sqr:c=>Y(c*c,r),add:(c,u)=>Y(c+u,r),sub:(c,u)=>Y(c-u,r),mul:(c,u)=>Y(c*u,r),pow:(c,u)=>bm(a,c,u),div:(c,u)=>Y(c*Do(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Do(c,r),sqrt:n.sqrt||(c=>(i||(i=gm(r)),i(a,c))),invertBatch:c=>wm(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>e?Ze(c,s):De(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Le(c):pe(c)}});return Object.freeze(a)}function Pu(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 ua(r){let t=Pu(r);return t+Math.ceil(t/2)}function Lu(r,t,e=!1){let n=r.length,o=Pu(t),s=ua(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Le(r):pe(r),a=Y(i,t-nt)+nt;return e?Ze(a,o):De(a,o)}var Du=BigInt(0),ko=BigInt(1);function fa(r,t){let e=t.negate();return r?e:t}function ku(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function da(r,t){ku(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function xm(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 vm(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 ha=new WeakMap,Ru=new WeakMap;function pa(r){return Ru.get(r)||1}function Ro(r,t){return{constTimeNegate:fa,hasPrecomputes(e){return pa(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Du;)n&ko&&(o=o.add(s)),s=s.double(),n>>=ko;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=da(n,t),i=[],a=e,c=a;for(let u=0;u<o;u++){c=a,i.push(c);for(let l=1;l<s;l++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=da(e,t),a=r.ZERO,c=r.BASE,u=BigInt(2**e-1),l=2**e,f=BigInt(e);for(let d=0;d<s;d++){let m=d*i,p=Number(o&u);o>>=f,p>i&&(p-=l,o+=ko);let g=m,h=m+Math.abs(p)-1,b=d%2!==0,x=p<0;p===0?c=c.add(fa(b,n[g])):a=a.add(fa(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=da(e,t),c=BigInt(2**e-1),u=2**e,l=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===Du)break;let m=Number(o&c);if(o>>=l,m>a&&(m-=u,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=ha.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&ha.set(n,o(s))),s},wNAFCached(e,n,o){let s=pa(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=pa(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){ku(n,t),Ru.set(e,n),ha.delete(e)}}}function Mo(r,t,e,n){if(xm(e,r),vm(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=sa(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),u=Math.floor((t.BITS-1)/i)*i,l=o;for(let f=u;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(l=l.add(d),f!==0)for(let m=0;m<i;m++)l=l.double()}return l}function xn(r){return ca(r.Fp),ne(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...la(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var jt=BigInt(0),Ot=BigInt(1),No=BigInt(2),Em=BigInt(8),Sm={zip215:!0};function Am(r){let t=xn(r);return ne(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Mu(r){let t=Am(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=No<<BigInt(a*8)-Ot,l=e.create,f=ke(t.n,t.nBitLength),d=t.uvRatio||((v,w)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(w))}}catch{return{isValid:!1,value:jt}}}),m=t.adjustScalarBytes||(v=>v),p=t.domain||((v,w,S)=>{if(Zt("phflag",S),w.length||S)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,w){Bt("coordinate "+v,w,jt,u)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let b=je((v,w)=>{let{ex:S,ey:C,ez:M}=v,N=v.is0();w==null&&(w=N?Em:e.inv(M));let U=l(S*w),q=l(C*w),O=l(M*w);if(N)return{x:jt,y:Ot};if(O!==Ot)throw new Error("invZ was invalid");return{x:U,y:q}}),x=je(v=>{let{a:w,d:S}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:C,ey:M,ez:N,et:U}=v,q=l(C*C),O=l(M*M),j=l(N*N),tt=l(j*j),gt=l(q*w),yt=l(j*l(gt+O)),wt=l(tt+l(S*l(q*O)));if(yt!==wt)throw new Error("bad point: equation left != right (1)");let vt=l(C*M),Nt=l(N*U);if(vt!==Nt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(w,S,C,M){this.ex=w,this.ey=S,this.ez=C,this.et=M,g("x",w),g("y",S),g("z",C),g("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof y)throw new Error("extended point not allowed");let{x:S,y:C}=w||{};return g("x",S),g("y",C),new y(S,C,Ot,l(S*C))}static normalizeZ(w){let S=e.invertBatch(w.map(C=>C.ez));return w.map((C,M)=>C.toAffine(S[M])).map(y.fromAffine)}static msm(w,S){return Mo(y,f,w,S)}_setWindowSize(w){L.setWindowSize(this,w)}assertValidity(){x(this)}equals(w){h(w);let{ex:S,ey:C,ez:M}=this,{ex:N,ey:U,ez:q}=w,O=l(S*q),j=l(N*M),tt=l(C*q),gt=l(U*M);return O===j&&tt===gt}is0(){return this.equals(y.ZERO)}negate(){return new y(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:w}=t,{ex:S,ey:C,ez:M}=this,N=l(S*S),U=l(C*C),q=l(No*l(M*M)),O=l(w*N),j=S+C,tt=l(l(j*j)-N-U),gt=O+U,yt=gt-q,wt=O-U,vt=l(tt*yt),Nt=l(gt*wt),Tt=l(tt*wt),ee=l(yt*gt);return new y(vt,Nt,ee,Tt)}add(w){h(w);let{a:S,d:C}=t,{ex:M,ey:N,ez:U,et:q}=this,{ex:O,ey:j,ez:tt,et:gt}=w;if(S===BigInt(-1)){let $l=l((N-M)*(j+O)),Hl=l((N+M)*(j-O)),Oi=l(Hl-$l);if(Oi===jt)return this.double();let Gl=l(U*No*gt),Wl=l(q*No*tt),Xl=Wl+Gl,Zl=Hl+$l,jl=Wl-Gl,Mh=l(Xl*Oi),Nh=l(Zl*jl),Bh=l(Xl*jl),Oh=l(Oi*Zl);return new y(Mh,Nh,Oh,Bh)}let yt=l(M*O),wt=l(N*j),vt=l(q*C*gt),Nt=l(U*tt),Tt=l((M+N)*(O+j)-yt-wt),ee=Nt-vt,ae=Nt+vt,cn=l(wt-S*yt),Lh=l(Tt*ee),Dh=l(ae*cn),kh=l(Tt*cn),Rh=l(ee*ae);return new y(Lh,Dh,Rh,kh)}subtract(w){return this.add(w.negate())}wNAF(w){return L.wNAFCached(this,w,y.normalizeZ)}multiply(w){let S=w;Bt("scalar",S,Ot,n);let{p:C,f:M}=this.wNAF(S);return y.normalizeZ([C,M])[0]}multiplyUnsafe(w,S=y.ZERO){let C=w;return Bt("scalar",C,jt,n),C===jt?_:this.is0()||C===Ot?this:L.wNAFCachedUnsafe(this,C,y.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(w){return b(this,w)}clearCofactor(){let{h:w}=t;return w===Ot?this:this.multiplyUnsafe(w)}static fromHex(w,S=!1){let{d:C,a:M}=t,N=e.BYTES;w=st("pointHex",w,N),Zt("zip215",S);let U=w.slice(),q=w[N-1];U[N-1]=q&-129;let O=Le(U),j=S?u:e.ORDER;Bt("pointHex.y",O,jt,j);let tt=l(O*O),gt=l(tt-Ot),yt=l(C*tt-M),{isValid:wt,value:vt}=d(gt,yt);if(!wt)throw new Error("Point.fromHex: invalid y coordinate");let Nt=(vt&Ot)===Ot,Tt=(q&128)!==0;if(!S&&vt===jt&&Tt)throw new Error("Point.fromHex: x=0 and x_0=1");return Tt!==Nt&&(vt=l(-vt)),y.fromAffine({x:vt,y:O})}static fromPrivateKey(w){return T(w).point}toRawBytes(){let{x:w,y:S}=this.toAffine(),C=Ze(S,e.BYTES);return C[C.length-1]|=w&Ot?128:0,C}toHex(){return he(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,Ot,l(t.Gx*t.Gy)),y.ZERO=new y(jt,Ot,Ot,jt);let{BASE:E,ZERO:_}=y,L=Ro(y,a*8);function I(v){return Y(v,n)}function P(v){return I(Le(v))}function T(v){let w=e.BYTES;v=st("private key",v,w);let S=st("hashed private key",s(v),2*w),C=m(S.slice(0,w)),M=S.slice(w,2*w),N=P(C),U=E.multiply(N),q=U.toRawBytes();return{head:C,prefix:M,scalar:N,point:U,pointBytes:q}}function rt(v){return T(v).pointBytes}function H(v=new Uint8Array,...w){let S=me(...w);return P(s(p(S,st("context",v),!!o)))}function K(v,w,S={}){v=st("message",v),o&&(v=o(v));let{prefix:C,scalar:M,pointBytes:N}=T(w),U=H(S.context,C,v),q=E.multiply(U).toRawBytes(),O=H(S.context,q,N,v),j=I(U+O*M);Bt("signature.s",j,jt,n);let tt=me(q,Ze(j,e.BYTES));return st("result",tt,e.BYTES*2)}let ht=Sm;function A(v,w,S,C=ht){let{context:M,zip215:N}=C,U=e.BYTES;v=st("signature",v,2*U),w=st("message",w),S=st("publicKey",S,U),N!==void 0&&Zt("zip215",N),o&&(w=o(w));let q=Le(v.slice(U,2*U)),O,j,tt;try{O=y.fromHex(S,N),j=y.fromHex(v.slice(0,U),N),tt=E.multiplyUnsafe(q)}catch{return!1}if(!N&&O.isSmallOrder())return!1;let gt=H(M,j.toRawBytes(),O.toRawBytes(),w);return j.add(O.multiplyUnsafe(gt)).subtract(tt).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:rt,sign:K,verify:A,ExtendedPoint:y,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,w=y.BASE){return w._setWindowSize(v),w.multiply(BigInt(3)),w}}}}var ma=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Nu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Qw=BigInt(0),_m=BigInt(1),Bu=BigInt(2),Jw=BigInt(3),Im=BigInt(5),Cm=BigInt(8);function Tm(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ma,a=r*r%s*r%s,c=ot(a,Bu,s)*a%s,u=ot(c,_m,s)*r%s,l=ot(u,Im,s)*u%s,f=ot(l,t,s)*l%s,d=ot(f,e,s)*f%s,m=ot(d,n,s)*d%s,p=ot(m,o,s)*m%s,g=ot(p,o,s)*m%s,h=ot(g,t,s)*l%s;return{pow_p_5_8:ot(h,Bu,s)*r%s,b2:a}}function Pm(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Lm(r,t){let e=ma,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Tm(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,u=Y(i*Nu,e),l=a===r,f=a===Y(-r,e),d=a===Y(-r*Nu,e);return l&&(i=c),(f||d)&&(i=u),Tu(i,e)&&(i=Y(-i,e)),{isValid:l||f,value:i}}var Dm=ke(ma,void 0,!0),km={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Dm,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Cm,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Su,randomBytes:Mr,adjustScalarBytes:Pm,uvRatio:Lm},vn=Mu(km);var Bo=32,Oo=64,ga=32;function Ou(){let r=vn.utils.randomPrivateKey(),t=vn.getPublicKey(r);return{privateKey:Rm(r,t),publicKey:t}}function Fu(r,t){let e=r.subarray(0,ga);return vn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Uu(r,t,e){return vn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Rm(r,t){let e=new Uint8Array(Oo);for(let n=0;n<ga;n++)e[n]=r[n],e[ga+n]=t[n];return e}var En=class{type="Ed25519";raw;constructor(t){this.raw=Uo(t,Bo)}toMultihash(){return fe.digest(oe(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:et(this.raw,t.raw)}verify(t,e){return Uu(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:et(this.raw,t.raw)}sign(t){return Fu(this.raw,t)}};function ya(r){return r=Uo(r,Bo),new En(r)}async function qu(){let{privateKey:r,publicKey:t}=Ou();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 ct(r=0){return new Uint8Array(r)}function Et(r=0){return new Uint8Array(r)}var Mm=Math.pow(2,7),Nm=Math.pow(2,14),Bm=Math.pow(2,21),ba=Math.pow(2,28),wa=Math.pow(2,35),xa=Math.pow(2,42),va=Math.pow(2,49),Z=128,St=127;function dt(r){if(r<Mm)return 1;if(r<Nm)return 2;if(r<Bm)return 3;if(r<ba)return 4;if(r<wa)return 5;if(r<xa)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 Ea(r,t,e=0){switch(dt(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 Om(r,t,e=0){switch(dt(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 Sa(r,t){let e=r[t],n=0;if(n+=e&St,e<Z||(e=r[t+1],n+=(e&St)<<7,e<Z)||(e=r[t+2],n+=(e&St)<<14,e<Z)||(e=r[t+3],n+=(e&St)<<21,e<Z)||(e=r[t+4],n+=(e&St)*ba,e<Z)||(e=r[t+5],n+=(e&St)*wa,e<Z)||(e=r[t+6],n+=(e&St)*xa,e<Z)||(e=r[t+7],n+=(e&St)*va,e<Z))return n;throw new RangeError("Could not decode varint")}function Fm(r,t){let e=r.get(t),n=0;if(n+=e&St,e<Z||(e=r.get(t+1),n+=(e&St)<<7,e<Z)||(e=r.get(t+2),n+=(e&St)<<14,e<Z)||(e=r.get(t+3),n+=(e&St)<<21,e<Z)||(e=r.get(t+4),n+=(e&St)*ba,e<Z)||(e=r.get(t+5),n+=(e&St)*wa,e<Z)||(e=r.get(t+6),n+=(e&St)*xa,e<Z)||(e=r.get(t+7),n+=(e&St)*va,e<Z))return n;throw new RangeError("Could not decode varint")}function At(r,t,e=0){return t==null&&(t=Et(dt(r))),t instanceof Uint8Array?Ea(r,t,e):Om(r,t,e)}function Yt(r,t=0){return r instanceof Uint8Array?Sa(r,t):Fm(r,t)}var Aa=new Float32Array([-0]),Re=new Uint8Array(Aa.buffer);function zu(r,t,e){Aa[0]=r,t[e]=Re[0],t[e+1]=Re[1],t[e+2]=Re[2],t[e+3]=Re[3]}function Vu(r,t){return Re[0]=r[t],Re[1]=r[t+1],Re[2]=r[t+2],Re[3]=r[t+3],Aa[0]}var _a=new Float64Array([-0]),_t=new Uint8Array(_a.buffer);function $u(r,t,e){_a[0]=r,t[e]=_t[0],t[e+1]=_t[1],t[e+2]=_t[2],t[e+3]=_t[3],t[e+4]=_t[4],t[e+5]=_t[5],t[e+6]=_t[6],t[e+7]=_t[7]}function Hu(r,t){return _t[0]=r[t],_t[1]=r[t+1],_t[2]=r[t+2],_t[3]=r[t+3],_t[4]=r[t+4],_t[5]=r[t+5],_t[6]=r[t+6],_t[7]=r[t+7],_a[0]}var Um=BigInt(Number.MAX_SAFE_INTEGER),Km=BigInt(Number.MIN_SAFE_INTEGER),qt=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<Um&&t>Km)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>Gu&&(o=0n,++n>Gu&&(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 qt(0,0);Je.toBigInt=function(){return 0n};Je.zzEncode=Je.zzDecode=function(){return this};Je.length=function(){return 1};var Gu=4294967296n;function Wu(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 Xu(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 Ia(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 Qt(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 Ca=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,Qt(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 Qt(this,4);return Ko(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return Ko(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=Vu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=Hu(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 Qt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Xu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Qt(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 qt(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 Qt(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 Qt(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 Qt(this,8);let t=Ko(this.buf,this.pos+=4),e=Ko(this.buf,this.pos+=4);return new qt(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=Sa(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 Ta(r){return new Ca(r instanceof Uint8Array?r:r.subarray())}function Lt(r,t,e){let n=Ta(r);return t.decode(n,void 0,e)}var Pa={};Pt(Pa,{base10:()=>qm});var qm=Ie({prefix:"9",name:"base10",alphabet:"0123456789"});var La={};Pt(La,{base16:()=>zm,base16upper:()=>Vm});var zm=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vm=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Da={};Pt(Da,{base2:()=>$m});var $m=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ka={};Pt(ka,{base256emoji:()=>Zm});var ju=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Hm=ju.reduce((r,t,e)=>(r[e]=t,r),[]),Gm=ju.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Wm(r){return r.reduce((t,e)=>(t+=Hm[e],t),"")}function Xm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Gm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Zm=Cr({prefix:"\u{1F680}",name:"base256emoji",encode:Wm,decode:Xm});var Na={};Pt(Na,{base64:()=>Ra,base64pad:()=>jm,base64url:()=>Ma,base64urlpad:()=>Ym});var Ra=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jm=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ma=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ym=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ba={};Pt(Ba,{base8:()=>Qm});var Qm=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Oa={};Pt(Oa,{identity:()=>Jm});var Jm=Cr({prefix:"\0",name:"identity",encode:r=>nu(r),decode:r=>ru(r)});var kx=new TextEncoder,Rx=new TextDecoder;var Ka={};Pt(Ka,{sha256:()=>Or,sha512:()=>rg});function Ua({name:r,code:t,encode:e}){return new Fa(r,t,e)}var Fa=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?Wt(this.code,e):e.then(n=>Wt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Qu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Or=Ua({name:"sha2-256",code:18,encode:Qu("SHA-256")}),rg=Ua({name:"sha2-512",code:19,encode:Qu("SHA-512")});var Sn={...Oa,...Da,...Ba,...Pa,...La,...Xi,...Zi,...Wi,...Na,...ka},Hx={...Ka,...Qi};function tf(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ju=tf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),qa=tf("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=Et(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ng={utf8:Ju,"utf-8":Ju,hex:Sn.base16,latin1:qa,ascii:qa,binary:qa,...Sn},qo=ng;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 za(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Et(i);o+i>t&&(n=Et(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 Va(){}var Ha=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},og=za();function sg(r){return globalThis.Buffer!=null?Et(r):og(r)}var _n=class{len;head;tail;states;constructor(){this.len=0,this.head=new tr(Va,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 Ga((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,qt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=qt.fromBigInt(t);return this._push(zo,e.length(),e)}uint64Number(t){return this._push(Ea,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=qt.fromBigInt(t).zzEncode();return this._push(zo,e.length(),e)}sint64Number(t){let e=qt.fromNumber(t).zzEncode();return this._push(zo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push($a,1,t?1:0)}fixed32(t){return this._push(An,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=qt.fromBigInt(t);return this._push(An,4,e.lo)._push(An,4,e.hi)}fixed64Number(t){let e=qt.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(zu,4,t)}double(t){return this._push($u,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push($a,1,0):this.uint32(e)._push(ag,e,t)}string(t){let e=Wu(t);return e!==0?this.uint32(e)._push(Ia,e,t):this._push($a,1,0)}fork(){return this.states=new Ha(this),this.head=this.tail=new tr(Va,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(Va,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=sg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function $a(r,t,e){t[e]=r&255}function ig(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ga=class extends tr{next;constructor(t,e){super(ig,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 ag(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(cg,t,r),this},_n.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(lg,t,r),this});function cg(r,t,e){t.set(r,e)}function lg(r,t,e){r.length<40?Ia(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function Wa(){return new _n}function Dt(r,t){let e=Wa();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 Xa(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 kt(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 Za;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(Za||(Za={}));(function(r){r.codec=()=>Xa(Za)})(mt||(mt={}));var se;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(se||(se={}));var ja;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(ja||(ja={}));var Ln={};Pt(Ln,{MAX_RSA_KEY_SIZE:()=>ec,generateRSAKeyPair:()=>sc,jwkToJWKKeyPair:()=>gf,jwkToPkcs1:()=>vg,jwkToPkix:()=>nc,jwkToRSAPrivateKey:()=>mf,pkcs1ToJwk:()=>df,pkcs1ToRSAPrivateKey:()=>pf,pkixToJwk:()=>hf,pkixToRSAPublicKey:()=>oc});var ug=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]),Ne=new Uint32Array(64),Ya=class extends Nr{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)Ne[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Ne[f-15],m=Ne[f-2],p=Xt(d,7)^Xt(d,18)^d>>>3,g=Xt(m,17)^Xt(m,19)^m>>>10;Ne[f]=g+Ne[f-7]+p+Ne[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Xt(a,6)^Xt(a,11)^Xt(a,25),m=l+d+xu(a,c,u)+ug[f]+Ne[f]|0,g=(Xt(n,2)^Xt(n,13)^Xt(n,22))+vu(n,o,s)|0;l=u,u=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,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Ne.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Ur=Io(()=>new Ya);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 Rt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Et(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var nf=Symbol.for("@achingbrain/uint8arraylist");function rf(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?.[nf]}var Q=class r{bufs;length;[nf]=!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=rf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=rf(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 Rt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Rt(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 u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){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,u=n.byteLength-1,l;for(let f=e;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){l=Math.max(1,d-a[m]);break}}if(l===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=Et(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=ct(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=ct(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=ct(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=Et(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=ct(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=ct(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=ct(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=ct(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=ct(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(!et(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 fg=parseInt("11111",2),Ja=parseInt("10000000",2),dg=parseInt("01111111",2),of={2:hg,3:gg,5:mg,6:pg,16:Qa,22:Qa,48:Qa};function Cn(r,t={offset:0}){let e=r[t.offset]&fg;if(t.offset++,of[e]!=null)return of[e](r,t);throw new Error("No decoder for tag "+e)}function Ho(r,t){let e=0;if((r[t.offset]&Ja)===Ja){let n=r[t.offset]&dg,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 Qa(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 hg(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 pg(r,t){let e=Ho(r,t);return t.offset+=e,["oid-unimplemented"]}function mg(r,t){return t.offset++,null}function gg(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 yg(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 tc(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=yg(r.byteLength);return new Q(Uint8Array.from([t.byteLength|Ja]),t)}function Vt(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]),tc(t),t)}function sf(r){let t=Uint8Array.from([0]),e=new Q(t,r);return new Q(Uint8Array.from([3]),tc(e),e)}function Go(r){let t=new Q;for(let e of r)t.append(e);return new Q(Uint8Array.from([48]),tc(t),t)}function Kr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Mr(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 af={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 Be=af;async function cf(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 bg(t);return{privateKey:e[0],publicKey:e[1]}}async function lf(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 uf(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 bg(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 ff(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:et(this.raw,t.raw)}verify(t,e){return uf(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:et(this.raw,t.raw)}sign(t){return lf(this._key,t)}};var ec=8192,rc=18,wg=1062,xg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function df(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 vg(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([Vt(Uint8Array.from([0])),Vt(k(r.n,"base64url")),Vt(k(r.e,"base64url")),Vt(k(r.d,"base64url")),Vt(k(r.p,"base64url")),Vt(k(r.q,"base64url")),Vt(k(r.dp,"base64url")),Vt(k(r.dq,"base64url")),Vt(k(r.qi,"base64url"))]).subarray()}function hf(r){let t=Cn(r,{offset:0});return{kty:"RSA",n:B(t[1][0],"base64url"),e:B(t[1][1],"base64url")}}function nc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Go([xg,sf(Go([Vt(k(r.n,"base64url")),Vt(k(r.e,"base64url"))]))]).subarray()}function pf(r){let t=df(r);return mf(t)}function oc(r,t){if(r.byteLength>=wg)throw new Er("Key size is too large");let e=hf(r);if(t==null){let n=Ur(se.encode({Type:mt.RSA,Data:r}));t=Wt(rc,n)}return new qr(e,t)}function mf(r){if(ff(r)>ec)throw new R("Key size is too large");let t=gf(r),e=Ur(se.encode({Type:mt.RSA,Data:nc(t.publicKey)})),n=Wt(rc,e);return new Dn(t.privateKey,new qr(t.publicKey,n))}async function sc(r){if(r>ec)throw new R("Key size is too large");let t=await cf(r),e=Ur(se.encode({Type:mt.RSA,Data:nc(t.publicKey)})),n=Wt(rc,e);return new Dn(t.privateKey,new qr(t.publicKey,n))}function gf(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,yu(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()}},ic=(r,t,e)=>new Xo(r,t).update(e).digest();ic.create=(r,t)=>new Xo(r,t);function yf(r){r.lowS!==void 0&&Zt("lowS",r.lowS),r.prehash!==void 0&&Zt("prehash",r.prehash)}function Eg(r){let t=xn(r);ne(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:Sg,hexToBytes:Ag}=Lo,ac=class extends Error{constructor(t=""){super(t)}},ge={Err:ac,_tlv:{encode:(r,t)=>{let{Err:e}=ge;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}=ge,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 u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;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}=ge;if(r<ye)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}=ge;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 Sg(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ge,o=typeof r=="string"?Ag(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:u,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=ge,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},ye=BigInt(0),bt=BigInt(1),g2=BigInt(2),bf=BigInt(3),y2=BigInt(4);function _g(r){let t=Eg(r),{Fp:e}=t,n=ke(t.n,t.nBitLength),o=t.toBytes||((g,h,b)=>{let x=h.toAffine();return me(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),b=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:b,y:x}});function i(g){let{a:h,b}=t,x=e.sqr(g),y=e.mul(x,g);return e.add(e.add(y,e.mul(g,h)),b)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return bn(g,bt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:b,wrapPrivateKey:x,n:y}=t;if(h&&typeof g!="bigint"){if(Pe(g)&&(g=he(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let E;try{E=typeof g=="bigint"?g:pe(st("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return x&&(E=Y(E,y)),Bt("private key",E,bt,y),E}function u(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let l=je((g,h)=>{let{px:b,py:x,pz:y}=g;if(e.eql(y,e.ONE))return{x:b,y:x};let E=g.is0();h==null&&(h=E?e.ONE:e.inv(y));let _=e.mul(b,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:b}=g.toAffine();if(!e.isValid(h)||!e.isValid(b))throw new Error("bad point: x or y not FE");let x=e.sqr(b),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,b,x){if(this.px=h,this.py=b,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(b==null||!e.isValid(b))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:b,y:x}=h||{};if(!h||!e.isValid(b)||!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(b)&&y(x)?d.ZERO:new d(b,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let b=e.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(b[y])).map(d.fromAffine)}static fromHex(h){let b=d.fromAffine(s(st("pointHex",h)));return b.assertValidity(),b}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,b){return Mo(d,n,h,b)}_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){u(h);let{px:b,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=e.eql(e.mul(b,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}=t,x=e.mul(b,bf),{px:y,py:E,pz:_}=this,L=e.ZERO,I=e.ZERO,P=e.ZERO,T=e.mul(y,y),rt=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(rt,I),I=e.add(rt,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,rt),P=e.add(P,P),P=e.add(P,P),new d(L,I,P)}add(h){u(h);let{px:b,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=e.ZERO,P=e.ZERO,T=e.ZERO,rt=t.a,H=e.mul(t.b,bf),K=e.mul(b,E),ht=e.mul(x,_),A=e.mul(y,L),D=e.add(b,x),v=e.add(E,_);D=e.mul(D,v),v=e.add(K,ht),D=e.sub(D,v),v=e.add(b,y);let w=e.add(E,L);return v=e.mul(v,w),w=e.add(K,A),v=e.sub(v,w),w=e.add(x,y),I=e.add(_,L),w=e.mul(w,I),I=e.add(ht,A),w=e.sub(w,I),T=e.mul(rt,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(rt,A),v=e.mul(H,v),ht=e.add(ht,A),A=e.sub(K,A),A=e.mul(rt,A),v=e.add(v,A),K=e.mul(ht,v),P=e.add(P,K),K=e.mul(w,v),I=e.mul(D,I),I=e.sub(I,K),K=e.mul(D,ht),T=e.mul(w,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:b,n:x}=t;Bt("scalar",h,ye,x);let y=d.ZERO;if(h===ye)return y;if(this.is0()||h===bt)return this;if(!b||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:L,k2:I}=b.splitScalar(h),P=y,T=y,rt=this;for(;_>ye||I>ye;)_&bt&&(P=P.add(rt)),I&bt&&(T=T.add(rt)),rt=rt.double(),_>>=bt,I>>=bt;return E&&(P=P.negate()),L&&(T=T.negate()),T=new d(e.mul(T.px,b.beta),T.py,T.pz),P.add(T)}multiply(h){let{endo:b,n:x}=t;Bt("scalar",h,bt,x);let y,E;if(b){let{k1neg:_,k1:L,k2neg:I,k2:P}=b.splitScalar(h),{p:T,f:rt}=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,b.beta),H.py,H.pz),y=T.add(H),E=rt.add(K)}else{let{p:_,f:L}=this.wNAF(h);y=_,E=L}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,b,x){let y=d.BASE,E=(L,I)=>I===ye||I===bt||!L.equals(y)?L.multiplyUnsafe(I):L.multiply(I),_=E(this,b).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return l(this,h)}isTorsionFree(){let{h,isTorsionFree:b}=t;if(h===bt)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:b}=t;return h===bt?this:b?b(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Zt("isCompressed",h),he(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 Ig(r){let t=xn(r);return ne(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function wf(r){let t=Ig(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(A){return Y(A,n)}function a(A){return Do(A,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:f}=_g({...t,toBytes(A,D,v){let w=D.toAffine(),S=e.toBytes(w.x),C=me;return Zt("isCompressed",v),v?C(Uint8Array.from([D.hasEvenY()?2:3]),S):C(Uint8Array.from([4]),S,e.toBytes(w.y))},fromBytes(A){let D=A.length,v=A[0],w=A.subarray(1);if(D===o&&(v===2||v===3)){let S=pe(w);if(!bn(S,bt,e.ORDER))throw new Error("Point is not on curve");let C=l(S),M;try{M=e.sqrt(C)}catch(q){let O=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+O)}let N=(M&bt)===bt;return(v&1)===1!==N&&(M=e.neg(M)),{x:S,y:M}}else if(D===s&&v===4){let S=e.fromBytes(w.subarray(0,e.BYTES)),C=e.fromBytes(w.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=>he(De(A,t.nByteLength));function m(A){let D=n>>bt;return A>D}function p(A){return m(A)?i(-A):A}let g=(A,D,v)=>pe(A.slice(D,v));class h{constructor(D,v,w){this.r=D,this.s=v,this.recovery=w,this.assertValidity()}static fromCompact(D){let v=t.nByteLength;return D=st("compactSignature",D,v*2),new h(g(D,0,v),g(D,v,2*v))}static fromDER(D){let{r:v,s:w}=ge.toSig(st("DER",D));return new h(v,w)}assertValidity(){Bt("r",this.r,bt,n),Bt("s",this.s,bt,n)}addRecoveryBit(D){return new h(this.r,this.s,D)}recoverPublicKey(D){let{r:v,s:w,recovery:S}=this,C=L(st("msgHash",D));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let M=S===2||S===3?v+t.n:v;if(M>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let N=(S&1)===0?"02":"03",U=c.fromHex(N+d(M)),q=a(M),O=i(-C*q),j=i(w*q),tt=c.BASE.multiplyAndAddUnsafe(U,O,j);if(!tt)throw new Error("point at infinify");return tt.assertValidity(),tt}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 ge.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(A){try{return u(A),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let A=ua(t.n);return Lu(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=Pe(A),v=typeof A=="string",w=(D||v)&&A.length;return D?w===o||w===s:v?w===2*o||w===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(u(A)).toRawBytes(v)}let _=t.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");let D=pe(A),v=A.length*8-t.nBitLength;return v>0?D>>BigInt(v):D},L=t.bits2int_modN||function(A){return i(_(A))},I=wn(t.nBitLength);function P(A){return Bt("num < 2^"+t.nBitLength,A,ye,I),De(A,t.nByteLength)}function T(A,D,v=rt){if(["recovered","canonical"].some(yt=>yt in v))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:S}=t,{lowS:C,prehash:M,extraEntropy:N}=v;C==null&&(C=!0),A=st("msgHash",A),yf(v),M&&(A=st("prehashed msgHash",w(A)));let U=L(A),q=u(D),O=[P(q),P(U)];if(N!=null&&N!==!1){let yt=N===!0?S(e.BYTES):N;O.push(st("extraEntropy",yt))}let j=me(...O),tt=U;function gt(yt){let wt=_(yt);if(!f(wt))return;let vt=a(wt),Nt=c.BASE.multiply(wt).toAffine(),Tt=i(Nt.x);if(Tt===ye)return;let ee=i(vt*i(tt+Tt*q));if(ee===ye)return;let ae=(Nt.x===Tt?0:2)|Number(Nt.y&bt),cn=ee;return C&&m(ee)&&(cn=p(ee),ae^=1),new h(Tt,cn,ae)}return{seed:j,k2sig:gt}}let rt={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function K(A,D,v=rt){let{seed:w,k2sig:S}=T(A,D,v),C=t;return ia(C.hash.outputLen,C.nByteLength,C.hmac)(w,S)}c.BASE._setWindowSize(8);function ht(A,D,v,w=H){let S=A;D=st("msgHash",D),v=st("publicKey",v);let{lowS:C,prehash:M,format:N}=w;if(yf(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&N!=="compact"&&N!=="der")throw new Error("format must be compact or der");let U=typeof S=="string"||Pe(S),q=!U&&!N&&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,j;try{if(q&&(O=new h(S.r,S.s)),U){try{N!=="compact"&&(O=h.fromDER(S))}catch(ae){if(!(ae instanceof ge.Err))throw ae}!O&&N!=="der"&&(O=h.fromCompact(S))}j=c.fromHex(v)}catch{return!1}if(!O||C&&O.hasHighS())return!1;M&&(D=t.hash(D));let{r:tt,s:gt}=O,yt=L(D),wt=a(gt),vt=i(yt*wt),Nt=i(tt*wt),Tt=c.BASE.multiplyAndAddUnsafe(j,vt,Nt)?.toAffine();return Tt?i(Tt.x)===tt:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:K,verify:ht,ProjectivePoint:c,Signature:h,utils:b}}function Cg(r){return{hash:r,hmac:(t,...e)=>ic(r,t,Ji(...e)),randomBytes:Mr}}function xf(r,t){let e=n=>wf({...r,...Cg(n)});return{...e(t),create:e}}var Sf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Tg=BigInt(1),cc=BigInt(2),Ef=(r,t)=>(r+t/cc)/t;function Pg(r){let t=Sf,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,l=u*u*r%t,f=ot(l,e,t)*l%t,d=ot(f,e,t)*l%t,m=ot(d,cc,t)*u%t,p=ot(m,o,t)*m%t,g=ot(p,s,t)*p%t,h=ot(g,a,t)*g%t,b=ot(h,c,t)*h%t,x=ot(b,a,t)*g%t,y=ot(x,e,t)*l%t,E=ot(y,i,t)*p%t,_=ot(E,n,t)*u%t,L=ot(_,cc,t);if(!lc.eql(lc.sqr(L),r))throw new Error("Cannot find square root");return L}var lc=ke(Sf,void 0,void 0,{sqrt:Pg}),$t=xf({a:BigInt(0),b:BigInt(7),Fp:lc,n:vf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=vf,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Tg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Ef(s*r,t),c=Ef(-n*r,t),u=Y(r-a*e-c*o,t),l=Y(-a*n-c*s,t),f=u>i,d=l>i;if(f&&(u=t-u),d&&(l=t-l),u>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},Ur),I2=BigInt(0);var C2=$t.ProjectivePoint;function uc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Af(r,t){let e=Or.digest(t instanceof Uint8Array?t:t.subarray());if(uc(e))return e.then(({digest:n})=>$t.sign(n,r).toDERRawBytes()).catch(n=>{throw new Tn(String(n))});try{return $t.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Tn(String(n))}}function _f(r,t,e){let n=Or.digest(e instanceof Uint8Array?e:e.subarray());if(uc(n))return n.then(({digest:o})=>$t.verify(t,o,r)).catch(o=>{throw new Pn(String(o))});try{return $t.verify(t,n.digest,r)}catch(o){throw new Pn(String(o))}}var kn=class{type="secp256k1";raw;_key;constructor(t){this._key=Tf(t),this.raw=If(this._key)}toMultihash(){return fe.digest(oe(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:et(this.raw,t.raw)}verify(t,e){return _f(this._key,e,t)}},Zo=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Cf(t),this.publicKey=new kn(e??Pf(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:et(this.raw,t.raw)}sign(t){return Af(this.raw,t)}};function fc(r){return new kn(r)}async function Lf(){let r=Lg();return new Zo(r)}function If(r){return $t.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Cf(r){try{return $t.getPublicKey(r,!0),r}catch(t){throw new un(String(t))}}function Tf(r){try{return $t.ProjectivePoint.fromHex(r),r}catch(t){throw new Er(String(t))}}function Pf(r){try{return $t.getPublicKey(r,!0)}catch(t){throw new un(String(t))}}function Lg(){return $t.utils.randomPrivateKey()}async function Df(r,t){if(r==="Ed25519")return qu();if(r==="secp256k1")return Lf();if(r==="RSA")return sc(t??2048);throw new _e}function zr(r,t){let{Type:e,Data:n}=se.decode(r),o=n??new Uint8Array;switch(e){case mt.RSA:return oc(o,t);case mt.Ed25519:return ya(o);case mt.secp256k1:return fc(o);default:throw new _e}}function kf(r){let{Type:t,Data:e}=se.decode(r.digest),n=e??new Uint8Array;switch(t){case mt.Ed25519:return ya(n);case mt.secp256k1:return fc(n);default:throw new _e}}function oe(r){return se.encode({Type:mt[r.type],Data:r.raw})}var Rf=Symbol.for("nodejs.util.inspect.custom"),Dg=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(Dg,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Rf](){return`PeerId(${this.toString()})`}},Mn=class extends Rn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Nn=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}},kg=2336,On=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=fe.digest(k(this.url))}[Rf](){return`PeerId(${this.url})`}[po]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ut.createV1(kg,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=B(t)),t.toString()===this.toString())}};var Rg=114,Mf=2336;function ie(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Kt(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=Kt(t.decode(r))}return Vr(e)}function dc(r){if(r.type==="Ed25519")return new Nn({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 Mn({multihash:r.toCID().multihash,publicKey:r});throw new _e}function Nf(r){return dc(r.publicKey)}function Vr(r){if(Ng(r))return new Mn({multihash:r});if(Mg(r))try{let t=kf(r);if(t.type==="Ed25519")return new Nn({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 bo("Supplied PeerID Multihash is invalid")}function Fn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Rg&&r.code!==Mf)throw new yo("Supplied PeerID CID is invalid");if(r.code===Mf){let t=B(r.multihash.digest);return new On(new URL(t))}return Vr(r.multihash)}function Mg(r){return r.code===fe.code}function Ng(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 pc=ln(Of(),1);var Kn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},mc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Ff=r=>globalThis.DOMException===void 0?new mc(r):new DOMException(r),Uf=r=>{let t=r.reason===void 0?Ff("This operation was aborted."):r.reason;return t instanceof Error?t:Ff(t)};function qn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((l,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(Uf(m)),a=()=>{f(Uf(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(l,f);return}let d=new Kn;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{l(await r)}catch(m){f(m)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}function gc(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=gc(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 Oe=class extends pc.default{#t;#e;#r=0;#a;#c;#p=0;#o;#l;#n;#m;#s=0;#u;#i;#g;#w=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.#b(),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.#b()},this.#c),this.#p=Date.now()+this.#c)}#b(){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.#w++).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=[zt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var yc=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:zt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:zt[t.type],TTL:t.TTL??t.ttl??yc,data:t.data instanceof Uint8Array?B(t.data):t.data}))}}var Fg=4;function bc(r,t={}){let e=new Oe({concurrency:t.queryConcurrency??Fg});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Yo(o.types).forEach(a=>{s.append("type",zt[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 Kf(){return[bc("https://cloudflare-dns.com/dns-query"),bc("https://dns.google/resolve")]}var Vf=ln(zf(),1);var wc=class{lru;constructor(t){this.lru=(0,Vf.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:zt[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??yc)*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 $f(r){return new wc(r)}var Ug=1e3,Jo=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=$f(t.cacheSize??Ug),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["."]=Kf())}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 u=await c(t,{...e,types:n});for(let l of u.Answer)this.cache.add(t,l);return u}catch(u){a.push(u),e.onProgress?.(new ft("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var zt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(zt||(zt={}));function Hf(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",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=t,s+=l,s>u||(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 Gf=45,Kg=15,$r=new ts;function es(r){if(!(r.length>Kg))return $r.new(r).parseWith(()=>$r.readIPv4Addr())}function rs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Gf))return $r.new(r).parseWith(()=>$r.readIPv6Addr())}function rr(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Gf)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 Wf(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 Xf(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 xc(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 Zf(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 jf(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,cE=parseInt("0xFFFF",16),qg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Vn(r,t){t.length===or&&r.length===nr&&Wf(t,0,11)&&(t=t.slice(12)),t.length===nr&&r.length===or&&Xf(r,qg,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 Yf(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 vc(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=Ec(s,8*n);return{network:Vn(o,i),mask:i}}function Ec(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}=vc(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=Ec(o,8*n.length);this.network=Vn(n,this.mask)}}contains(t){return Yf({network:this.network,mask:this.mask},t)}toString(){let t=Zf(this.mask),e=t!==-1?String(t):jf(this.mask);return xc(this.network)+"/"+e}};function Jt(r){return!!es(r)}function Gr(r){return!!rs(r)}function ns(r){return!!rr(r)}var Qf=Jt,zg=Gr,Sc=function(r){let t=0;if(r=r.toString().trim(),Qf(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(zg(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Qf(e[n]),i;s&&(i=Sc(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")},Jf=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={},Ac={},$g=[[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"]];$g.forEach(r=>{let t=Hg(...r);Ac[t.code]=t,Wr[t.name]=t});function Hg(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function $(r){if(typeof r=="number"){if(Ac[r]!=null)return Ac[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 Gg=$("ip4"),Wg=$("ip6"),Xg=$("ipcidr");function Tc(r,t){switch($(r).code){case 4:case 41:return jg(t);case 42:return Cc(t);case 43:return B(t,"base10");case 6:case 273:case 33:case 132:return rd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Cc(t);case 421:return t0(t);case 444:return ed(t);case 445:return ed(t);case 466:return Jg(t);case 481:return globalThis.encodeURIComponent(Cc(t));default:return B(t,"base16")}}function Pc(r,t){switch($(r).code){case 4:return td(t);case 41:return td(t);case 42:return Ic(t);case 43:return k(t,"base10");case 6:case 273:case 33:case 132:return Dc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ic(t);case 421:return Yg(t);case 444:return e0(t);case 445:return r0(t);case 466:return Qg(t);case 481:return Ic(globalThis.decodeURIComponent(t));default:return k(t,"base16")}}function Lc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===Gg.code||n===Wg.code)&&(e=o),n===Xg.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new Hr(e,t)}var _c=Object.values(Sn).map(r=>r.decoder),Zg=function(){let r=_c[0].or(_c[1]);return _c.slice(2).forEach(t=>r=r.or(t)),r}();function td(r){if(!ns(r))throw new Error("invalid ip address");return Sc(r)}function jg(r){let t=Jf(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 Dc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function rd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ic(r){let t=k(r),e=Uint8Array.from(At(t.length));return Rt([e,t],e.length+t.length)}function Cc(r){let t=Yt(r);if(r=r.slice(dt(t)),r.length!==t)throw new Error("inconsistent lengths");return B(r)}function Yg(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(G.decode(`z${r}`)).bytes:t=ut.parse(r).multihash.bytes;let e=Uint8Array.from(At(t.length));return Rt([e,t],e.length+t.length)}function Qg(r){let t=Zg.decode(r),e=Uint8Array.from(At(t.length));return Rt([e,t],e.length+t.length)}function Jg(r){let t=Yt(r),e=r.slice(dt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+B(e,"base64url")}function t0(r){let t=Yt(r),e=r.slice(dt(t));if(e.length!==t)throw new Error("inconsistent lengths");return B(e,"base58btc")}function e0(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=Ut.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=Dc(n);return Rt([e,o],e.length+o.length)}function r0(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=Ut.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=Dc(n);return Rt([e,o],e.length+o.length)}function ed(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=B(t,"base32"),o=rd(e);return`${n}:${o}`}function nd(r){r=kc(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=kc(o.slice(s).join("/")),t.push([a.code,Pc(a.code,n)]),e.push([a.code,n]);break}let c=Pc(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Tc(a.code,c)])}return{string:od(e),bytes:ss(t),tuples:t,stringTuples:e,path:n}}function Rc(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Yt(r,o),i=dt(s),a=$(s),c=n0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=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,u]);let l=Tc(s,u);if(e.push([s,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:od(e),tuples:t,stringTuples:e,path:n}}function od(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}),kc(t.join("/"))}function ss(r){return Rt(r.map(t=>{let e=$(t[0]),n=Uint8Array.from(At(e.code));return t.length>1&&t[1]!=null&&(n=Rt([n,t[1]])),n}))}function n0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Yt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+dt(e)}}function kc(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 o0=Symbol.for("nodejs.util.inspect.custom"),Nc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),s0=[$("dns").code,$("dns4").code,$("dns6").code,$("dnsaddr").code],Mc=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=Rc(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=nd(t)}else if(Fe(t))e=Rc(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"),u=$("ip6"),l=$("dns6"),f=$("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(s=`%${p??""}`),s0.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${p??""}${s}`,t=m===l.code?6:4),(m===i.code||m===a.code)&&(e=$(m).name==="tcp"?"tcp":"udp",o=parseInt(p??"")),(m===c.code||m===u.code)&&(e=$(m).name==="tcp"?"tcp":"udp",n=`${p??""}${s}`,t=m===u.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 et(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 Mc(`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)}[o0](){return`Multiaddr(${this.#t})`}};var Xr=new Map;function Fe(r){return!!r?.[Nc]}function W(r){return new is(r)}var i0=32,{code:a0}=$("dnsaddr"),Bc=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},sr=async function(t,e={}){let n=e.maxRecursiveDepth??i0;if(n===0)throw new Bc("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===a0)??[],i=await(e?.dns??Hf()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[zt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let l=u.data.replace(/["']/g,"").trim().split("=")[1];if(l==null||a!=null&&!l.includes(a))continue;let f=W(l);if(l.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 hd=ln(dd(),1),ls=hd.default;var h0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:sr}},transportManager:{faultTolerance:$e.FATAL_ALL}};async function pd(r){let t=ls(h0,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 p0(r,t){try{if(typeof r=="string"&&r.length>0)return m0(r);if(typeof r=="number"&&isFinite(r))return t?.long?y0(r):g0(r);throw new Error("Value is not a string or number.")}catch(e){let n=b0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function m0(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=p0;function g0(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?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 b0(r){return typeof r=="object"&&r!==null&&"message"in r}function Fc(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=fs,e.destroy=u,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(l){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let b=g,x=Number(new Date),y=x-(f||x);b.diff=y,b.prev=f,b.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(b,T),h.splice(E,1),E--}return L}),e.formatArgs.call(b,h),(b.log||e.log).apply(b,h)}return g.namespace=l,g.useColors=e.useColors(),g.color=e.selectColor(l),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(l)),p),set:h=>{d=h}}),typeof e.init=="function"&&e.init(g),g}function n(l,f){let d=e(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.substr(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(l))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){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=_0(),w0=["#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 x0(){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 v0(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 E0=console.debug??console.log??(()=>{});function S0(r){try{r?ds?.setItem("debug",r):ds?.removeItem("debug")}catch{}}function A0(){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 _0(){try{return localStorage}catch{}}function I0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var md=Fc({formatArgs:v0,save:S0,load:A0,useColors:x0,setupFormatters:I0,colors:w0,storage:ds,log:E0});var Ft=md;Ft.formatters.b=r=>r==null?"undefined":G.baseEncode(r);Ft.formatters.t=r=>r==null?"undefined":Ut.baseEncode(r);Ft.formatters.m=r=>r==null?"undefined":Ra.baseEncode(r);Ft.formatters.p=r=>r==null?"undefined":r.toString();Ft.formatters.c=r=>r==null?"undefined":r.toString();Ft.formatters.k=r=>r==null?"undefined":r.toString();Ft.formatters.a=r=>r==null?"undefined":r.toString();Ft.formatters.e=r=>r==null?"undefined":gd(r.stack)??gd(r.message)??r.toString();function C0(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 T0(r)}}}function T0(r){let t=C0(`${r}:trace`);return Ft.enabled(`${r}:trace`)&&Ft.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Ft(`${r}:trace`)),Object.assign(Ft(r),{error:Ft(`${r}:error`),trace:t})}function gd(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=Kt(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 Uc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},yd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},bd=new globalThis.TextEncoder;function P0(r,t){let e=Uc[t],n=yd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function L0(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Uc[t],o=yd[t],s=r;for(;s.length>0;){let i=bd.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 Kc(r,{size:t=32,utf8Buffer:e}={}){if(!Uc[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 L0(r,t,e);r=bd.encode(r)}return P0(r,t)}var $n={hash:r=>Number(Kc(r,{size:32})),hashV:(r,t)=>D0($n.hash(r,t))};function D0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var qc=64,te=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=ct(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?et(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 te))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof te))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 te))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 te))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var k0=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 te(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<k0;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 te(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 te(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}},R0={1:.5,2:.84,4:.95,8:.98};function M0(r=.001){return r>.002?2:r>1e-5?4:8}function wd(r,t=.001){let e=M0(t),n=R0[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 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=kt((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:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(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=xd(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:oe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return et(this.marshal(),t.marshal())}async validate(t){let e=xd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},xd=(r,t,e)=>{let n=k(r),o=At(n.byteLength),s=At(t.length),i=At(e.length);return new Q(o,n,s,t,i,e)};function vd(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 Ed="libp2p-peer-record",Sd=Uint8Array.from([3,1]);var Xn;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=kt((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:ct(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(l&7);break}}}return c})),o),n.encode=s=>Dt(s,n.codec()),n.decode=(s,i)=>Lt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=kt((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:ct(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=>Dt(n,r.codec()),r.decode=(n,o)=>Lt(n,r.codec(),o)})(Xn||(Xn={}));var ur=class r{static createFromProtobuf=t=>{let e=Xn.decode(t),n=Vr(Kt(e.peerId)),o=(e.addresses??[]).map(i=>W(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Ed;static CODEC=Sd;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||!vd(this.multiaddrs,t.multiaddrs))}};function N0(r){return r[Symbol.asyncIterator]!=null}function B0(r){if(N0(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=B0;var Ue={},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)=>{Ue[r]==null&&(Ue[r]=[]),Ue[r].push(t)};Qr.removeEventListener=(r,t)=>{Ue[r]!=null&&(Ue[r]=Ue[r].filter(e=>e===t))};Qr.dispatchEvent=function(r,t,e){Ue[r]!=null&&Ue[r].forEach(n=>n(t,e))};var zc=Qr;var Vc="lock:worker:request-read",$c="lock:worker:release-read",Hc="lock:master:grant-read",Gc="lock:worker:request-write",Wc="lock:worker:release-write",Xc="lock:master:grant-write";var Ad=(r=21)=>Math.random().toString().substring(2);var _d=(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 u=l=>{if(l?.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Id=(r,t,e,n)=>async()=>{let o=Ad();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)})},O0={singleProcess:!1},Cd=r=>{if(r=Object.assign({},O0,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return zc.addEventListener("message",_d(e,"requestReadLock",Vc,$c,Hc)),zc.addEventListener("message",_d(e,"requestWriteLock",Gc,Wc,Xc)),e}return{isWorker:!0,readLock:e=>Id(e,Vc,Hc,$c),writeLock:e=>Id(e,Gc,Xc,Wc)}};var fr={},Ke;async function Zc(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 F0=(r,t)=>{if(Ke.isWorker===!0)return{readLock:Ke.readLock(r,t),writeLock:Ke.writeLock(r,t)};let e=new Oe({concurrency:1}),n;return{async readLock(){if(n!=null)return Zc(n,t);n=new Oe({concurrency:t.concurrency,autoStart:!1});let o=n,s=Zc(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Zc(e,t)}}},U0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function jc(r){let t=Object.assign({},U0,r);return Ke==null&&(Ke=Cd(t),Ke.isWorker!==!0&&(Ke.addEventListener("requestReadLock",e=>{fr[e.data.name]!=null&&fr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),Ke.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]=F0(t.name,t)),fr[t.name]}var we;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=kt((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 u={key:"",value:ct(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Dt(i,o.codec()),o.decode=(i,a)=>Lt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=kt((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),bs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=bs.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Dt(i,o.codec()),o.decode=(i,a)=>Lt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=kt((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 u=o.uint32();switch(u>>>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 l=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(l.key,l.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 l=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(l.key,l.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Dt(o,r.codec()),r.decode=(o,s)=>Lt(o,r.codec(),s)})(we||(we={}));var ys;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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:ct(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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(ys||(ys={}));var bs;(function(r){let t;r.codec=()=>(t==null&&(t=kt((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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(bs||(bs={}));function K0(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=G.decode(`z${r}`);e=Kt(o)}let n=zr(t.publicKey,e);return dc(n)}function ws(r,t,e){let n=we.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:K0(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 Td(r,t){return q0(r.addresses,t.addresses)&&z0(r.protocols,t.protocols)&&V0(r.publicKey,t.publicKey)&&$0(r.peerRecordEnvelope,t.peerRecordEnvelope)&&H0(r.metadata,t.metadata)&&G0(r.tags,t.tags)}function q0(r,t){return Ld(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!et(e.multiaddr,n.multiaddr)))}function z0(r,t){return Ld(r,t,(e,n)=>e===n)}function V0(r,t){return Pd(r,t)}function $0(r,t){return Pd(r,t)}function H0(r,t){return Dd(r,t,(e,n)=>et(e,n))}function G0(r,t){return Dd(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function Pd(r,t){return r==null&&t==null?!0:r!=null&&t!=null?et(r,t):!1}function Ld(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 Dd(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 xe="/",kd=new TextEncoder().encode(xe),vs=kd[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(xe))}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=kd),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(xe).slice(1)}type(){return W0(this.baseNamespace())}name(){return X0(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(xe)||(t+=xe),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(xe):new r(t.slice(0,-1).join(xe))}child(t){return this.toString()===xe?t:t.toString()===xe?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(),...Z0(t.map(e=>e.namespaces()))])}};function W0(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function X0(r){let t=r.split(":");return t[t.length-1]}function Z0(r){return[].concat(...r)}var Yc="/peers/";function jn(r){if(!mo(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new dr(`${Yc}${t}`)}async function Rd(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)),!Fe(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,u=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:Md})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Es(d,{validate:Nd,map:Bd})}t.peerRecordEnvelope!=null&&(u=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:Md})}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:Bd})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=oe(o.id.publicKey):t.publicKey!=null?l=oe(t.publicKey):r.publicKey!=null&&(l=oe(r.publicKey));let f={addresses:await Rd(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(m=>et(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 Md(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 Bd(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 Od(r){let t=r.toString().split("/")[2],e=ut.parse(t,Ut);return Fn(e)}function Qc(r,t,e){let n=Od(r);return ws(n,t,e)}function j0(r,t){return{prefix:Yc,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Qc(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Qc(n.key,n.value,t),Qc(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=jc({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=we.decode(n);if(this.#r(o))throw await this.datastore.delete(e),new He;return xs(t,o,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(j0(t??{},this.maxAddressAge))){let o=Od(e);if(o.equals(this.peerId))continue;let s=we.decode(n);if(this.#r(s)){await this.datastore.delete(e);continue}yield xs(o,s,this.maxAddressAge)}}async#t(t){try{let e=jn(t),n=await this.datastore.get(e),o=we.decode(n);if(this.#r(o))throw await this.datastore.delete(e),new He;return{peerPB:o,peer:ws(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=we.encode(e);return await this.datastore.put(jn(t),o),{peer:ws(t,o,this.maxAddressAge),previous:n?.peer,updated:n==null||!Td(e,n.peerPB)}}#r(t){if(t.updated==null)return!0;let e=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,o=t.addresses.filter(s=>s.observed!=null&&s.observed>n);return e&&o.length===0}};var Jc=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 Fd(r,t={}){return new Jc(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 Y0(r){return r[Symbol.asyncIterator]!=null}function Q0(r){if(Y0(r))return(async()=>{for await(let t of r);})();for(let t of r);}var tl=Q0;function J0(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 Ud=J0;function ty(r){return r[Symbol.asyncIterator]!=null}function ey(r,t){let e=0;if(ty(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Ud(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=ey;function ry(r){return r[Symbol.asyncIterator]!=null}function ny(r,t){return ry(r)?async function*(){yield*(await Zn(r)).sort(t)}():function*(){yield*Zn(r).sort(t)}()}var el=ny;function oy(r){return r[Symbol.asyncIterator]!=null}function sy(r,t){return oy(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 rl=sy;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 tl(this.putMany(t,n)),t=[],await tl(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)=>el(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=hr(n,()=>o++>=s)}return t.limit!=null&&(n=rl(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)=>el(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=hr(n,()=>s++>=o)}return t.limit!=null&&(n=rl(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 Kd(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 zd=ln(qd(),1),iy=["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"],ay=iy.map(r=>new zd.Netmask(r));function nl(r){for(let t of ay)if(t.contains(r))return!0;return!1}function cy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ly(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 nl(o)}function uy(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function fy(r){let t=r.split(":"),e=t[t.length-1];return nl(e)}function dy(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 qe(r){return Jt(r)?nl(r):cy(r)?ly(r):uy(r)?fy(r):Gr(r)?dy(r):void 0}var hy=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}"}),J=()=>({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{Ma.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),X=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Ct=(...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 it(...r){function t(o){let s=hy(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()),sl=V(z("dns"),pr()),v6=it(Ps,X(J())),E6=it(Ls,X(J())),S6=it(Ds,X(J())),A6=it(Ct(sl,Ds,Ps,Ls),X(J())),Vd=V(z("ip4"),Jr(Jt)),$d=V(z("ip6"),Jr(Gr)),il=Ct(Vd,$d),ve=Ct(il,sl,Ps,Ls,Ds),_6=it(Ct(il,V(Ct(sl,Ds,Ps,Ls),X(J())))),al=it(Vd),cl=it($d),I6=it(il),ll=V(ve,z("tcp"),Qn()),to=V(ve,z("udp"),Qn()),eo=it(V(ll,X(J()))),C6=it(to),ul=V(to,z("quic"),X(J())),ks=V(to,z("quic-v1"),X(J())),py=Ct(ul,ks),T6=it(ul),Hd=it(ks),ol=Ct(ve,ll,to,ul,ks),Gd=Ct(V(ol,z("ws"),X(J()))),mr=it(Gd),Wd=Ct(V(ol,z("wss"),X(J())),V(ol,z("tls"),X(V(z("sni"),pr())),z("ws"),X(J()))),ro=it(Wd),Xd=V(to,z("webrtc-direct"),X(Jn()),X(Jn()),X(J())),fl=it(Xd),Zd=V(ks,z("webtransport"),X(Jn()),X(Jn()),X(J())),dl=it(Zd),Ts=Ct(Gd,Wd,V(ll,X(J())),V(py,X(J())),V(ve,X(J())),Xd,Zd,J()),P6=it(Ts),my=V(Ts,z("p2p-circuit"),J()),no=it(my),gy=Ct(V(Ts,z("p2p-circuit"),z("webrtc"),X(J())),V(Ts,z("webrtc"),X(J())),V(z("webrtc"),X(J()))),hl=it(gy),yy=Ct(V(ve,z("tcp"),Qn(),z("http"),X(J())),V(ve,z("http"),X(J()))),L6=it(yy),by=Ct(V(ve,z("tcp"),Ct(V(z("443"),z("http")),V(Qn(),z("https"))),X(J())),V(ve,z("tls"),z("http"),X(J())),V(ve,z("https"),X(J()))),D6=it(by),wy=Ct(V(z("memory"),pr(),X(J()))),k6=it(wy);var jd=864e13;var xy=448,pl=449,vy=53,Ey=54,Sy=55,Ay=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=qe(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?jd-Date.now():0,lastVerified:o?jd-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(l=>[$(l[0]).name,l[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]===xy&&t[n+1]?.[0]!==pl)return t.splice(n+1,0,[pl,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]===pl||e[0]===vy||e[0]===Ey||e[0]===Sy||e[0]===Ay)return e[1]}};var ml=4,gl=41,yl=6,_y=273,Ms=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:Jt(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]===yl?"tcp":"udp",s=parseInt(e[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===n&&l.externalPort===s&&l.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,n,s,o),i=i||l.verified,c.splice(u,1),u--)}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]===ml||o[0][0]===gl)&&o[1][0]===yl?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===ml||o[0][0]===gl)&&o[1][0]===_y&&(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?ml:gl,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]===yl?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===o&&l.externalPort===i&&l.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,o,i,s),a=a||l.verified,l.verified=!1,l.expires=Date.now()+e)}return a}};function Yd(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 Ns(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function gr(r){try{if(!Ns(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:qe(t)??!1}catch{}return!0}var Iy={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??Iy.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)||Yd(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 Cy=[4,41,53,54,55,56];function bl(r){try{let[[t]]=r.stringTuples();return Cy.includes(t)}catch{}return!1}var Ty={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??Ty.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:!bl(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(bl(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Qd=6e4,Jd={maxObservedAddresses:10,addressVerificationTTL:Qd*10,addressVerificationRetry:Qd*5},Py=r=>r;function wl(r,t){let e=r.getPeerId();return e!=null&&ie(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 Ms(t,e),this.transportAddresses=new Os(t,e),this.announceFilter=e.announceFilter??Py,this.observedAddressFilter=Gn(1024),this.addressVerificationTTL=e.addressVerificationTTL??Jd.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Jd.addressVerificationRetry,this._updatePeerStoreAddresses=Kd(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${Jt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(W(`/ip${Jt(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"||qe(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>mr.exactMatch(s)||ro.exactMatch(s),s=>eo.exactMatch(s),s=>Hd.exactMatch(s)];for(let s of o){if(!s(t))continue;let i=n.filter(u=>u.getAddrs().filter(l=>l.toOptions().family===4&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>u.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 th;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(th||(th={}));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"}},br=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 xl=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")}},Dy=["metrics","connectionProtector","dns"],ky=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function eh(r={}){let t=new xl(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!ky.includes(o)){let i=t.components[o];if(i==null&&!Dy.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 rh(r){let t={};for(let e of Object.values(r.components))for(let n of Ry(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of My(e))if(t[n]!==!0)throw new Ks(`Service "${Ny(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Ry(r){return Array.isArray(r?.[dn])?r[dn]:[]}function My(r){return Array.isArray(r?.[zi])?r[zi]:[]}function Ny(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var By=4,Oy=41;function nh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(mr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===By||e[0][0]===Oy?!!qe(`${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 oh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Fy=new WeakMap;function Uy({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(oh());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(oh())},l=()=>{o&&o.removeEventListener("abort",u)},f=new Promise((d,m)=>{i=()=>{l(),d(n)},a=m,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Fy.set(f,()=>{c(s),s=null,i()}),f}}var Ky=Uy(),sh=Ky;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 vl}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 sh(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)}},vl=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:ie(e),r.forEach(n=>{if(!Fe(n))throw new Ae("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=ie(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 qy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function ih(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??qy;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",ch="last-dial-success";var ti=100,ei=50;async function lh(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 Lc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var zy={maxConnections:ti,allow:[]},ri=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??zy.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 u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}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(u=>u.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await ih(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 lt(){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 El=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function oi(r={}){return Vy(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 Vy(r,t){t=t??{};let e=t.onEnd,n=new en,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(y){b(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},u=h=>s!=null?s(h):(n.push(h),o),l=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 u({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?l(h):u({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 b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let x,y;b!=null&&(x=new Promise((E,_)=>{y=()=>{_(new El)},b.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&b!=null&&b?.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 Sl=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 Sl(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",l),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},u=f=>{a(),i(f.detail)},l=()=>{a(),i(o)};e?.addEventListener("abort",l),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var si=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 ze(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new si(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new si(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 ii=class{deferred;signal;constructor(t){this.signal=t,this.deferred=lt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Gt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $y(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ai=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=$y(),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 Gt),this.cleanup())}async join(t={}){let e=new ii(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 ze(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 le{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 ai(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 Gt)}),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=oi({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 Gt("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 ci=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 Ee(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 Al(r){if(!Ns(r))return!1;let{address:t}=r.nodeAddress();return uh(t)}function Hy(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=hl.exactMatch(r.multiaddr),u=hl.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=fl.exactMatch(r.multiaddr),f=fl.exactMatch(t.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=dl.exactMatch(r.multiaddr),m=dl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function Gy(r,t){let e=Al(r.multiaddr),n=Al(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Wy(r,t){let e=gr(r.multiaddr),n=gr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Xy(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Zy(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(Hy).sort(Xy).sort(Zy).sort(Wy).sort(Gy)}var li={maxParallelDials:ei,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:sr}},ui=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??li.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??li.maxDialQueueLength,this.dialTimeout=e.dialTimeout??li.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 ci({concurrency:e.maxParallelDials??li.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Gt.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 u of o)if(c.has(u.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=Ee([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Tl,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,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],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}l.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(m=>m.multiaddr.toString())),t?.onProgress?.(new ft("dial-queue:calculated-addresses",l));for(let m of l){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:{[ch]: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:{[ah]: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);u.push(p)}}}throw u.length===1?u[0]:new AggregateError(u,"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 lh(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 u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?fh(u):u.sort(this.addressSorter);if(l.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",l.map(({multiaddr:f})=>f.toString())),l}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 fi=class extends on{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var bh=ln(gh(),1);var Yy=Object.prototype.toString,Qy=r=>Yy.call(r)==="[object Error]",Jy=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 Pl(r){return r&&Qy(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Jy.has(r.message):!1}var Ll=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 Dl(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=bh.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 Ll)throw c.originalError;if(c instanceof TypeError&&!Pl(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(u){yh(u,a,t),i(),n(u)}}})})}var di=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 fi({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);wh(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Dl(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(qi)&&(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=>wh(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 wh(r){for(let t of r.tags.keys())if(t.startsWith(qi))return!0;return!1}var Tl=50,kl={maxConnections:ti,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},hi=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??kl.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??kl.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Qs({points:e.inboundConnectionThreshold??kl.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 ui(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 di({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 Jl(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 tu(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 ce("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??Tl});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 Ae("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 rb=1.2,nb=2,ob=2e3,pi=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??nb,this.timeoutMultiplier=t.timeoutMultiplier??rb,this.minTimeout=t.minTimeout??ob,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=Ee([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 Rl=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=lt(),this.haveNext=lt()}[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=lt(),t}async throw(t){return this.ended=!0,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 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=lt(),await ze(this.readNext.promise,e?.signal,e)}};function xh(){return new Rl}var mi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ml=class extends Error{code;constructor(t,e){super(t),this.code=e}},Nl=class extends Ml{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function gi(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,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((l,f)=>{c=()=>{f(new Nl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),u]);return f===!0?new Q:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new mi("unexpected end of input");o.append(f)}let l=o.sublist(0,i);return o.consume(i),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},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 sb=1e4,ib="1.0.0",ab="ping",cb="ipfs",vh=32,lb=!0,yi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??cb}/${ab}/${ib}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??sb,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??lb,this.timeout=new pi({...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=gi(o);e=Date.now(),await Promise.all([s.write(Kr(vh),{signal:n}),s.read(vh,{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)}};function ub(r){return r[Symbol.asyncIterator]!=null}async function fb(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)t.push(n)})),t.end()}catch(e){t.end(e)}}async function*db(r){let t=oi({objectMode:!0});fb(r,t).catch(()=>{}),yield*t}function*hb(r){for(let t of r)yield*t}function pb(...r){let t=[];for(let e of r)ub(e)||t.push(e);return t.length===r.length?hb(t):db(r)}var ao=pb;var bi=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 ce;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new ce;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var wi=globalThis.CustomEvent??Event;async function*Bl(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=lt(),a=lt(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=lt(),await i.promise),l)break;let g={done:!1};s.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,o.dispatchEvent(new wi("task-complete"))},h=>{g.done=!0,g.err=h,o.dispatchEvent(new wi("task-complete"))})}c=!0,o.dispatchEvent(new wi("task-complete"))}catch(p){u=p,o.dispatchEvent(new wi("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 l=!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 l=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=lt(),await a.promise),u!=null)throw u;if(n?yield*d():yield*m(),c&&s.length===0)break}}var xi=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 Bl(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 vi=class extends le{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=Ee([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),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=Ee([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 ze(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 Ol=32,Fl=64,Ei=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:Ol,maxOutboundStreams:Fl},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 Ul=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 Eh(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ul({name:t,metrics:e}):n=new Map,n}var Si=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=Eh({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 ce("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 u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),al.matches(c)?e.ipv4.attempts++:cl.matches(c)&&e.ipv6.attempts++,n.push(u.listen(c).then(()=>{e.errors.delete(c.toString()),al.matches(c)&&e.ipv4.success++,cl.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 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:
|
|
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
|
|
8
|
-
`);async function xr(r,t,e){await r.write(t,e)}async function
|
|
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 Fl=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 _h(){return new Fl}var Ei=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ih(r,t){let e=_h();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 Ei("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 Si=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ai=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_i=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function co(r,t={}){let e=Ih(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=dt(t.maxDataLength));let n=t?.lengthDecoder??Qt,o=t?.lengthEncoder??_t;return{read:async i=>{let a=-1,c=new Q;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 Si("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new _i("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ai("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new Q(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Q(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var bw=k(`
|
|
8
|
+
`);async function xr(r,t,e){await r.write(t,e)}async function Ch(r,t,e){await r.writeV(t,e)}async function xw(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==bw[0])throw t.log.error("Invalid mss message - missing newline",e),new bo("Missing newline");return e.sublist(0,-1)}async function Ve(r,t){let e=await xw(r,t);return B(e.subarray())}async function lo(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return vw(r,t[0],e);let n=co(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=k(`${vt}
|
|
9
9
|
`),i=k(`${o}
|
|
10
|
-
`);await
|
|
11
|
-
`),e),e.log.trace("select: reading protocol response");let
|
|
12
|
-
`;yield new Q(Uint8Array.from([19]),k(`${
|
|
13
|
-
`),
|
|
10
|
+
`);await Ch(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await Ve(n,e);if(e.log.trace('select: read "%s"',a),a===vt&&(e.log.trace("select: reading protocol response"),a=await Ve(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 xr(n,k(`${c}
|
|
11
|
+
`),e),e.log.trace("select: reading protocol response");let l=await Ve(n,e);if(e.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:n.unwrap(),protocol:c}}throw new fn("protocol selection failed")}function vw(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=co({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 L=`${t}
|
|
12
|
+
`;yield new Q(Uint8Array.from([19]),k(`${vt}
|
|
13
|
+
`),_t(L.length),k(L),_).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([k(`${vt}
|
|
14
14
|
`),k(`${t}
|
|
15
|
-
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',
|
|
16
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',
|
|
17
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new Q(...t.map(i=>
|
|
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 Ve(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',x),x===vt&&(x=await Ve(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',x,t),x!==t)throw new fn("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 Ii=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},an=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ci=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ti(r){return r[Symbol.asyncIterator]!=null}function Ph(r,t){if(r.byteLength>t)throw new an("Message length too long")}var Li=r=>{let t=dt(r),e=St(t);return _t(r,e),Li.bytes=t,e};Li.bytes=0;function Di(r,t){t=t??{};let e=t.lengthEncoder??Li,n=t?.maxDataLength??4194304;function*o(s){Ph(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ti(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}Di.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Li,n=t?.maxDataLength??4194304;return Ph(r,n),new Q(e(r.byteLength),r)};var vr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(vr||(vr={}));var ql=r=>{let t=Qt(r);return ql.bytes=dt(t),t};ql.bytes=0;function Kl(r,t){let e=new Q,n=vr.LENGTH,o=-1,s=t?.lengthDecoder??ql,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===vr.LENGTH)try{if(o=s(e),o<0)throw new Ii("Invalid message length");if(o>a)throw new an("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=vr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ci("Message length length too long");break}throw l}if(n===vr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=vr.LENGTH}}}return Ti(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new uo("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new uo("Unexpected end of input")}()}Kl.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 Kl(n,{...t??{},onLength:s=>{e=s}})};async function fo(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=co(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await Ve(n,e);if(e.log.trace('handle: read "%s"',o),o===vt){e.log.trace('handle: respond with "%s" for "%s"',vt,o),await xr(n,k(`${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 xr(n,k(`${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 Q(...t.map(i=>Di.single(k(`${i}
|
|
18
18
|
`))),k(`
|
|
19
19
|
`));e.log.trace('handle: respond with "%s" for %s',t,o),await xr(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 xr(n,k(`na
|
|
20
|
-
`),e),e.log('handle: responded with "na" for "%s"',o)}}var xb=500,Vl=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";[Ql]=!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(xb);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 Ih(r){return new Vl(r)}function Eb(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Ol}function Sb(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??Fl}function Ch(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ri=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=Ee([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=ie(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 u=t;if(n?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(t.log("protecting the %s connection",e),u=await l.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new ft(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let l={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,l)}else{let l=t.remoteAddr.getPeerId();if(l==null)throw new Ae(`${e} connection that skipped encryption must have a peer id`);let f=ie(l);c="native",s=f}if(s.equals(this.components.peerId)){let l=new Ar("Can not dial self");throw t.abort(l),l}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 l=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=l.muxerFactory,i=l.stream}}catch(l){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,l),l}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,u,l,f;a!=null&&(u=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:b,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=Eb(x,this.components.registrar);if(Ch(x,"inbound",f)===y){let _=new vo(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=b.source,p.sink=b.sink,p.protocol=x,b.closeWrite!=null&&(p.closeWrite=b.closeWrite),b.closeRead!=null&&(p.closeRead=b.closeRead),b.close!=null&&(p.close=b.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()})}}),l=async(p,g={})=>{if(u==null)throw new yr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await u.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:b,protocol:x}=await lo(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=Sb(x,this.components.registrar,g),E=Ch(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=b.source,h.sink=b.sink,h.protocol=x,b.closeWrite!=null&&(h.closeWrite=b.closeWrite),b.closeRead!=null&&(h.closeRead=b.closeRead),b.close!=null&&(h.close=b.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(b){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,b),h.timeline.close==null&&h.abort(b),b}},Promise.all([u.sink(s.source),s.sink(u.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=Ih({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:l??m,getStreams:()=>u?.streams??[],close:async p=>{await u?.close(p),await o.close(p)},abort:p=>{o.abort(p),u?.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 br(`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 br(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 br(`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 br(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 Mi="2.8.1",Ni="js-libp2p";function Ph(r,t){return`${r??Ni}/${t??Mi} browser/${globalThis.navigator.userAgent}`}var Bi=class extends le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new le,n=e.dispatchEvent.bind(e);e.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||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??Mi,i=this.components=eh({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Ph(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Cs,connectionGater:nh(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",Fd(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",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Ri(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(t.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Si(this.components,t.transportManager)),this.configureComponent("connectionManager",new hi(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new yi(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Ei(this.components)),this.configureComponent("addressManager",new Fs(this.components,t.addresses));let a=(t.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new xi(this.components,{routers:a}));let c=(t.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new bi(this.components,{routers:c})),this.configureComponent("randomWalk",new vi(this.components)),(t.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),t.services!=null)for(let u of Object.keys(t.services)){let l=t.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[Fi]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Fi])),f[Ki]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ki])),f[Ui]!=null&&(this.log("registering service %s for peer discovery",u),f[Ui].addEventListener?.("peer",d=>{this.#t(d)}))}rh(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={}){Fe(t)&&(t=ie(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=Rt([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 Ab(r={}){r.privateKey??=await Df("Ed25519");let t=new Bi({...await pd(r),peerId:Nf(r.privateKey)});return r.start!==!1&&await t.start(),t}return Vh(_b);})();
|
|
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-071267286",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);})();
|
|
21
21
|
/*! Bundled license information:
|
|
22
22
|
|
|
23
23
|
@noble/hashes/esm/utils.js:
|