libp2p 2.8.5-9b33d202e → 2.8.5-cdc63e6cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
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 lp=Object.create;var vo=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var fp=Object.getOwnPropertyNames;var dp=Object.getPrototypeOf,hp=Object.prototype.hasOwnProperty;var Pe=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Bt=(r,t)=>{for(var e in t)vo(r,e,{get:t[e],enumerable:!0})},su=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fp(t))!hp.call(r,o)&&o!==e&&vo(r,o,{get:()=>t[o],enumerable:!(n=up(t,o))||n.enumerable});return r};var hn=(r,t,e)=>(e=r!=null?lp(dp(r)):{},su(t||!r||!r.__esModule?vo(e,"default",{value:r,enumerable:!0}):e,r)),pp=r=>su(vo({},"__esModule",{value:!0}),r);var fd=Pe((GE,Tc)=>{"use strict";var qg=Object.prototype.hasOwnProperty,Nt="~";function jn(){}Object.create&&(jn.prototype=Object.create(null),new jn().__proto__||(Nt=!1));function zg(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function ud(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new zg(e,n||r,o),i=Nt?Nt+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 os(r,t){--r._eventsCount===0?r._events=new jn:delete r._events[t]}function It(){this._events=new jn,this._eventsCount=0}It.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)qg.call(e,n)&&t.push(Nt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};It.prototype.listeners=function(t){var e=Nt?Nt+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=Nt?Nt+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=Nt?Nt+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};It.prototype.on=function(t,e,n){return ud(this,t,e,n,!1)};It.prototype.once=function(t,e,n){return ud(this,t,e,n,!0)};It.prototype.removeListener=function(t,e,n,o){var s=Nt?Nt+t:t;if(!this._events[s])return this;if(!e)return os(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&os(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:os(this,s)}return this};It.prototype.removeAllListeners=function(t){var e;return t?(e=Nt?Nt+t:t,this._events[e]&&os(this,e)):(this._events=new jn,this._eventsCount=0),this};It.prototype.off=It.prototype.removeListener;It.prototype.addListener=It.prototype.on;It.prefixed=Nt;It.EventEmitter=It;typeof Tc<"u"&&(Tc.exports=It)});var gd=Pe((mv,md)=>{md.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 Rd=Pe((zS,Md)=>{"use strict";Md.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var Kd=Pe((Fd,Ud)=>{"use strict";var ms=Rd(),{hasOwnProperty:Od}=Object.prototype,{propertyIsEnumerable:h0}=Object,Jr=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),p0=Fd,Nd={concatArrays:!1,ignoreUndefined:!1},gs=r=>{let t=[];for(let e in r)Od.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)h0.call(r,n)&&t.push(n)}return t};function tn(r){return Array.isArray(r)?m0(r):ms(r)?g0(r):r}function m0(r){let t=r.slice(0,0);return gs(r).forEach(e=>{Jr(t,e,tn(r[e]))}),t}function g0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return gs(r).forEach(e=>{Jr(t,e,tn(r[e]))}),t}var Bd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Jr(r,o,Jc(r[o],t[o],n)):Jr(r,o,tn(t[o])))}),r),y0=(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++)Od.call(s,a)&&(i.push(String(a)),s===r?Jr(n,o++,s[a]):Jr(n,o++,tn(s[a])));n=Bd(n,s,gs(s).filter(a=>!i.includes(a)),e)}),n};function Jc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?y0(r,t,e):!ms(t)||!ms(r)?tn(t):Bd(r,t,gs(t),e)}Ud.exports=function(...r){let t=Jc(tn(Nd),this!==p0&&this||{},Nd),e={_:{}};for(let n of r)if(n!==void 0){if(!ms(n))throw new TypeError("`"+n+"` is not an Option Object");e=Jc(e,{_:n},t)}return e._}});var mh=Pe(io=>{(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}(),io.ip2long=i,io.long2ip=a,io.Netmask=r}).call(io)});var Vh=Pe((a8,zh)=>{function Wt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}zh.exports=Wt;Wt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Wt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Wt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Wt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Wt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Wt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Wt.prototype.start=Wt.prototype.try;Wt.prototype.errors=function(){return this._errors};Wt.prototype.attempts=function(){return this._attempts};Wt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var Hh=Pe(Ar=>{var rw=Vh();Ar.operation=function(r){var t=Ar.timeouts(r);return new rw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ar.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};Ar.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};Ar.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=Ar.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=Pe((l8,$h)=>{$h.exports=Hh()});var Dw={};Bt(Dw,{createLibp2p:()=>Lw});var iu=Symbol.for("@libp2p/connection");var $i=Symbol.for("@libp2p/content-routing");var Gi=Symbol.for("@libp2p/peer-discovery");var So=Symbol.for("@libp2p/peer-id");function Ao(r){return!!r?.[So]}var Wi=Symbol.for("@libp2p/peer-routing");var ji="keep-alive";var Uw=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 Xt=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"}},Cr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},pn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var _o=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Pr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Ge=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Tr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Te=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Io=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Co=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},mn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Po=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var To=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},fe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Lr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Dr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Lo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Do=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Le=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var de=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function ko(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function au(...r){let t=[];for(let e of r)ko(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 cu(...r){let t=[];for(let e of r)ko(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 gn=Symbol.for("@libp2p/service-capabilities"),Xi=Symbol.for("@libp2p/service-dependencies");var ta={};Bt(ta,{base58btc:()=>q,base58flickr:()=>xp});var db=new Uint8Array(0);function lu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function he(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function uu(r){return new TextEncoder().encode(r)}function fu(r){return new TextDecoder().decode(r)}function mp(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],k=0,I=y-1;(_!==0||k<h)&&I!==-1;I--,k++)_+=256*E[I]>>>0,E[I]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=k,w++}for(var T=y-h;T!==y&&E[T]===0;)T++;for(var D=c.repeat(g);T<y;++T)D+=r.charAt(E[T]);return D}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,k=x-1;(E!==0||_<w)&&k!==-1;k--,_++)E+=a*y[k]>>>0,y[k]=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 T=new Uint8Array(h+(x-I)),D=h;I!==x;)T[D++]=y[I++];return T}}}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 gp=mp,yp=gp,hu=yp;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")}},Yi=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 pu(this,t)}},Qi=class{decoders;constructor(t){this.decoders=t}or(t){return pu(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 pu(r,t){return new Qi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ji=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 Yi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function kr({name:r,prefix:t,encode:e,decode:n}){return new Ji(r,t,e,n)}function De({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=hu(e,r);return kr({prefix:t,name:r,encode:n,decode:s=>he(o(s))})}function wp(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 bp(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 it({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return kr({prefix:t,name:r,encode(o){return bp(o,n,e)},decode(o){return wp(o,n,e,r)}})}var q=De({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xp=De({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ea={};Bt(ea,{base32:()=>Kt,base32hex:()=>Ap,base32hexpad:()=>Ip,base32hexpadupper:()=>Cp,base32hexupper:()=>_p,base32pad:()=>vp,base32padupper:()=>Sp,base32upper:()=>Ep,base32z:()=>Pp});var Kt=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ep=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),vp=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sp=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ap=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_p=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ip=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cp=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pp=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ra={};Bt(ra,{base36:()=>yn,base36upper:()=>Tp});var yn=De({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Tp=De({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Lp=yu,mu=128,Dp=127,kp=~Dp,Mp=Math.pow(2,31);function yu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Mp;)t[e++]=r&255|mu,r/=128;for(;r&kp;)t[e++]=r&255|mu,r>>>=7;return t[e]=r|0,yu.bytes=e-n+1,t}var Rp=na,Np=128,gu=127;function na(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw na.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&gu)<<o:(i&gu)*Math.pow(2,o),o+=7}while(i>=Np);return na.bytes=s-n,e}var Op=Math.pow(2,7),Bp=Math.pow(2,14),Fp=Math.pow(2,21),Up=Math.pow(2,28),Kp=Math.pow(2,35),qp=Math.pow(2,42),zp=Math.pow(2,49),Vp=Math.pow(2,56),Hp=Math.pow(2,63),$p=function(r){return r<Op?1:r<Bp?2:r<Fp?3:r<Up?4:r<Kp?5:r<qp?6:r<zp?7:r<Vp?8:r<Hp?9:10},Gp={encode:Lp,decode:Rp,encodingLength:$p},Wp=Gp,wn=Wp;function bn(r,t=0){return[wn.decode(r,t),wn.decode.bytes]}function Mr(r,t,e=0){return wn.encode(r,t,e),t}function Rr(r){return wn.encodingLength(r)}function Zt(r,t){let e=t.byteLength,n=Rr(r),o=n+Rr(e),s=new Uint8Array(o+e);return Mr(r,s,0),Mr(e,s,n),s.set(t,o),new Nr(r,e,t,s)}function qt(r){let t=he(r),[e,n]=bn(t),[o,s]=bn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Nr(e,o,i,t)}function wu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&lu(r.bytes,e.bytes)}}var Nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function bu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Xp(e,oa(r),t??q.encoder);default:return Zp(e,oa(r),t??Kt.encoder)}}var xu=new WeakMap;function oa(r){let t=xu.get(r);if(t==null){let e=new Map;return xu.set(r,e),e}return t}var ot=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!==xn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Yp)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=Zt(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&&wu(t.multihash,n.multihash)}toString(t){return bu(this,t)}toJSON(){return{"/":bu(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??Eu(n,o,s.bytes))}else if(e[Qp]===!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!==xn)throw new Error(`Version 0 CID must use dag-pb (code: ${xn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Eu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,xn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=he(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Nr(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]=bn(t.subarray(e));return e+=d,f},o=n(),s=xn;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]=jp(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 oa(s).set(n,t),s}};function jp(r,t){switch(r[0]){case"Q":{let e=t??q;return[q.prefix,e.decode(`${q.prefix}${r}`)]}case q.prefix:{let e=t??q;return[q.prefix,e.decode(r)]}case Kt.prefix:{let e=t??Kt;return[Kt.prefix,e.decode(r)]}case yn.prefix:{let e=t??yn;return[yn.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 Xp(r,t,e){let{prefix:n}=e;if(n!==q.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 Zp(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 xn=112,Yp=18;function Eu(r,t,e){let n=Rr(r),o=n+Rr(t),s=new Uint8Array(o+e.byteLength);return Mr(r,s,0),Mr(t,s,n),s.set(e,o),s}var Qp=Symbol.for("@ipld/js-cid/CID");var sa={};Bt(sa,{identity:()=>Yt});var vu=0,Jp="identity",Su=he;function tm(r){return Zt(vu,Su(r))}var Yt={code:vu,name:Jp,encode:Su,digest:tm};function Q(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 at(r=0){return new Uint8Array(r)}function vt(r=0){return new Uint8Array(r)}function Pt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=vt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var _u=Symbol.for("@achingbrain/uint8arraylist");function Au(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 Ro(r){return!!r?.[_u]}var W=class r{bufs;length;[_u]=!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(Ro(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(Ro(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=Au(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Au(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(Ro(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 Pt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Pt(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(!Ro(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=vt(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=at(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=at(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=at(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=vt(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=at(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=at(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=at(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=at(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=at(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(!Q(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 ia={};Bt(ia,{base10:()=>em});var em=De({prefix:"9",name:"base10",alphabet:"0123456789"});var aa={};Bt(aa,{base16:()=>rm,base16upper:()=>nm});var rm=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nm=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ca={};Bt(ca,{base2:()=>om});var om=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var la={};Bt(la,{base256emoji:()=>lm});var Iu=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}"),sm=Iu.reduce((r,t,e)=>(r[e]=t,r),[]),im=Iu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function am(r){return r.reduce((t,e)=>(t+=sm[e],t),"")}function cm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=im[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var lm=kr({prefix:"\u{1F680}",name:"base256emoji",encode:am,decode:cm});var da={};Bt(da,{base64:()=>ua,base64pad:()=>um,base64url:()=>fa,base64urlpad:()=>fm});var ua=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),um=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fa=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fm=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ha={};Bt(ha,{base8:()=>dm});var dm=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pa={};Bt(pa,{identity:()=>hm});var hm=kr({prefix:"\0",name:"identity",encode:r=>fu(r),decode:r=>uu(r)});var Xb=new TextEncoder,Zb=new TextDecoder;var ya={};Bt(ya,{sha256:()=>Or,sha512:()=>gm});function ga({name:r,code:t,encode:e}){return new ma(r,t,e)}var ma=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?Zt(this.code,e):e.then(n=>Zt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Pu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Or=ga({name:"sha2-256",code:18,encode:Pu("SHA-256")}),gm=ga({name:"sha2-512",code:19,encode:Pu("SHA-512")});var En={...pa,...ca,...ha,...ia,...aa,...ea,...ra,...ta,...da,...la},cx={...ya,...sa};function Lu(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Tu=Lu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),wa=Lu("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=vt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ym={utf8:Tu,"utf-8":Tu,hex:En.base16,latin1:wa,ascii:wa,binary:wa,...En},No=ym;function P(r,t="utf8"){let e=No[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function O(r,t="utf8"){let e=No[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var wm=parseInt("11111",2),ba=parseInt("10000000",2),bm=parseInt("01111111",2),Du={0:vn,1:vn,2:xm,3:Sm,4:Am,5:vm,6:Em,16:vn,22:vn,48:vn};function pe(r,t={offset:0}){let e=r[t.offset]&wm;if(t.offset++,Du[e]!=null)return Du[e](r,t);throw new Error("No decoder for tag "+e)}function Sn(r,t){let e=0;if((r[t.offset]&ba)===ba){let n=r[t.offset]&bm,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function vn(r,t){Sn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=pe(r,t);if(n===null)break;e.push(n)}return e}function xm(r,t){let e=Sn(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 Em(r,t){let e=Sn(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function vm(r,t){return t.offset++,null}function Sm(r,t){let e=Sn(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Am(r,t){let e=Sn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function _m(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new W;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Oo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=_m(r.byteLength);return new W(Uint8Array.from([t.byteLength|ba]),t)}function Tt(r){let t=new W,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new W(Uint8Array.from([2]),Oo(t),t)}function An(r){let t=Uint8Array.from([0]),e=new W(t,r);return new W(Uint8Array.from([3]),Oo(e),e)}function ku(r){return new W(Uint8Array.from([4]),Oo(r),r)}function Qt(r,t=48){let e=new W;for(let n of r)e.append(n);return new W(Uint8Array.from([t]),Oo(e),e)}async function Mu(r="P-256"){let t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}async function Ru(r,t){let e=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]),n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Nu(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var Im=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Cm=Uint8Array.from([6,5,43,129,4,0,34]),Pm=Uint8Array.from([6,5,43,129,4,0,35]),Tm={ext:!0,kty:"EC",crv:"P-256"},Lm={ext:!0,kty:"EC",crv:"P-384"},Dm={ext:!0,kty:"EC",crv:"P-521"},xa=32,Ea=48,va=66;function Sa(r){let t=pe(r);return Ou(t)}function Ou(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===xa*2+1)return n=O(t.subarray(e,e+xa),"base64url"),o=O(t.subarray(e+xa),"base64url"),new We({...Tm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ea*2+1)return n=O(t.subarray(e,e+Ea),"base64url"),o=O(t.subarray(e+Ea),"base64url"),new We({...Lm,key_ops:["verify"],x:n,y:o});if(t.byteLength===va*2+1)return n=O(t.subarray(e,e+va),"base64url"),o=O(t.subarray(e+va),"base64url"),new We({...Dm,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Bu(r){return Qt([Tt(Uint8Array.from([1])),ku(P(r.d??"","base64url")),Qt([Uu(r.crv)],160),Qt([An(new W(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function Fu(r){return Qt([Tt(Uint8Array.from([1])),Qt([Uu(r.crv)],160),Qt([An(new W(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function Uu(r){if(r==="P-256")return Im;if(r==="P-384")return Cm;if(r==="P-521")return Pm;throw new R(`Invalid curve ${r}`)}async function Ku(r="P-256"){let t=await Mu(r);return new Bo(t.privateKey)}var We=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Fu(this.jwk)),this._raw}toMultihash(){return Yt.digest($t(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}async verify(t,e){return Nu(this.jwk,e,t)}},Bo=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new We({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Bu(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}async sign(t){return Ru(this.jwk,t)}};var je=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function km(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Fo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Xe(r,...t){if(!km(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 qu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Fo(r.outputLen),Fo(r.blockLen)}function Fr(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 zu(r,t){Xe(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function me(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Uo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Jt(r,t){return r<<32-t|r>>>t}function Vu(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function _n(r){return typeof r=="string"&&(r=Vu(r)),Xe(r),r}function Aa(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Xe(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Br=class{};function _a(r){let t=n=>r().update(_n(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Ur(r=32){if(je&&typeof je.getRandomValues=="function")return je.getRandomValues(new Uint8Array(r));if(je&&typeof je.randomBytes=="function")return Uint8Array.from(je.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Mm(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 Hu(r,t,e){return r&t^~r&e}function $u(r,t,e){return r&t^r&e^t&e}var In=class extends Br{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Uo(this.buffer)}update(t){Fr(this),t=_n(t),Xe(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Uo(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){Fr(this),zu(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,me(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Mm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Uo(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.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ge=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ko=BigInt(4294967295),Gu=BigInt(32);function Rm(r,t=!1){return t?{h:Number(r&Ko),l:Number(r>>Gu&Ko)}:{h:Number(r>>Gu&Ko)|0,l:Number(r&Ko)|0}}function Wu(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Rm(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Ia=(r,t,e)=>r>>>e,Ca=(r,t,e)=>r<<32-e|t>>>e,Ze=(r,t,e)=>r>>>e|t<<32-e,Ye=(r,t,e)=>r<<32-e|t>>>e,Cn=(r,t,e)=>r<<64-e|t>>>e-32,Pn=(r,t,e)=>r>>>e-32|t<<64-e;function ie(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var ju=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Xu=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Zu=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Yu=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Qu=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Ju=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Om=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ke=new Uint32Array(64),qo=class extends In{constructor(t=32){super(64,t,8,!1),this.A=ge[0]|0,this.B=ge[1]|0,this.C=ge[2]|0,this.D=ge[3]|0,this.E=ge[4]|0,this.F=ge[5]|0,this.G=ge[6]|0,this.H=ge[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)ke[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=ke[f-15],m=ke[f-2],p=Jt(d,7)^Jt(d,18)^d>>>3,g=Jt(m,17)^Jt(m,19)^m>>>10;ke[f]=g+ke[f-7]+p+ke[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=Jt(a,6)^Jt(a,11)^Jt(a,25),m=u+d+Hu(a,c,l)+Om[f]+ke[f]|0,g=(Jt(n,2)^Jt(n,13)^Jt(n,22))+$u(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(){me(ke)}destroy(){this.set(0,0,0,0,0,0,0,0),me(this.buffer)}};var tf=Wu(["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))),Bm=tf[0],Fm=tf[1],Me=new Uint32Array(80),Re=new Uint32Array(80),Pa=class extends In{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}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)Me[y]=t.getUint32(e),Re[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let E=Me[y-15]|0,_=Re[y-15]|0,k=Ze(E,_,1)^Ze(E,_,8)^Ia(E,_,7),I=Ye(E,_,1)^Ye(E,_,8)^Ca(E,_,7),T=Me[y-2]|0,D=Re[y-2]|0,et=Ze(T,D,19)^Cn(T,D,61)^Ia(T,D,6),X=Ye(T,D,19)^Pn(T,D,61)^Ca(T,D,6),F=Zu(I,X,Re[y-7],Re[y-16]),pt=Yu(F,k,et,Me[y-7],Me[y-16]);Me[y]=pt|0,Re[y]=F|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=Ze(f,d,14)^Ze(f,d,18)^Cn(f,d,41),_=Ye(f,d,14)^Ye(f,d,18)^Pn(f,d,41),k=f&m^~f&g,I=d&p^~d&h,T=Qu(x,_,I,Fm[y],Re[y]),D=Ju(T,w,E,k,Bm[y],Me[y]),et=T|0,X=Ze(n,o,28)^Cn(n,o,34)^Cn(n,o,39),F=Ye(n,o,28)^Pn(n,o,34)^Pn(n,o,39),pt=n&s^n&a^s&a,A=o&i^o&c^i&c;w=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=ie(l|0,u|0,D|0,et|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=ju(et,F,A);n=Xu(L,D,X,pt),o=L|0}({h:n,l:o}=ie(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ie(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ie(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ie(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ie(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:p}=ie(this.Fh|0,this.Fl|0,m|0,p|0),{h:g,l:h}=ie(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=ie(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(){me(Me,Re)}destroy(){me(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var zo=_a(()=>new qo);var ef=_a(()=>new Pa);var ka=BigInt(0),Da=BigInt(1);function Qe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ma(r){if(!Qe(r))throw new Error("Uint8Array expected")}function ae(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Tn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function of(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ka:BigInt("0x"+r)}var sf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Um=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Ne(r){if(Ma(r),sf)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Um[r[e]];return t}var ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function rf(r){if(r>=ye._0&&r<=ye._9)return r-ye._0;if(r>=ye.A&&r<=ye.F)return r-(ye.A-10);if(r>=ye.a&&r<=ye.f)return r-(ye.a-10)}function Ln(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(sf)return Uint8Array.fromHex(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=rf(r.charCodeAt(s)),a=rf(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 we(r){return of(Ne(r))}function Je(r){return Ma(r),of(Ne(Uint8Array.from(r).reverse()))}function tr(r,t){return Ln(r.toString(16).padStart(t*2,"0"))}function Kr(r,t){return tr(r,t).reverse()}function st(r,t,e){let n;if(typeof t=="string")try{n=Ln(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Qe(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 Oe(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ma(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 Ta=r=>typeof r=="bigint"&&ka<=r;function Vo(r,t,e){return Ta(r)&&Ta(t)&&Ta(e)&&t<=r&&r<e}function zt(r,t,e,n){if(!Vo(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function af(r){let t;for(t=0;r>ka;r>>=Da,t+=1);return t}var er=r=>(Da<<BigInt(r))-Da,La=r=>new Uint8Array(r),nf=r=>Uint8Array.from(r);function cf(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=La(r),o=La(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=La(0))=>{o=a(nf([0]),f),n=a(),f.length!==0&&(o=a(nf([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 Oe(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Km={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"||Qe(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 be(r,t,e={}){let n=(o,s,i)=>{let a=Km[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}function qr(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 Lt=BigInt(0),mt=BigInt(1),rr=BigInt(2),qm=BigInt(3),Ra=BigInt(4),lf=BigInt(5),uf=BigInt(8),zm=BigInt(9),Vm=BigInt(16);function tt(r,t){let e=r%t;return e>=Lt?e:t+e}function rt(r,t,e){let n=r;for(;t-- >Lt;)n*=n,n%=e;return n}function Ho(r,t){if(r===Lt)throw new Error("invert: expected non-zero number");if(t<=Lt)throw new Error("invert: expected positive modulus, got "+t);let e=tt(r,t),n=t,o=Lt,s=mt,i=mt,a=Lt;for(;e!==Lt;){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!==mt)throw new Error("invert: does not exist");return tt(o,t)}function Hm(r){let t=r-mt,e=0;for(;t%rr===Lt;)t/=rr,e++;let n=rr,o=xe(r);for(;n<r&&ff(o,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1){let i=(r+mt)/Ra;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=(t+mt)/rr;return function(a,c){if(!ff(a,c))throw new Error("Cannot find square root");let l=e,u=a.pow(a.mul(a.ONE,n),t),f=a.pow(c,s),d=a.pow(c,t);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,mt<<BigInt(l-m-1));u=a.sqr(p),f=a.mul(f,p),d=a.mul(d,u),l=m}return f}}function $m(r){return r%Ra===qm?function(e,n){let o=(r+mt)/Ra,s=e.pow(n,o);if(!e.eql(e.sqr(s),n))throw new Error("Cannot find square root");return s}:r%uf===lf?function(e,n){let o=e.mul(n,rr),s=(r-lf)/uf,i=e.pow(o,s),a=e.mul(n,i),c=e.mul(e.mul(a,rr),i),l=e.mul(a,e.sub(c,e.ONE));if(!e.eql(e.sqr(l),n))throw new Error("Cannot find square root");return l}:(r%Vm,Hm(r))}var df=(r,t)=>(tt(r,t)&mt)===mt,Gm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Na(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Gm.reduce((n,o)=>(n[o]="function",n),t);return be(r,e)}function Wm(r,t,e){if(e<Lt)throw new Error("invalid exponent, negatives unsupported");if(e===Lt)return r.ONE;if(e===mt)return t;let n=r.ONE,o=t;for(;e>Lt;)e&mt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=mt;return n}function zr(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function jm(r,t){let e=(r.ORDER-mt)/rr,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("Cannot find square root: probably non-prime P");return o?1:s?0:-1}function ff(r,t){let e=jm(r,t);return e===0||e===1}function Oa(r,t){t!==void 0&&Fo(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function xe(r,t,e=!1,n={}){if(r<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Oa(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:er(o),ZERO:Lt,ONE:mt,create:c=>tt(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Lt<=c&&c<r},is0:c=>c===Lt,isOdd:c=>(c&mt)===mt,neg:c=>tt(-c,r),eql:(c,l)=>c===l,sqr:c=>tt(c*c,r),add:(c,l)=>tt(c+l,r),sub:(c,l)=>tt(c-l,r),mul:(c,l)=>tt(c*l,r),pow:(c,l)=>Wm(a,c,l),div:(c,l)=>tt(c*Ho(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Ho(c,r),sqrt:n.sqrt||(c=>(i||(i=$m(r)),i(a,c))),toBytes:c=>e?Kr(c,s):tr(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Je(c):we(c)},invertBatch:c=>zr(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function hf(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 Ba(r){let t=hf(r);return t+Math.ceil(t/2)}function pf(r,t,e=!1){let n=r.length,o=hf(t),s=Ba(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Je(r):we(r),a=tt(i,t-mt)+mt;return e?Kr(a,o):tr(a,o)}var mf=BigInt(0),za=BigInt(1);function Fa(r,t){let e=t.negate();return r?e:t}function yf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ua(r,t){yf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=er(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function gf(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=za);let l=t*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,m=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:m,offsetF:l}}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 Zm(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 Ka=new WeakMap,wf=new WeakMap;function qa(r){return wf.get(r)||1}function $o(r,t){return{constTimeNegate:Fa,hasPrecomputes(e){return qa(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>mf;)n&za&&(o=o.add(s)),s=s.double(),n>>=za;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Ua(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 s=r.ZERO,i=r.BASE,a=Ua(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:d,isNegF:m,offsetF:p}=gf(o,c,a);o=l,f?i=i.add(Fa(m,n[p])):s=s.add(Fa(d,n[u]))}return{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=Ua(e,t);for(let a=0;a<i.windows&&o!==mf;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=gf(o,a,i);if(o=c,!u){let d=n[l];s=s.add(f?d.negate():d)}}return s},getPrecomputes(e,n,o){let s=Ka.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Ka.set(n,o(s))),s},wNAFCached(e,n,o){let s=qa(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=qa(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){yf(n,t),wf.set(e,n),Ka.delete(e)}}}function Go(r,t,e,n){if(Xm(e,r),Zm(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=af(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=er(i),c=new Array(Number(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)&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 Dn(r){return Na(r.Fp),be(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Oa(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ce=BigInt(0),Dt=BigInt(1),bf=BigInt(2),Ym=BigInt(8),Qm={zip215:!0};function Jm(r){let t=Dn(r);return be(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function xf(r){let t=Jm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=bf<<BigInt(a*8)-Dt,u=e.create,f=xe(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:ce}}}),m=t.adjustScalarBytes||(v=>v),p=t.domain||((v,b,S)=>{if(ae("phflag",S),b.length||S)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b,S=!1){let C=S?Dt:ce;zt("coordinate "+v,b,C,l)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let w=qr((v,b)=>{let{ex:S,ey:C,ez:N}=v,B=v.is0();b==null&&(b=B?Ym:e.inv(N));let U=u(S*b),K=u(C*b),G=u(N*b);if(B)return{x:ce,y:Dt};if(G!==Dt)throw new Error("invZ was invalid");return{x:U,y:K}}),x=qr(v=>{let{a:b,d:S}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:C,ey:N,ez:B,et:U}=v,K=u(C*C),G=u(N*N),Y=u(B*B),dt=u(Y*Y),lt=u(K*b),wt=u(Y*u(lt+G)),Ot=u(dt+u(S*u(K*G)));if(wt!==Ot)throw new Error("bad point: equation left != right (1)");let gt=u(C*N),Et=u(B*U);if(gt!==Et)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(b,S,C,N){g("x",b),g("y",S),g("z",C,!0),g("t",N),this.ex=b,this.ey=S,this.ez=C,this.et=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,Dt,u(S*C))}static normalizeZ(b){let S=zr(e,b.map(C=>C.ez));return b.map((C,N)=>C.toAffine(S[N])).map(y.fromAffine)}static msm(b,S){return Go(y,f,b,S)}_setWindowSize(b){k.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:S,ey:C,ez:N}=this,{ex:B,ey:U,ez:K}=b,G=u(S*K),Y=u(B*N),dt=u(C*K),lt=u(U*N);return G===Y&&dt===lt}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,B=u(S*S),U=u(C*C),K=u(bf*u(N*N)),G=u(b*B),Y=S+C,dt=u(u(Y*Y)-B-U),lt=G+U,wt=lt-K,Ot=G-U,gt=u(dt*wt),Et=u(lt*Ot),Ut=u(dt*Ot),jt=u(wt*lt);return new y(gt,Et,jt,Ut)}add(b){h(b);let{a:S,d:C}=t,{ex:N,ey:B,ez:U,et:K}=this,{ex:G,ey:Y,ez:dt,et:lt}=b,wt=u(N*G),Ot=u(B*Y),gt=u(K*C*lt),Et=u(U*dt),Ut=u((N+B)*(G+Y)-wt-Ot),jt=Et-gt,dn=Et+gt,ou=u(Ot-S*wt),sp=u(Ut*jt),ip=u(dn*ou),ap=u(Ut*ou),cp=u(jt*dn);return new y(sp,ip,cp,ap)}subtract(b){return this.add(b.negate())}wNAF(b){return k.wNAFCached(this,b,y.normalizeZ)}multiply(b){let S=b;zt("scalar",S,Dt,n);let{p:C,f:N}=this.wNAF(S);return y.normalizeZ([C,N])[0]}multiplyUnsafe(b,S=y.ZERO){let C=b;return zt("scalar",C,ce,n),C===ce?_:this.is0()||C===Dt?this:k.wNAFCachedUnsafe(this,C,y.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return k.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=t;return b===Dt?this:this.multiplyUnsafe(b)}static fromHex(b,S=!1){let{d:C,a:N}=t,B=e.BYTES;b=st("pointHex",b,B),ae("zip215",S);let U=b.slice(),K=b[B-1];U[B-1]=K&-129;let G=Je(U),Y=S?l:e.ORDER;zt("pointHex.y",G,ce,Y);let dt=u(G*G),lt=u(dt-Dt),wt=u(C*dt-N),{isValid:Ot,value:gt}=d(lt,wt);if(!Ot)throw new Error("Point.fromHex: invalid y coordinate");let Et=(gt&Dt)===Dt,Ut=(K&128)!==0;if(!S&&gt===ce&&Ut)throw new Error("Point.fromHex: x=0 and x_0=1");return Ut!==Et&&(gt=u(-gt)),y.fromAffine({x:gt,y:G})}static fromPrivateKey(b){let{scalar:S}=D(b);return E.multiply(S)}toRawBytes(){let{x:b,y:S}=this.toAffine(),C=Kr(S,e.BYTES);return C[C.length-1]|=b&Dt?128:0,C}toHex(){return Ne(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,Dt,u(t.Gx*t.Gy)),y.ZERO=new y(ce,Dt,Dt,ce);let{BASE:E,ZERO:_}=y,k=$o(y,a*8);function I(v){return tt(v,n)}function T(v){return I(Je(v))}function D(v){let b=e.BYTES;v=st("private key",v,b);let S=st("hashed private key",s(v),2*b),C=m(S.slice(0,b)),N=S.slice(b,2*b),B=T(C);return{head:C,prefix:N,scalar:B}}function et(v){let{head:b,prefix:S,scalar:C}=D(v),N=E.multiply(C),B=N.toRawBytes();return{head:b,prefix:S,scalar:C,point:N,pointBytes:B}}function X(v){return et(v).pointBytes}function F(v=Uint8Array.of(),...b){let S=Oe(...b);return T(s(p(S,st("context",v),!!o)))}function pt(v,b,S={}){v=st("message",v),o&&(v=o(v));let{prefix:C,scalar:N,pointBytes:B}=et(b),U=F(S.context,C,v),K=E.multiply(U).toRawBytes(),G=F(S.context,K,B,v),Y=I(U+G*N);zt("signature.s",Y,ce,n);let dt=Oe(K,Kr(Y,e.BYTES));return st("result",dt,e.BYTES*2)}let A=Qm;function L(v,b,S,C=A){let{context:N,zip215:B}=C,U=e.BYTES;v=st("signature",v,2*U),b=st("message",b),S=st("publicKey",S,U),B!==void 0&&ae("zip215",B),o&&(b=o(b));let K=Je(v.slice(U,2*U)),G,Y,dt;try{G=y.fromHex(S,B),Y=y.fromHex(v.slice(0,U),B),dt=E.multiplyUnsafe(K)}catch{return!1}if(!B&&G.isSmallOrder())return!1;let lt=F(N,Y.toRawBytes(),G.toRawBytes(),b);return Y.add(G.multiplyUnsafe(lt)).subtract(dt).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:X,sign:pt,verify:L,ExtendedPoint:y,utils:{getExtendedPublicKey:et,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,b=y.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var Va=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ef=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),c1=BigInt(0),tg=BigInt(1),vf=BigInt(2),l1=BigInt(3),eg=BigInt(5),rg=BigInt(8);function ng(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Va,a=r*r%s*r%s,c=rt(a,vf,s)*a%s,l=rt(c,tg,s)*r%s,u=rt(l,eg,s)*l%s,f=rt(u,t,s)*u%s,d=rt(f,e,s)*f%s,m=rt(d,n,s)*d%s,p=rt(m,o,s)*m%s,g=rt(p,o,s)*m%s,h=rt(g,t,s)*u%s;return{pow_p_5_8:rt(h,vf,s)*r%s,b2:a}}function og(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function sg(r,t){let e=Va,n=tt(t*t*t,e),o=tt(n*n*t,e),s=ng(r*o).pow_p_5_8,i=tt(r*n*s,e),a=tt(t*i*i,e),c=i,l=tt(i*Ef,e),u=a===r,f=a===tt(-r,e),d=a===tt(-r*Ef,e);return u&&(i=c),(f||d)&&(i=l),df(i,e)&&(i=tt(-i,e)),{isValid:u||f,value:i}}var Sf=xe(Va,void 0,!0),ig={a:Sf.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Sf,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:rg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ef,randomBytes:Ur,adjustScalarBytes:og,uvRatio:sg},kn=xf(ig);var Wo=32,jo=64,Ha=32;function Af(){let r=kn.utils.randomPrivateKey(),t=kn.getPublicKey(r);return{privateKey:ag(r,t),publicKey:t}}function _f(r,t){let e=r.subarray(0,Ha);return kn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function If(r,t,e){return kn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function ag(r,t){let e=new Uint8Array(jo);for(let n=0;n<Ha;n++)e[n]=r[n],e[Ha+n]=t[n];return e}var Mn=class{type="Ed25519";raw;constructor(t){this.raw=Zo(t,Wo)}toMultihash(){return Yt.digest($t(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}verify(t,e){return If(this.raw,e,t)}},Xo=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Zo(t,jo),this.publicKey=new Mn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}sign(t){return _f(this.raw,t)}};function $a(r){return r=Zo(r,Wo),new Mn(r)}async function Pf(){let{privateKey:r,publicKey:t}=Af();return new Xo(r,t)}function Zo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var cg=Math.pow(2,7),lg=Math.pow(2,14),ug=Math.pow(2,21),Ga=Math.pow(2,28),Wa=Math.pow(2,35),ja=Math.pow(2,42),Xa=Math.pow(2,49),Z=128,St=127;function ht(r){if(r<cg)return 1;if(r<lg)return 2;if(r<ug)return 3;if(r<Ga)return 4;if(r<Wa)return 5;if(r<ja)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 Za(r,t,e=0){switch(ht(r)){case 8:t[e++]=r&255|Z,r/=128;case 7:t[e++]=r&255|Z,r/=128;case 6:t[e++]=r&255|Z,r/=128;case 5:t[e++]=r&255|Z,r/=128;case 4:t[e++]=r&255|Z,r>>>=7;case 3:t[e++]=r&255|Z,r>>>=7;case 2:t[e++]=r&255|Z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function fg(r,t,e=0){switch(ht(r)){case 8:t.set(e++,r&255|Z),r/=128;case 7:t.set(e++,r&255|Z),r/=128;case 6:t.set(e++,r&255|Z),r/=128;case 5:t.set(e++,r&255|Z),r/=128;case 4:t.set(e++,r&255|Z),r>>>=7;case 3:t.set(e++,r&255|Z),r>>>=7;case 2:t.set(e++,r&255|Z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ya(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)*Ga,e<Z)||(e=r[t+5],n+=(e&St)*Wa,e<Z)||(e=r[t+6],n+=(e&St)*ja,e<Z)||(e=r[t+7],n+=(e&St)*Xa,e<Z))return n;throw new RangeError("Could not decode varint")}function dg(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)*Ga,e<Z)||(e=r.get(t+5),n+=(e&St)*Wa,e<Z)||(e=r.get(t+6),n+=(e&St)*ja,e<Z)||(e=r.get(t+7),n+=(e&St)*Xa,e<Z))return n;throw new RangeError("Could not decode varint")}function At(r,t,e=0){return t==null&&(t=vt(ht(r))),t instanceof Uint8Array?Za(r,t,e):fg(r,t,e)}function te(r,t=0){return r instanceof Uint8Array?Ya(r,t):dg(r,t)}var Qa=new Float32Array([-0]),Be=new Uint8Array(Qa.buffer);function Tf(r,t,e){Qa[0]=r,t[e]=Be[0],t[e+1]=Be[1],t[e+2]=Be[2],t[e+3]=Be[3]}function Lf(r,t){return Be[0]=r[t],Be[1]=r[t+1],Be[2]=r[t+2],Be[3]=r[t+3],Qa[0]}var Ja=new Float64Array([-0]),_t=new Uint8Array(Ja.buffer);function Df(r,t,e){Ja[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 kf(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],Ja[0]}var hg=BigInt(Number.MAX_SAFE_INTEGER),pg=BigInt(Number.MIN_SAFE_INTEGER),Vt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return or;if(t<hg&&t>pg)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>Mf&&(o=0n,++n>Mf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return or;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):or}},or=new Vt(0,0);or.toBigInt=function(){return 0n};or.zzEncode=or.zzDecode=function(){return this};or.length=function(){return 1};var Mf=4294967296n;function Rf(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 Nf(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 tc(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 ee(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Yo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ec=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,ee(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 ee(this,4);return Yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ee(this,4);return Yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ee(this,4);let t=Lf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ee(this,4);let t=kf(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 ee(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Nf(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ee(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ee(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Vt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ee(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 ee(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 ee(this,8);let t=Yo(this.buf,this.pos+=4),e=Yo(this.buf,this.pos+=4);return new Vt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ya(this.buf,this.pos);return this.pos+=ht(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function rc(r){return new ec(r instanceof Uint8Array?r:r.subarray())}function kt(r,t,e){let n=rc(r);return t.decode(n,void 0,e)}function nc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return vt(i);o+i>t&&(n=vt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var sr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function oc(){}var ic=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},mg=nc();function gg(r){return globalThis.Buffer!=null?vt(r):mg(r)}var Nn=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(oc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new sr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ac((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(Qo,10,Vt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Vt.fromBigInt(t);return this._push(Qo,e.length(),e)}uint64Number(t){return this._push(Za,ht(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Vt.fromBigInt(t).zzEncode();return this._push(Qo,e.length(),e)}sint64Number(t){let e=Vt.fromNumber(t).zzEncode();return this._push(Qo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(sc,1,t?1:0)}fixed32(t){return this._push(Rn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Vt.fromBigInt(t);return this._push(Rn,4,e.lo)._push(Rn,4,e.hi)}fixed64Number(t){let e=Vt.fromNumber(t);return this._push(Rn,4,e.lo)._push(Rn,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(Tf,4,t)}double(t){return this._push(Df,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(sc,1,0):this.uint32(e)._push(wg,e,t)}string(t){let e=Rf(t);return e!==0?this.uint32(e)._push(tc,e,t):this._push(sc,1,0)}fork(){return this.states=new ic(this),this.head=this.tail=new sr(oc,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 sr(oc,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=gg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function sc(r,t,e){t[e]=r&255}function yg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ac=class extends sr{next;constructor(t,e){super(yg,t,e),this.next=void 0}};function Qo(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 Rn(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 wg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Nn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(bg,t,r),this},Nn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(xg,t,r),this});function bg(r,t,e){t.set(r,e)}function xg(r,t,e){r.length<40?tc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function cc(){return new Nn}function Mt(r,t){let e=cc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Vr;(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"})(Vr||(Vr={}));function Jo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function lc(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 Jo("enum",Vr.VARINT,e,n)}function Rt(r,t){return Jo("message",Vr.LENGTH_DELIMITED,r,t)}var ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},On=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var uc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(uc||(uc={}));(function(r){r.codec=()=>lc(uc)})(ut||(ut={}));var le;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(le||(le={}));var fc;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(fc||(fc={}));function Hr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Ur(r)}var Bn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Fn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ts=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ff={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ts("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 Fe=Ff;var Kn={};Bt(Kn,{MAX_RSA_KEY_SIZE:()=>dc,generateRSAKeyPair:()=>Ec,jwkToJWKKeyPair:()=>zf,jwkToPkcs1:()=>Ag,jwkToPkix:()=>gc,jwkToRSAPrivateKey:()=>xc,pkcs1MessageToJwk:()=>pc,pkcs1MessageToRSAPrivateKey:()=>yc,pkcs1ToJwk:()=>Sg,pkcs1ToRSAPrivateKey:()=>qf,pkixMessageToJwk:()=>mc,pkixMessageToRSAPublicKey:()=>bc,pkixToJwk:()=>_g,pkixToRSAPublicKey:()=>wc});var es=zo;var $r=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Kn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ot.createV1(114,this._multihash)}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}verify(t,e){return Kf(this.jwk,e,t)}},Un=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Kn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}sign(t){return Uf(this.jwk,t)}};var dc=8192,hc=18,Eg=1062,vg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Sg(r){let t=pe(r);return pc(t)}function pc(r){return{n:O(r[1],"base64url"),e:O(r[2],"base64url"),d:O(r[3],"base64url"),p:O(r[4],"base64url"),q:O(r[5],"base64url"),dp:O(r[6],"base64url"),dq:O(r[7],"base64url"),qi:O(r[8],"base64url"),kty:"RSA"}}function Ag(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 Qt([Tt(Uint8Array.from([0])),Tt(P(r.n,"base64url")),Tt(P(r.e,"base64url")),Tt(P(r.d,"base64url")),Tt(P(r.p,"base64url")),Tt(P(r.q,"base64url")),Tt(P(r.dp,"base64url")),Tt(P(r.dq,"base64url")),Tt(P(r.qi,"base64url"))]).subarray()}function _g(r){let t=pe(r,{offset:0});return mc(t)}function mc(r){let t=pe(r[1],{offset:0});return{kty:"RSA",n:O(t[0],"base64url"),e:O(t[1],"base64url")}}function gc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Qt([vg,An(Qt([Tt(P(r.n,"base64url")),Tt(P(r.e,"base64url"))]))]).subarray()}function qf(r){let t=pe(r);return yc(t)}function yc(r){let t=pc(r);return xc(t)}function wc(r,t){if(r.byteLength>=Eg)throw new Cr("Key size is too large");let e=pe(r,{offset:0});return bc(e,r,t)}function bc(r,t,e){let n=mc(r);if(e==null){let o=es(le.encode({Type:ut.RSA,Data:t}));e=Zt(hc,o)}return new $r(n,e)}function xc(r){if(Hf(r)>dc)throw new R("Key size is too large");let t=zf(r),e=es(le.encode({Type:ut.RSA,Data:gc(t.publicKey)})),n=Zt(hc,e);return new Un(t.privateKey,new $r(t.publicKey,n))}async function Ec(r){if(r>dc)throw new R("Key size is too large");let t=await Vf(r),e=es(le.encode({Type:ut.RSA,Data:gc(t.publicKey)})),n=Zt(hc,e);return new Un(t.privateKey,new $r(t.publicKey,n))}function zf(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Vf(r){let t=await Fe.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 Ig(t);return{privateKey:e[0],publicKey:e[1]}}async function Uf(r,t){let e=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Kf(r,t,e){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Ig(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)])}function Hf(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return P(r.n,"base64url").length*8}var rs=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,qu(t);let n=_n(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),me(s)}update(t){return Fr(this),this.iHash.update(t),this}digestInto(t){Fr(this),Xe(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}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vc=(r,t,e)=>new rs(r,t).update(e).digest();vc.create=(r,t)=>new rs(r,t);function $f(r){r.lowS!==void 0&&ae("lowS",r.lowS),r.prehash!==void 0&&ae("prehash",r.prehash)}function Cg(r){let t=Dn(r);be(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 Sc=class extends Error{constructor(t=""){super(t)}},Ee={Err:Sc,_tlv:{encode:(r,t)=>{let{Err:e}=Ee;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=Tn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Tn(o.length/2|128):"";return Tn(r)+s+o+t},decode(r,t){let{Err:e}=Ee,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}=Ee;if(r<ve)throw new t("integer: negative integers are not allowed");let e=Tn(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}=Ee;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 we(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ee,o=st("signature",r),{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}=Ee,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},ve=BigInt(0),yt=BigInt(1),F2=BigInt(2),Gf=BigInt(3),U2=BigInt(4);function Pg(r){let t=Cg(r),{Fp:e}=t,n=xe(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let x=h.toAffine();return Oe(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 Vo(g,yt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=t;if(h&&typeof g!="bigint"){if(Qe(g)&&(g=Ne(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:we(st("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=tt(E,y)),zt("private key",E,yt,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=qr((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),k=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:k}}),f=qr(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(h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w)||e.is0(w))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");this.px=h,this.py=w,this.pz=x,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=zr(e,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(st("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return Go(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:k}=h,I=e.eql(e.mul(w,k),e.mul(E,y)),T=e.eql(e.mul(x,k),e.mul(_,y));return I&&T}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,x=e.mul(w,Gf),{px:y,py:E,pz:_}=this,k=e.ZERO,I=e.ZERO,T=e.ZERO,D=e.mul(y,y),et=e.mul(E,E),X=e.mul(_,_),F=e.mul(y,E);return F=e.add(F,F),T=e.mul(y,_),T=e.add(T,T),k=e.mul(h,T),I=e.mul(x,X),I=e.add(k,I),k=e.sub(et,I),I=e.add(et,I),I=e.mul(k,I),k=e.mul(F,k),T=e.mul(x,T),X=e.mul(h,X),F=e.sub(D,X),F=e.mul(h,F),F=e.add(F,T),T=e.add(D,D),D=e.add(T,D),D=e.add(D,X),D=e.mul(D,F),I=e.add(I,D),X=e.mul(E,_),X=e.add(X,X),D=e.mul(X,F),k=e.sub(k,D),T=e.mul(X,et),T=e.add(T,T),T=e.add(T,T),new d(k,I,T)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:k}=h,I=e.ZERO,T=e.ZERO,D=e.ZERO,et=t.a,X=e.mul(t.b,Gf),F=e.mul(w,E),pt=e.mul(x,_),A=e.mul(y,k),L=e.add(w,x),M=e.add(E,_);L=e.mul(L,M),M=e.add(F,pt),L=e.sub(L,M),M=e.add(w,y);let v=e.add(E,k);return M=e.mul(M,v),v=e.add(F,A),M=e.sub(M,v),v=e.add(x,y),I=e.add(_,k),v=e.mul(v,I),I=e.add(pt,A),v=e.sub(v,I),D=e.mul(et,M),I=e.mul(X,A),D=e.add(I,D),I=e.sub(pt,D),D=e.add(pt,D),T=e.mul(I,D),pt=e.add(F,F),pt=e.add(pt,F),A=e.mul(et,A),M=e.mul(X,M),pt=e.add(pt,A),A=e.sub(F,A),A=e.mul(et,A),M=e.add(M,A),F=e.mul(pt,M),T=e.add(T,F),F=e.mul(v,M),I=e.mul(L,I),I=e.sub(I,F),F=e.mul(L,pt),D=e.mul(v,D),D=e.add(D,F),new d(I,T,D)}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;zt("scalar",h,ve,x);let y=d.ZERO;if(h===ve)return y;if(this.is0()||h===yt)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:k,k2:I}=w.splitScalar(h),T=y,D=y,et=this;for(;_>ve||I>ve;)_&yt&&(T=T.add(et)),I&yt&&(D=D.add(et)),et=et.double(),_>>=yt,I>>=yt;return E&&(T=T.negate()),k&&(D=D.negate()),D=new d(e.mul(D.px,w.beta),D.py,D.pz),T.add(D)}multiply(h){let{endo:w,n:x}=t;zt("scalar",h,yt,x);let y,E;if(w){let{k1neg:_,k1:k,k2neg:I,k2:T}=w.splitScalar(h),{p:D,f:et}=this.wNAF(k),{p:X,f:F}=this.wNAF(T);D=p.constTimeNegate(_,D),X=p.constTimeNegate(I,X),X=new d(e.mul(X.px,w.beta),X.py,X.pz),y=D.add(X),E=et.add(F)}else{let{p:_,f:k}=this.wNAF(h);y=_,E=k}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(k,I)=>I===ve||I===yt||!k.equals(y)?k.multiplyUnsafe(I):k.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===yt)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===yt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return ae("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return ae("isCompressed",h),Ne(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=$o(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Tg(r){let t=Dn(r);return be(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Wf(r){let t=Tg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(A){return tt(A,n)}function a(A){return Ho(A,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Pg({...t,toBytes(A,L,M){let v=L.toAffine(),b=e.toBytes(v.x),S=Oe;return ae("isCompressed",M),M?S(Uint8Array.from([L.hasEvenY()?2:3]),b):S(Uint8Array.from([4]),b,e.toBytes(v.y))},fromBytes(A){let L=A.length,M=A[0],v=A.subarray(1);if(L===o&&(M===2||M===3)){let b=we(v);if(!Vo(b,yt,e.ORDER))throw new Error("Point is not on curve");let S=u(b),C;try{C=e.sqrt(S)}catch(U){let K=U instanceof Error?": "+U.message:"";throw new Error("Point is not on curve"+K)}let N=(C&yt)===yt;return(M&1)===1!==N&&(C=e.neg(C)),{x:b,y:C}}else if(L===s&&M===4){let b=e.fromBytes(v.subarray(0,e.BYTES)),S=e.fromBytes(v.subarray(e.BYTES,2*e.BYTES));return{x:b,y:S}}else{let b=o,S=s;throw new Error("invalid Point, expected length of "+b+", or uncompressed "+S+", got "+L)}}}),d=A=>Ne(tr(A,t.nByteLength));function m(A){let L=n>>yt;return A>L}function p(A){return m(A)?i(-A):A}let g=(A,L,M)=>we(A.slice(L,M));class h{constructor(L,M,v){zt("r",L,yt,n),zt("s",M,yt,n),this.r=L,this.s=M,v!=null&&(this.recovery=v),Object.freeze(this)}static fromCompact(L){let M=t.nByteLength;return L=st("compactSignature",L,M*2),new h(g(L,0,M),g(L,M,2*M))}static fromDER(L){let{r:M,s:v}=Ee.toSig(st("DER",L));return new h(M,v)}assertValidity(){}addRecoveryBit(L){return new h(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:v,recovery:b}=this,S=k(st("msgHash",L));if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");let C=b===2||b===3?M+t.n:M;if(C>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let N=(b&1)===0?"02":"03",B=c.fromHex(N+d(C)),U=a(C),K=i(-S*U),G=i(v*U),Y=c.BASE.multiplyAndAddUnsafe(B,K,G);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ln(this.toDERHex())}toDERHex(){return Ee.hexFromSig(this)}toCompactRawBytes(){return Ln(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=Ba(t.n);return pf(t.randomBytes(A),t.n)},precompute(A=8,L=c.BASE){return L._setWindowSize(A),L.multiply(BigInt(3)),L}};function x(A,L=!0){return c.fromPrivateKey(A).toRawBytes(L)}function y(A){let L=Qe(A),M=typeof A=="string",v=(L||M)&&A.length;return L?v===o||v===s:M?v===2*o||v===2*s:A instanceof c}function E(A,L,M=!0){if(y(A))throw new Error("first arg must be private key");if(!y(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(l(A)).toRawBytes(M)}let _=t.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");let L=we(A),M=A.length*8-t.nBitLength;return M>0?L>>BigInt(M):L},k=t.bits2int_modN||function(A){return i(_(A))},I=er(t.nBitLength);function T(A){return zt("num < 2^"+t.nBitLength,A,ve,I),tr(A,t.nByteLength)}function D(A,L,M=et){if(["recovered","canonical"].some(lt=>lt in M))throw new Error("sign() legacy options not supported");let{hash:v,randomBytes:b}=t,{lowS:S,prehash:C,extraEntropy:N}=M;S==null&&(S=!0),A=st("msgHash",A),$f(M),C&&(A=st("prehashed msgHash",v(A)));let B=k(A),U=l(L),K=[T(U),T(B)];if(N!=null&&N!==!1){let lt=N===!0?b(e.BYTES):N;K.push(st("extraEntropy",lt))}let G=Oe(...K),Y=B;function dt(lt){let wt=_(lt);if(!f(wt))return;let Ot=a(wt),gt=c.BASE.multiply(wt).toAffine(),Et=i(gt.x);if(Et===ve)return;let Ut=i(Ot*i(Y+Et*U));if(Ut===ve)return;let jt=(gt.x===Et?0:2)|Number(gt.y&yt),dn=Ut;return S&&m(Ut)&&(dn=p(Ut),jt^=1),new h(Et,dn,jt)}return{seed:G,k2sig:dt}}let et={lowS:t.lowS,prehash:!1},X={lowS:t.lowS,prehash:!1};function F(A,L,M=et){let{seed:v,k2sig:b}=D(A,L,M),S=t;return cf(S.hash.outputLen,S.nByteLength,S.hmac)(v,b)}c.BASE._setWindowSize(8);function pt(A,L,M,v=X){let b=A;L=st("msgHash",L),M=st("publicKey",M);let{lowS:S,prehash:C,format:N}=v;if($f(v),"strict"in v)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 B=typeof b=="string"||Qe(b),U=!B&&!N&&typeof b=="object"&&b!==null&&typeof b.r=="bigint"&&typeof b.s=="bigint";if(!B&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,G;try{if(U&&(K=new h(b.r,b.s)),B){try{N!=="compact"&&(K=h.fromDER(b))}catch(jt){if(!(jt instanceof Ee.Err))throw jt}!K&&N!=="der"&&(K=h.fromCompact(b))}G=c.fromHex(M)}catch{return!1}if(!K||S&&K.hasHighS())return!1;C&&(L=t.hash(L));let{r:Y,s:dt}=K,lt=k(L),wt=a(dt),Ot=i(lt*wt),gt=i(Y*wt),Et=c.BASE.multiplyAndAddUnsafe(G,Ot,gt)?.toAffine();return Et?i(Et.x)===Y:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:F,verify:pt,ProjectivePoint:c,Signature:h,utils:w}}function Lg(r){return{hash:r,hmac:(t,...e)=>vc(r,t,Aa(...e)),randomBytes:Ur}}function jf(r,t){let e=n=>Wf({...r,...Lg(n)});return{...e(t),create:e}}var Yf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Dg=BigInt(1),Ac=BigInt(2),Zf=(r,t)=>(r+t/Ac)/t;function kg(r){let t=Yf,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=rt(u,e,t)*u%t,d=rt(f,e,t)*u%t,m=rt(d,Ac,t)*l%t,p=rt(m,o,t)*m%t,g=rt(p,s,t)*p%t,h=rt(g,a,t)*g%t,w=rt(h,c,t)*h%t,x=rt(w,a,t)*g%t,y=rt(x,e,t)*u%t,E=rt(y,i,t)*p%t,_=rt(E,n,t)*l%t,k=rt(_,Ac,t);if(!_c.eql(_c.sqr(k),r))throw new Error("Cannot find square root");return k}var _c=xe(Yf,void 0,void 0,{sqrt:kg}),Gt=jf({a:BigInt(0),b:BigInt(7),Fp:_c,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=-Dg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Zf(s*r,t),c=Zf(-n*r,t),l=tt(r-a*e-c*o,t),u=tt(-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}}}},zo),j2=BigInt(0);var X2=Gt.ProjectivePoint;function Ic(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Qf(r,t){let e=Or.digest(t instanceof Uint8Array?t:t.subarray());if(Ic(e))return e.then(({digest:n})=>Gt.sign(n,r).toDERRawBytes()).catch(n=>{throw new Bn(String(n))});try{return Gt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Bn(String(n))}}function Jf(r,t,e){let n=Or.digest(e instanceof Uint8Array?e:e.subarray());if(Ic(n))return n.then(({digest:o})=>Gt.verify(t,o,r)).catch(o=>{throw new Fn(String(o))});try{return Gt.verify(t,n.digest,r)}catch(o){throw new Fn(String(o))}}var qn=class{type="secp256k1";raw;_key;constructor(t){this._key=rd(t),this.raw=td(this._key)}toMultihash(){return Yt.digest($t(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}verify(t,e){return Jf(this._key,e,t)}},ns=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=ed(t),this.publicKey=new qn(e??nd(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}sign(t){return Qf(this.raw,t)}};function Cc(r){return new qn(r)}async function od(){let r=Mg();return new ns(r)}function td(r){return Gt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ed(r){try{return Gt.getPublicKey(r,!0),r}catch(t){throw new pn(String(t))}}function rd(r){try{return Gt.ProjectivePoint.fromHex(r),r}catch(t){throw new Cr(String(t))}}function nd(r){try{return Gt.getPublicKey(r,!0)}catch(t){throw new pn(String(t))}}function Mg(){return Gt.utils.randomPrivateKey()}async function sd(r,t){if(r==="Ed25519")return Pf();if(r==="secp256k1")return od();if(r==="RSA")return Ec(Rg(t));if(r==="ECDSA")return Ku(Ng(t));throw new Le}function Gr(r,t){let{Type:e,Data:n}=le.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return wc(o,t);case ut.Ed25519:return $a(o);case ut.secp256k1:return Cc(o);case ut.ECDSA:return Sa(o);default:throw new Le}}function id(r){let{Type:t,Data:e}=le.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return $a(n);case ut.secp256k1:return Cc(n);case ut.ECDSA:return Sa(n);default:throw new Le}}function $t(r){return le.encode({Type:ut[r.type],Data:r.raw})}function Rg(r){return r==null?2048:parseInt(r,10)}function Ng(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new R("Unsupported curve, should be P-256, P-384 or P-521")}var ad=Symbol.for("nodejs.util.inspect.custom"),Og=114,zn=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()})`}[So]=!0;toString(){return this.string==null&&(this.string=q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(Og,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Q(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[ad](){return`PeerId(${this.toString()})`}},Vn=class extends zn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Hn=class extends zn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},$n=class extends zn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Bg=2336,Gn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Yt.digest(P(this.url))}[ad](){return`PeerId(${this.url})`}[So]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(Bg,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=O(t)),t.toString()===this.toString())}};var Fg=114,cd=2336;function ue(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=qt(q.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wn(ot.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 Wr(e)}function Pc(r){if(r.type==="Ed25519")return new Hn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new $n({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Vn({multihash:r.toCID().multihash,publicKey:r});throw new Le}function ld(r){return Pc(r.publicKey)}function Wr(r){if(Kg(r))return new Vn({multihash:r});if(Ug(r))try{let t=id(r);if(t.type==="Ed25519")return new Hn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new $n({multihash:r,publicKey:t})}catch{let e=O(r.digest);return new Gn(new URL(e))}throw new Co("Supplied PeerID Multihash is invalid")}function Wn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Fg&&r.code!==cd)throw new Io("Supplied PeerID CID is invalid");if(r.code===cd){let t=O(r.multihash.digest);return new Gn(new URL(t))}return Wr(r.multihash)}function Ug(r){return r.code===Yt.code}function Kg(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 Lc=hn(fd(),1);var Xn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Dc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},dd=r=>globalThis.DOMException===void 0?new Dc(r):new DOMException(r),hd=r=>{let t=r.reason===void 0?dd("This operation was aborted."):r.reason;return t instanceof Error?t:dd(t)};function Zn(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(hd(m)),a=()=>{f(hd(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Xn;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 kc(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 Yn=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=kc(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 Ue=class extends Lc.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:Yn,...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#E(){return this.#s<this.#u}#v(){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.#E){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=Zn(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 Xn&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},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 ss(r){let t=[Ht.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Mc=60;function is(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:Ht[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Ht[t.type],TTL:t.TTL??t.ttl??Mc,data:t.data instanceof Uint8Array?O(t.data):t.data}))}}var Vg=4;function Rc(r,t={}){let e=new Ue({concurrency:t.queryConcurrency??Vg});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ss(o.types).forEach(a=>{s.append("type",Ht[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=is(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 pd(){return[Rc("https://cloudflare-dns.com/dns-query"),Rc("https://dns.google/resolve")]}var yd=hn(gd(),1);var Nc=class{lru;constructor(t){this.lru=(0,yd.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 is({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:Ht[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??Mc)*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 wd(r){return new Nc(r)}var Hg=1e3,as=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=wd(t.cacheSize??Hg),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["."]=pd())}async query(t,e={}){let n=ss(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 Ht;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ht||(Ht={}));function bd(r={}){return new as(r)}var cs=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 xd=45,$g=15,jr=new cs;function ls(r){if(!(r.length>$g))return jr.new(r).parseWith(()=>jr.readIPv4Addr())}function us(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>xd))return jr.new(r).parseWith(()=>jr.readIPv6Addr())}function ar(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>xd)return;let e=jr.new(r).parseWith(()=>jr.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 Ed(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 vd(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 Oc(r){switch(r.length){case cr:return r.join(".");case lr:{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 Sd(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 Ad(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var cr=4,lr=16,Mv=parseInt("0xFFFF",16),Gg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Qn(r,t){t.length===lr&&r.length===cr&&Ed(t,0,11)&&(t=t.slice(12)),t.length===cr&&r.length===lr&&vd(r,Gg,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 _d(r,t){if(typeof t=="string"&&(t=ar(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 Bc(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=cr,o=ls(t);if(o==null&&(n=lr,o=us(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=Fc(s,8*n);return{network:Qn(o,i),mask:i}}function Fc(r,t){if(t!==8*cr&&t!==8*lr)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 Xr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Bc(t));else{let n=ar(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=ar(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Fc(o,8*n.length);this.network=Qn(n,this.mask)}}contains(t){return _d({network:this.network,mask:this.mask},t)}toString(){let t=Sd(this.mask),e=t!==-1?String(t):Ad(this.mask);return Oc(this.network)+"/"+e}};function re(r){return!!ls(r)}function Zr(r){return!!us(r)}function fs(r){return!!ar(r)}var Id=re,Wg=Zr,Uc=function(r){let t=0;if(r=r.toString().trim(),Id(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Wg(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Id(e[n]),i;s&&(i=Uc(e[n]),e[n]=O(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,O(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")},Cd=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Yr={},Kc={},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);Kc[t.code]=t,Yr[t.name]=t});function Zg(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function H(r){if(typeof r=="number"){if(Kc[r]!=null)return Kc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Yr[r]!=null)return Yr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Yg=H("ip4"),Qg=H("ip6"),Jg=H("ipcidr");function Hc(r,t){switch(H(r).code){case 4:case 41:return e0(t);case 42:return Vc(t);case 43:return O(t,"base10");case 6:case 273:case 33:case 132:return Ld(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Vc(t);case 421:return s0(t);case 444:return Td(t);case 445:return Td(t);case 466:return o0(t);case 481:return globalThis.encodeURIComponent(Vc(t));default:return O(t,"base16")}}function $c(r,t){switch(H(r).code){case 4:return Pd(t);case 41:return Pd(t);case 42:return zc(t);case 43:return P(t,"base10");case 6:case 273:case 33:case 132:return Wc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return zc(t);case 421:return r0(t);case 444:return i0(t);case 445:return a0(t);case 466:return n0(t);case 481:return zc(globalThis.decodeURIComponent(t));default:return P(t,"base16")}}function Gc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===Yg.code||n===Qg.code)&&(e=o),n===Jg.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new Xr(e,t)}var qc=Object.values(En).map(r=>r.decoder),t0=function(){let r=qc[0].or(qc[1]);return qc.slice(2).forEach(t=>r=r.or(t)),r}();function Pd(r){if(!fs(r))throw new Error("invalid ip address");return Uc(r)}function e0(r){let t=Cd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!fs(t))throw new Error("invalid ip address");return t}function Wc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Ld(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function zc(r){let t=P(r),e=Uint8Array.from(At(t.length));return Pt([e,t],e.length+t.length)}function Vc(r){let t=te(r);if(r=r.slice(ht(t)),r.length!==t)throw new Error("inconsistent lengths");return O(r)}function r0(r){let t;r[0]==="Q"||r[0]==="1"?t=qt(q.decode(`z${r}`)).bytes:t=ot.parse(r).multihash.bytes;let e=Uint8Array.from(At(t.length));return Pt([e,t],e.length+t.length)}function n0(r){let t=t0.decode(r),e=Uint8Array.from(At(t.length));return Pt([e,t],e.length+t.length)}function o0(r){let t=te(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+O(e,"base64url")}function s0(r){let t=te(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return O(e,"base58btc")}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!==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=Wc(n);return Pt([e,o],e.length+o.length)}function a0(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=Wc(n);return Pt([e,o],e.length+o.length)}function Td(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=O(t,"base32"),o=Ld(e);return`${n}:${o}`}function Dd(r){r=jc(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=H(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new ds("invalid address: "+r);if(a.path===!0){n=jc(o.slice(s).join("/")),t.push([a.code,$c(a.code,n)]),e.push([a.code,n]);break}let c=$c(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Hc(a.code,c)])}return{string:kd(e),bytes:hs(t),tuples:t,stringTuples:e,path:n}}function Xc(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=te(r,o),i=ht(s),a=H(s),c=c0(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 ds("Invalid address Uint8Array: "+O(r,"base16"));t.push([s,l]);let u=Hc(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:kd(e),tuples:t,stringTuples:e,path:n}}function kd(r){let t=[];return r.map(e=>{let n=H(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),jc(t.join("/"))}function hs(r){return Pt(r.map(t=>{let e=H(t[0]),n=Uint8Array.from(At(e.code));return t.length>1&&t[1]!=null&&(n=Pt([n,t[1]])),n}))}function c0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=te(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ht(e)}}function jc(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ds=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var l0=Symbol.for("nodejs.util.inspect.custom"),Yc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),u0=[H("dns").code,H("dns4").code,H("dns6").code,H("dnsaddr").code],Zc=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ps=class r{bytes;#t;#e;#r;#a;[Yc]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Xc(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Dd(t)}else if(Ke(t))e=Xc(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=H("tcp"),a=H("udp"),c=H("ip4"),l=H("ip6"),u=H("dns6"),f=H("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(s=`%${p??""}`),u0.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=H(m).name==="tcp"?"tcp":"udp",o=parseInt(p??"")),(m===c.code||m===l.code)&&(e=H(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({},H(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>H(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(hs(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Yr.p2p.code&&t.push([n,o]),n===Yr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?O(q.decode(`z${n}`),"base58btc"):O(ot.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return Q(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Qr.get(e.name);if(n==null)throw new Zc(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>$(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)}[l0](){return`Multiaddr(${this.#t})`}};var Qr=new Map;function Ke(r){return!!r?.[Yc]}function $(r){return new ps(r)}var f0=32,{code:d0}=H("dnsaddr"),Qc=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},ur=async function(t,e={}){let n=e.maxRecursiveDepth??f0;if(n===0)throw new Qc("Max recursive depth reached");let[,o]=t.stringTuples().find(([l])=>l===d0)??[],i=await(e?.dns??bd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Ht.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=$(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 qd=hn(Kd(),1),ys=qd.default;var w0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:ur}},transportManager:{faultTolerance:$e.FATAL_ALL}};async function zd(r){let t=ys(w0,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 b0(r,t){try{if(typeof r=="string"&&r.length>0)return x0(r);if(typeof r=="number"&&isFinite(r))return t?.long?v0(r):E0(r);throw new Error("Value is not a string or number.")}catch(e){let n=S0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function x0(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 bs=b0;function E0(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?ws(r,t,864e5,"day"):t>=36e5?ws(r,t,36e5,"hour"):t>=6e4?ws(r,t,6e4,"minute"):t>=1e3?ws(r,t,1e3,"second"):`${r} ms`}function ws(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function S0(r){return typeof r=="object"&&r!==null&&"message"in r}function tl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=bs,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,(k,I)=>{if(k==="%%")return"%";E++;let T=e.formatters[I];if(typeof T=="function"){let D=h[E];k=T.call(w,D),h.splice(E,1),E--}return k}),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 xs=L0(),A0=["#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 _0(){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 I0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+bs(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 C0=console.debug??console.log??(()=>{});function P0(r){try{r?xs?.setItem("debug",r):xs?.removeItem("debug")}catch{}}function T0(){let r;try{r=xs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function L0(){try{return localStorage}catch{}}function D0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Vd=tl({formatArgs:I0,save:P0,load:T0,useColors:_0,setupFormatters:D0,colors:A0,storage:xs,log:C0});var Ft=Vd;Ft.formatters.b=r=>r==null?"undefined":q.baseEncode(r);Ft.formatters.t=r=>r==null?"undefined":Kt.baseEncode(r);Ft.formatters.m=r=>r==null?"undefined":ua.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":Hd(r.stack)??Hd(r.message)??r.toString();function k0(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 Es(){return{forComponent(r){return M0(r)}}}function M0(r){let t=k0(`${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 Hd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function fr(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 vs(r){let t=qt(q.decode(`z${r}`));return Wr(t)}var Se=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 fr(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 fr(this.map.values(),t=>t.key)}values(){return fr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var dr=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 fr(this.set.entries(),t=>{let e=vs(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=vs(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return fr(this.set.values(),t=>vs(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 el={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},$d={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Gd=new globalThis.TextEncoder;function R0(r,t){let e=el[t],n=$d[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=el[t],o=$d[t],s=r;for(;s.length>0;){let i=Gd.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 rl(r,{size:t=32,utf8Buffer:e}={}){if(!el[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=Gd.encode(r)}return R0(r,t)}var Jn={hash:r=>Number(rl(r,{size:32})),hashV:(r,t)=>O0(Jn.hash(r,t))};function O0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var nl=64,ne=class{fp;h;seed;constructor(t,e,n,o=2){if(o>nl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=at(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?Q(this.fp,t.fp):!1}};function hr(r,t){return Math.floor(Math.random()*(t-r))+r}var pr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ne))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 ne))throw new TypeError("Invalid Fingerprint");let e=hr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ne))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,to=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??Jn,this.seed=t.seed??hr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new ne(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 pr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new pr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[hr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new pr(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 pr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=P(t));let e=new ne(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=P(t));let e=new ne(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}},F0={1:.5,2:.84,4:.95,8:.98};function U0(r=.001){return r>.002?2:r>1e-5?4:8}function Wd(r,t=.001){let e=U0(t),n=F0[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),nl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Ss=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??Jn,this.seed=t.seed??hr(0,Math.pow(2,10)),this.filterSeries=[new to({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=P(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 to({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=P(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=P(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 eo(r,t=.001,e){return new Ss({...Wd(r,t),...e??{}})}var ro;(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:at(0),payloadType:at(0),payload:at(0),signature:at(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(ro||(ro={}));var As=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var en=class r{static createFromProtobuf=async t=>{let e=ro.decode(t),n=Gr(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=jd(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 As("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=ro.encode({publicKey:$t(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return Q(this.marshal(),t.marshal())}async validate(t){let e=jd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},jd=(r,t,e)=>{let n=P(r),o=At(n.byteLength),s=At(t.length),i=At(e.length);return new W(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 Zd="libp2p-peer-record",Yd=Uint8Array.from([3,1]);var no;(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:at(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Mt(s,n.codec()),n.decode=(s,i)=>kt(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:at(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 ir('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Mt(n,r.codec()),r.decode=(n,o)=>kt(n,r.codec(),o)})(no||(no={}));var mr=class r{static createFromProtobuf=t=>{let e=no.decode(t),n=Wr(qt(e.peerId)),o=(e.addresses??[]).map(i=>$(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Yd;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=no.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 K0(r){return r[Symbol.asyncIterator]!=null}function q0(r){if(K0(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 oo=q0;var qe={},rn=r=>{r.addEventListener("message",t=>{rn.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{rn.dispatchEvent("message",r,t)})};rn.addEventListener=(r,t)=>{qe[r]==null&&(qe[r]=[]),qe[r].push(t)};rn.removeEventListener=(r,t)=>{qe[r]!=null&&(qe[r]=qe[r].filter(e=>e===t))};rn.dispatchEvent=function(r,t,e){qe[r]!=null&&qe[r].forEach(n=>n(t,e))};var ol=rn;var sl="lock:worker:request-read",il="lock:worker:release-read",al="lock:master:grant-read",cl="lock:worker:request-write",ll="lock:worker:release-write",ul="lock:master:grant-write";var Qd=(r=21)=>Math.random().toString().substring(2);var Jd=(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)})}}}))},th=(r,t,e,n)=>async()=>{let o=Qd();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)})},z0={singleProcess:!1},eh=r=>{if(r=Object.assign({},z0,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return ol.addEventListener("message",Jd(e,"requestReadLock",sl,il,al)),ol.addEventListener("message",Jd(e,"requestWriteLock",cl,ll,ul)),e}return{isWorker:!0,readLock:e=>th(e,sl,al,il),writeLock:e=>th(e,cl,ul,ll)}};var gr={},ze;async function fl(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>Zn((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var V0=(r,t)=>{if(ze.isWorker===!0)return{readLock:ze.readLock(r,t),writeLock:ze.writeLock(r,t)};let e=new Ue({concurrency:1}),n;return{async readLock(){if(n!=null)return fl(n,t);n=new Ue({concurrency:t.concurrency,autoStart:!1});let o=n,s=fl(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,fl(e,t)}}},H0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function dl(r){let t=Object.assign({},H0,r);return ze==null&&(ze=eh(t),ze.isWorker!==!0&&(ze.addEventListener("requestReadLock",e=>{gr[e.data.name]!=null&&gr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),ze.addEventListener("requestWriteLock",async e=>{gr[e.data.name]!=null&&gr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),gr[t.name]==null&&(gr[t.name]=V0(t.name,t)),gr[t.name]}var Ae;(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:at(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>kt(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),Is.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=Is.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>kt(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),_s.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 ir('Decode error - map field "addresses" had too many elements');a.addresses.push(_s.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 ir('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 On('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 On('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Mt(o,r.codec()),r.decode=(o,s)=>kt(o,r.codec(),s)})(Ae||(Ae={}));var _s;(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:at(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(_s||(_s={}));var Is;(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=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(Is||(Is={}));function $0(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=q.decode(`z${r}`);e=qt(o)}let n=Gr(t.publicKey,e);return Pc(n)}function Cs(r,t,e){let n=Ae.decode(t);return Ps(r,n,e)}function Ps(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:$(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function rh(r,t){return G0(r.addresses,t.addresses)&&W0(r.protocols,t.protocols)&&j0(r.publicKey,t.publicKey)&&X0(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Z0(r.metadata,t.metadata)&&Y0(r.tags,t.tags)}function G0(r,t){return oh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!Q(e.multiaddr,n.multiaddr)))}function W0(r,t){return oh(r,t,(e,n)=>e===n)}function j0(r,t){return nh(r,t)}function X0(r,t){return nh(r,t)}function Z0(r,t){return sh(r,t,(e,n)=>Q(e,n))}function Y0(r,t){return sh(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function nh(r,t){return r==null&&t==null?!0:r!=null&&t!=null?Q(r,t):!1}function oh(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 sh(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 _e="/",ih=new TextEncoder().encode(_e),Ts=ih[0],yr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(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]!==Ts)throw new Error("Invalid key")}toString(t="utf8"){return O(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(_e))}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=ih),this._buf[0]!==Ts){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ts,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ts;)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(_e).slice(1)}type(){return Q0(this.baseNamespace())}name(){return J0(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(_e)||(t+=_e),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(_e):new r(t.slice(0,-1).join(_e))}child(t){return this.toString()===_e?t:t.toString()===_e?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(),...ty(t.map(e=>e.namespaces()))])}};function Q0(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function J0(r){let t=r.split(":");return t[t.length-1]}function ty(r){return[].concat(...r)}var hl="/peers/";function so(r){if(!Ao(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new yr(`${hl}${t}`)}async function ah(r,t,e,n){let o=new Map;for(let s of e){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=$(s.multiaddr)),!Ke(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 Ds(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=Ls(d,{validate:ch})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Ls(d,{validate:lh,map:uh})}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=Ls([...a.entries()],{validate:ch})}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=Ls([...m.entries()],{validate:lh,map:uh})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=$t(o.id.publicKey):t.publicKey!=null?u=$t(t.publicKey):r.publicKey!=null&&(u=$t(r.publicKey));let f={addresses:await ah(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=>Q(m.multiaddr,m.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Ls(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 ch(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 lh(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 uh(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 fh(r){let t=r.toString().split("/")[2],e=ot.parse(t,Kt);return Wn(e)}function pl(r,t,e){let n=fh(r);return Cs(n,t,e)}function ey(r,t){return{prefix:hl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(pl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(pl(n.key,n.value,t),pl(o.key,o.value,t)))}}var ks=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=dl({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(so(t))}async load(t){let e=so(t),n=await this.datastore.get(e),o=Ae.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new Ge;return Ps(t,o,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e){let n=await this.#t(t),o=await Ds(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,o,n)}async patch(t,e){let n=await this.#t(t),o=await Ds(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 Ds(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(ey(t??{},this.maxAddressAge))){let o=fh(e);if(o.equals(this.peerId))continue;let s=Ae.decode(n);if(this.#r(o,s)){await this.datastore.delete(e);continue}yield Ps(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t){try{let e=so(t),n=await this.datastore.get(e),o=Ae.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new Ge;return{peerPB:o,peer:Cs(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=Ae.encode(e);return await this.datastore.put(so(t),o),{peer:Cs(t,o,this.maxAddressAge),previous:n?.peer,updated:n==null||!rh(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 ml=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 ks(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 oo(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 en.openAndCertify(t,mr.DOMAIN),o=Wn(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=mr.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 en.createFromProtobuf(i.peerRecordEnvelope),c=mr.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 dh(r,t={}){return new ml(r,t)}var Ms=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 ry(r){return r[Symbol.asyncIterator]!=null}function ny(r){if(ry(r))return(async()=>{for await(let t of r);})();for(let t of r);}var gl=ny;function oy(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 hh=oy;function sy(r){return r[Symbol.asyncIterator]!=null}function iy(r,t){let e=0;if(sy(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=hh(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 wr=iy;function ay(r){return r[Symbol.asyncIterator]!=null}function cy(r,t){return ay(r)?async function*(){yield*(await oo(r)).sort(t)}():function*(){yield*oo(r).sort(t)}()}var yl=cy;function ly(r){return r[Symbol.asyncIterator]!=null}function uy(r,t){return ly(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 wl=uy;var Rs=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 gl(this.putMany(t,n)),t=[],await gl(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=wr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>yl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=wr(n,()=>o++>=s)}return t.limit!=null&&(n=wl(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=wr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>yl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=wr(n,()=>s++>=o)}return t.limit!=null&&(n=wl(n,t.limit)),n}};var Ns=class extends Rs{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 Ms;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 yr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new yr(t)}};function ph(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 gh=hn(mh(),1),fy=["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"],dy=fy.map(r=>new gh.Netmask(r));function bl(r){for(let t of dy)if(t.contains(r))return!0;return!1}function hy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function py(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 bl(o)}function my(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function gy(r){let t=r.split(":"),e=t[t.length-1];return bl(e)}function yy(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 Ve(r){return re(r)?bl(r):hy(r)?py(r):my(r)?gy(r):Zr(r)?yy(r):void 0}var wy=r=>r.toString().split("/").slice(1),nn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>nn(e=>e===r).match(t),pattern:r}),br=()=>({match:r=>nn(t=>typeof t=="string").match(r),pattern:"{string}"}),ao=()=>({match:r=>nn(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{q.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),co=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{fa.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),j=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 nt(...r){function t(o){let s=wy(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 by=J(),yh=nt(by),Bs=V(z("dns4"),br()),Fs=V(z("dns6"),br()),Us=V(z("dnsaddr"),br()),El=V(z("dns"),br()),G6=nt(Bs,j(J())),W6=nt(Fs,j(J())),j6=nt(Us,j(J())),X6=nt(Ct(El,Us,Bs,Fs),j(J())),wh=V(z("ip4"),nn(re)),bh=V(z("ip6"),nn(Zr)),vl=Ct(wh,bh),Ie=Ct(vl,El,Bs,Fs,Us),Z6=nt(Ct(vl,V(Ct(El,Us,Bs,Fs),j(J())))),Sl=nt(wh),Al=nt(bh),Y6=nt(vl),_l=V(Ie,z("tcp"),ao()),lo=V(Ie,z("udp"),ao()),uo=nt(V(_l,j(J()))),Q6=nt(lo),Il=V(lo,z("quic"),j(J())),Ks=V(lo,z("quic-v1"),j(J())),xy=Ct(Il,Ks),J6=nt(Il),xh=nt(Ks),xl=Ct(Ie,_l,lo,Il,Ks),Eh=Ct(V(xl,z("ws"),j(J()))),xr=nt(Eh),vh=Ct(V(xl,z("wss"),j(J())),V(xl,z("tls"),j(V(z("sni"),br())),z("ws"),j(J()))),fo=nt(vh),Sh=V(lo,z("webrtc-direct"),j(co()),j(co()),j(J())),Cl=nt(Sh),Ah=V(Ks,z("webtransport"),j(co()),j(co()),j(J())),Pl=nt(Ah),Os=Ct(Eh,vh,V(_l,j(J())),V(xy,j(J())),V(Ie,j(J())),Sh,Ah,J()),t4=nt(Os),Ey=V(Os,z("p2p-circuit"),J()),ho=nt(Ey),vy=Ct(V(Os,z("p2p-circuit"),z("webrtc"),j(J())),V(Os,z("webrtc"),j(J())),V(z("webrtc"),j(J()))),Tl=nt(vy),Sy=Ct(V(Ie,z("tcp"),ao(),z("http"),j(J())),V(Ie,z("http"),j(J()))),e4=nt(Sy),Ay=Ct(V(Ie,z("tcp"),Ct(V(z("443"),z("http")),V(ao(),z("https"))),j(J())),V(Ie,z("tls"),z("http"),j(J())),V(Ie,z("https"),j(J()))),r4=nt(Ay),_y=Ct(V(z("memory"),br(),j(J()))),n4=nt(_y);var _h=864e13;var Iy=448,Ll=449,Cy=53,Py=54,Ty=55,Ly=56,qs=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=Ve(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?_h-Date.now():0,lastVerified:o?_h-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:$(`/${s.map(u=>[H(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]===Iy&&t[n+1]?.[0]!==Ll)return t.splice(n+1,0,[Ll,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]===Ll||e[0]===Cy||e[0]===Py||e[0]===Ty||e[0]===Ly)return e[1]}};var Dl=4,kl=41,Ml=6,Dy=273,zs=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:re(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]===Ml?"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]===Dl||o[0][0]===kl)&&o[1][0]===Ml?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Dl||o[0][0]===kl)&&o[1][0]===Dy&&(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?Dl:kl,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:$(`/${o.map(c=>[H(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]===Ml?"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 Ih(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 Vs(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function Er(r){try{if(!Vs(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:Ve(t)??!1}catch{}return!0}var ky={maxObservedAddresses:10},Hs=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}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&&(Er(t)||Ih(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:$(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 My=[4,41,53,54,55,56];function Rl(r){try{let[[t]]=r.stringTuples();return My.includes(t)}catch{}return!1}var Ry={maxObservedAddresses:10},$s=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??Ry.maxObservedAddresses}get(t,e){if(Er(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:!Rl(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(Rl(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Ch=6e4,Ph={maxObservedAddresses:10,addressVerificationTTL:Ch*10,addressVerificationRetry:Ch*5},Ny=r=>r;function Nl(r,t){let e=r.getPeerId();return e!=null&&ue(e).equals(t)&&(r=r.decapsulate($(`/p2p/${t.toString()}`))),r}var Gs=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 Hs(t,e),this.dnsMappings=new qs(t,e),this.ipMappings=new zs(t,e),this.transportAddresses=new $s(t,e),this.announceFilter=e.announceFilter??Ny,this.observedAddressFilter=eo(1024),this.addressVerificationTTL=e.addressVerificationTTL??Ph.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Ph.addressVerificationRetry,this._updatePeerStoreAddresses=ph(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=>$(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>$(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>$(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=Nl(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=Nl(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=Nl(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=$(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(o=>{o.updateAnnounceAddrs(t)}),t.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];e=e.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),e=e.concat(n.map(o=>({multiaddr:o,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($(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${re(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove($(`/ip${re(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"||Ve(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>xr.exactMatch(s)||fo.exactMatch(s),s=>uo.exactMatch(s),s=>xh.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 Th;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Th||(Th={}));var Ws=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},js=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},on=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},po=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Xs=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"}},Ys=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},mo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Qs=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Js=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},ti=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},ei=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},ri=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},vr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Sr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},ni=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var Ol=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=Es())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>ko(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")}},By=["metrics","connectionProtector","dns"],Fy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Lh(r={}){let t=new Ol(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Fy.includes(o)){let i=t.components[o];if(i==null&&!By.includes(o))throw new Ws(`${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 Dh(r){let t={};for(let e of Object.values(r.components))for(let n of Uy(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Ky(e))if(t[n]!==!0)throw new js(`Service "${qy(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Uy(r){return Array.isArray(r?.[gn])?r[gn]:[]}function Ky(r){return Array.isArray(r?.[Xi])?r[Xi]:[]}function qy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var zy=4,Vy=41;function kh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(xr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===zy||e[0][0]===Vy?!!Ve(`${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 Mh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Hy=new WeakMap;function $y({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Mh());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(Mh())},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}),Hy.set(f,()=>{c(s),s=null,i()}),f}}var Gy=$y(),Rh=Gy;var oi=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}},si=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ii=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 Bl}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 oi("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 Rh(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)}},Bl=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 ai(r){if(Ao(r))return{peerId:r,multiaddrs:[]};let t=Array.isArray(r)?r:[r],e;if(t.length>0){let n=t[0].getPeerId();e=n==null?void 0:ue(n),t.forEach(o=>{if(!Ke(o))throw new Te("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ue(s);if(e?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!yh.exactMatch(n)),{peerId:e,multiaddrs:t}}var Wy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Nh(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Wy;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var Oh="last-dial-failure",Bh="last-dial-success";var ci=100,li=50;async function Fh(r,t){let e=!1;for(let o of Qr.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 go(r){try{let t;if(typeof r=="string"?t=$(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return Gc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var jy={maxConnections:ci,allow:[]},ui=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??jy.maxConnections,this.allow=(e.allow??[]).map(n=>go(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 Se;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 Nh(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 ct(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var fi=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}},sn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new fi(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 fi(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 Fl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Uh(r={}){return Xy(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 Xy(r,t){t=t??{};let e=t.onEnd,n=new sn,o,s,i,a=ct(),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=ct()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new sn,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 sn,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 Fl)},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 Ul=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 an(r,t,e,n){let o=new Ul(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 di=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 oe(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new di(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new di(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 hi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ct(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Xt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Zy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var pi=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Zy(),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 Xt),this.cleanup())}async join(t={}){let e=new hi(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 oe(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 ln=class extends de{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new si;let n=new pi(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 Xt)}),this.clear()}async onEmpty(t){this.size!==0&&await an(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await an(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await an(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=Uh({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 Xt("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 mi=class extends ln{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ce(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 Kh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Kl(r){if(!Vs(r))return!1;let{address:t}=r.nodeAddress();return Kh(t)}function Yy(r,t){let e=uo.exactMatch(r.multiaddr),n=uo.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=fo.exactMatch(r.multiaddr),s=fo.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=xr.exactMatch(r.multiaddr),a=xr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Tl.exactMatch(r.multiaddr),l=Tl.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Cl.exactMatch(r.multiaddr),f=Cl.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Pl.exactMatch(r.multiaddr),m=Pl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function Qy(r,t){let e=Kl(r.multiaddr),n=Kl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Jy(r,t){let e=Er(r.multiaddr),n=Er(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function tw(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function ew(r,t){let e=ho.exactMatch(r.multiaddr),n=ho.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function qh(r){return r.sort(Yy).sort(tw).sort(ew).sort(Jy).sort(Qy)}var gi={maxParallelDials:li,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ur}},yi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??gi.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??gi.maxDialQueueLength,this.dialTimeout=e.dialTimeout??gi.dialTimeout,this.connections=e.connections??new Se,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??{}))Qr.set(n,o);this.queue=new mi({concurrency:e.maxParallelDials??gi.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==Xt.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}=ai(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 Lr("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=Ce([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Hl,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 Lr("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:{[Bh]:P(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:{[Oh]:P(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new To(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:$(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Lr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new mo("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 Fh(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 ti("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?qh(l):l.sort(this.addressSorter);if(u.length===0)throw new mo("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=>!ho.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var wi=class extends ln{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var jh=hn(Gh(),1);var nw=Object.prototype.toString,ow=r=>nw.call(r)==="[object Error]",sw=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 $l(r){return r&&ow(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:sw.has(r.message):!1}var Gl=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}},Wh=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Wl(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=jh.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 Gl)throw c.originalError;if(c instanceof TypeError&&!$l(c))throw c;if(Wh(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Wh(l,a,t),i(),n(l)}}})})}var bi=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 wi({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);Xh(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Wl(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(ji)&&(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=>Xh(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 Xh(r){for(let t of r.tags.keys())if(t.startsWith(ji))return!0;return!1}var Hl=50,jl={maxConnections:ci,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},xi=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??jl.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Se,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=>go(n)),this.deny=(e.deny??[]).map(n=>go(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??jl.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ii({points:e.inboundConnectionThreshold??jl.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ui({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>$(n))}),this.dialQueue=new yi(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??li,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:ur},connections:this.connections}),this.reconnectQueue=new bi({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 au(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 cu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new fe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=ai(t);if(this.peerId.equals(n))throw new Tr("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??Hl});if(o.status!=="open")throw new Pr("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 Te("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=>$(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var un=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 cw=1.2,lw=2,uw=2e3,Ei=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new un(t.interval??5e3),this.failure=new un(t.interval??5e3),this.next=new un(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??lw,this.timeoutMultiplier=t.timeoutMultiplier??cw,this.minTimeout=t.minTimeout??uw,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=Ce([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 Xl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ct(),this.haveNext=ct()}[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=ct(),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=ct(),await oe(this.readNext.promise,e?.signal,e)}};function vi(){return new Xl}var Si=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ai(r,t){let e=vi();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 W;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await oe(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await oe(n.next(),i?.signal);if(l===!0)throw new Si("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 fw=1e4,dw="1.0.0",hw="ping",pw="ipfs",Zh=32,mw=!0,_i=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??pw}/${hw}/${dw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??fw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??mw,this.timeout=new Ei({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[gn]=["@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=Ai(o);e=Date.now(),await Promise.all([s.write(Hr(Zh),{signal:n}),s.read({bytes:Zh,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 gw(r){return r[Symbol.asyncIterator]!=null}async function yw(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*ww(r){let t=vi();yw(r,t).catch(()=>{}),yield*t}function*bw(r){for(let t of r)yield*t}function xw(...r){let t=[];for(let e of r)gw(e)||t.push(e);return t.length===r.length?bw(t):ww(r)}var yo=xw;var Ii=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:O(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:O(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 on("No content routers available");let n=this,o=new dr;for await(let s of yo(...n.routers.filter(i=>i.findProviders instanceof Function).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 on("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new on("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new fe;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new fe;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var Ci=globalThis.CustomEvent??Event;async function*Zl(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=ct(),a=ct(),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=ct(),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 Ci("task-complete"))},h=>{g.done=!0,g.err=h,o.dispatchEvent(new Ci("task-complete"))})}c=!0,o.dispatchEvent(new Ci("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ci("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=ct(),await a.promise),l!=null||(n?yield*d():yield*m(),l!=null))throw l;if(c&&s.length===0)break}}var Pi=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:O(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 po("No peer routers available");if(t.toString()===this.peerId.toString())throw new Xs("Should not try to find self");let n=this,o=yo(...this.routers.filter(s=>s.findPeer instanceof Function).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 Ge}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new po("No peer routers available");let n=this,o=eo(1024);for await(let s of Zl(async function*(){let i=yo(...n.routers.filter(a=>a.getClosestPeers instanceof Function).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 Ti=class extends de{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Ce([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ct(),yield(await an(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=Ce([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=Hr(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 oe(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 Yl=32,Ql=64,Li=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 Ys(`Handler already registered for protocol ${t}`);let o=ys.bind({ignoreUndefined:!0})({maxInboundStreams:Yl,maxOutboundStreams:Ql},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 Jl=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 Yh(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Jl({name:t,metrics:e}):n=new Map,n}var Di=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=Yh({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 ni(`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 fe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new Qs)});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})}),Sl.matches(c)?e.ipv4.attempts++:Al.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),Sl.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 Js(`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 lp=Object.create;var vo=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var fp=Object.getOwnPropertyNames;var dp=Object.getPrototypeOf,hp=Object.prototype.hasOwnProperty;var Pe=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Bt=(r,t)=>{for(var e in t)vo(r,e,{get:t[e],enumerable:!0})},su=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fp(t))!hp.call(r,o)&&o!==e&&vo(r,o,{get:()=>t[o],enumerable:!(n=up(t,o))||n.enumerable});return r};var hn=(r,t,e)=>(e=r!=null?lp(dp(r)):{},su(t||!r||!r.__esModule?vo(e,"default",{value:r,enumerable:!0}):e,r)),pp=r=>su(vo({},"__esModule",{value:!0}),r);var fd=Pe((GE,Tc)=>{"use strict";var qg=Object.prototype.hasOwnProperty,Nt="~";function jn(){}Object.create&&(jn.prototype=Object.create(null),new jn().__proto__||(Nt=!1));function zg(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function ud(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new zg(e,n||r,o),i=Nt?Nt+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 os(r,t){--r._eventsCount===0?r._events=new jn:delete r._events[t]}function It(){this._events=new jn,this._eventsCount=0}It.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)qg.call(e,n)&&t.push(Nt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};It.prototype.listeners=function(t){var e=Nt?Nt+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=Nt?Nt+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=Nt?Nt+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};It.prototype.on=function(t,e,n){return ud(this,t,e,n,!1)};It.prototype.once=function(t,e,n){return ud(this,t,e,n,!0)};It.prototype.removeListener=function(t,e,n,o){var s=Nt?Nt+t:t;if(!this._events[s])return this;if(!e)return os(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&os(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:os(this,s)}return this};It.prototype.removeAllListeners=function(t){var e;return t?(e=Nt?Nt+t:t,this._events[e]&&os(this,e)):(this._events=new jn,this._eventsCount=0),this};It.prototype.off=It.prototype.removeListener;It.prototype.addListener=It.prototype.on;It.prefixed=Nt;It.EventEmitter=It;typeof Tc<"u"&&(Tc.exports=It)});var gd=Pe((mv,md)=>{md.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 Rd=Pe((zS,Md)=>{"use strict";Md.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var Kd=Pe((Fd,Ud)=>{"use strict";var ms=Rd(),{hasOwnProperty:Od}=Object.prototype,{propertyIsEnumerable:h0}=Object,Jr=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),p0=Fd,Nd={concatArrays:!1,ignoreUndefined:!1},gs=r=>{let t=[];for(let e in r)Od.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)h0.call(r,n)&&t.push(n)}return t};function tn(r){return Array.isArray(r)?m0(r):ms(r)?g0(r):r}function m0(r){let t=r.slice(0,0);return gs(r).forEach(e=>{Jr(t,e,tn(r[e]))}),t}function g0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return gs(r).forEach(e=>{Jr(t,e,tn(r[e]))}),t}var Bd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Jr(r,o,Jc(r[o],t[o],n)):Jr(r,o,tn(t[o])))}),r),y0=(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++)Od.call(s,a)&&(i.push(String(a)),s===r?Jr(n,o++,s[a]):Jr(n,o++,tn(s[a])));n=Bd(n,s,gs(s).filter(a=>!i.includes(a)),e)}),n};function Jc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?y0(r,t,e):!ms(t)||!ms(r)?tn(t):Bd(r,t,gs(t),e)}Ud.exports=function(...r){let t=Jc(tn(Nd),this!==p0&&this||{},Nd),e={_:{}};for(let n of r)if(n!==void 0){if(!ms(n))throw new TypeError("`"+n+"` is not an Option Object");e=Jc(e,{_:n},t)}return e._}});var mh=Pe(io=>{(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}(),io.ip2long=i,io.long2ip=a,io.Netmask=r}).call(io)});var Vh=Pe((a8,zh)=>{function Wt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}zh.exports=Wt;Wt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Wt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Wt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Wt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Wt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Wt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Wt.prototype.start=Wt.prototype.try;Wt.prototype.errors=function(){return this._errors};Wt.prototype.attempts=function(){return this._attempts};Wt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var Hh=Pe(Ar=>{var rw=Vh();Ar.operation=function(r){var t=Ar.timeouts(r);return new rw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ar.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};Ar.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};Ar.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=Ar.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=Pe((l8,$h)=>{$h.exports=Hh()});var Dw={};Bt(Dw,{createLibp2p:()=>Lw});var iu=Symbol.for("@libp2p/connection");var $i=Symbol.for("@libp2p/content-routing");var Gi=Symbol.for("@libp2p/peer-discovery");var So=Symbol.for("@libp2p/peer-id");function Ao(r){return!!r?.[So]}var Wi=Symbol.for("@libp2p/peer-routing");var ji="keep-alive";var Uw=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 Xt=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"}},Cr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},pn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var _o=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Pr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Ge=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Tr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Te=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Io=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Co=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},mn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Po=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var To=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},fe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Lr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Dr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Lo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Do=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Le=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var de=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function ko(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function au(...r){let t=[];for(let e of r)ko(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 cu(...r){let t=[];for(let e of r)ko(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 gn=Symbol.for("@libp2p/service-capabilities"),Xi=Symbol.for("@libp2p/service-dependencies");var ta={};Bt(ta,{base58btc:()=>q,base58flickr:()=>xp});var db=new Uint8Array(0);function lu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function he(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function uu(r){return new TextEncoder().encode(r)}function fu(r){return new TextDecoder().decode(r)}function mp(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],k=0,I=y-1;(_!==0||k<h)&&I!==-1;I--,k++)_+=256*E[I]>>>0,E[I]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=k,w++}for(var T=y-h;T!==y&&E[T]===0;)T++;for(var D=c.repeat(g);T<y;++T)D+=r.charAt(E[T]);return D}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,k=x-1;(E!==0||_<w)&&k!==-1;k--,_++)E+=a*y[k]>>>0,y[k]=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 T=new Uint8Array(h+(x-I)),D=h;I!==x;)T[D++]=y[I++];return T}}}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 gp=mp,yp=gp,hu=yp;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")}},Yi=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 pu(this,t)}},Qi=class{decoders;constructor(t){this.decoders=t}or(t){return pu(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 pu(r,t){return new Qi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ji=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 Yi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function kr({name:r,prefix:t,encode:e,decode:n}){return new Ji(r,t,e,n)}function De({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=hu(e,r);return kr({prefix:t,name:r,encode:n,decode:s=>he(o(s))})}function wp(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 bp(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 it({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return kr({prefix:t,name:r,encode(o){return bp(o,n,e)},decode(o){return wp(o,n,e,r)}})}var q=De({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xp=De({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ea={};Bt(ea,{base32:()=>Kt,base32hex:()=>Ap,base32hexpad:()=>Ip,base32hexpadupper:()=>Cp,base32hexupper:()=>_p,base32pad:()=>vp,base32padupper:()=>Sp,base32upper:()=>Ep,base32z:()=>Pp});var Kt=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ep=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),vp=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sp=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ap=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_p=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ip=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cp=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pp=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ra={};Bt(ra,{base36:()=>yn,base36upper:()=>Tp});var yn=De({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Tp=De({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Lp=yu,mu=128,Dp=127,kp=~Dp,Mp=Math.pow(2,31);function yu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Mp;)t[e++]=r&255|mu,r/=128;for(;r&kp;)t[e++]=r&255|mu,r>>>=7;return t[e]=r|0,yu.bytes=e-n+1,t}var Rp=na,Np=128,gu=127;function na(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw na.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&gu)<<o:(i&gu)*Math.pow(2,o),o+=7}while(i>=Np);return na.bytes=s-n,e}var Op=Math.pow(2,7),Bp=Math.pow(2,14),Fp=Math.pow(2,21),Up=Math.pow(2,28),Kp=Math.pow(2,35),qp=Math.pow(2,42),zp=Math.pow(2,49),Vp=Math.pow(2,56),Hp=Math.pow(2,63),$p=function(r){return r<Op?1:r<Bp?2:r<Fp?3:r<Up?4:r<Kp?5:r<qp?6:r<zp?7:r<Vp?8:r<Hp?9:10},Gp={encode:Lp,decode:Rp,encodingLength:$p},Wp=Gp,wn=Wp;function bn(r,t=0){return[wn.decode(r,t),wn.decode.bytes]}function Mr(r,t,e=0){return wn.encode(r,t,e),t}function Rr(r){return wn.encodingLength(r)}function Zt(r,t){let e=t.byteLength,n=Rr(r),o=n+Rr(e),s=new Uint8Array(o+e);return Mr(r,s,0),Mr(e,s,n),s.set(t,o),new Nr(r,e,t,s)}function qt(r){let t=he(r),[e,n]=bn(t),[o,s]=bn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Nr(e,o,i,t)}function wu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&lu(r.bytes,e.bytes)}}var Nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function bu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Xp(e,oa(r),t??q.encoder);default:return Zp(e,oa(r),t??Kt.encoder)}}var xu=new WeakMap;function oa(r){let t=xu.get(r);if(t==null){let e=new Map;return xu.set(r,e),e}return t}var ot=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!==xn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Yp)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=Zt(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&&wu(t.multihash,n.multihash)}toString(t){return bu(this,t)}toJSON(){return{"/":bu(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??Eu(n,o,s.bytes))}else if(e[Qp]===!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!==xn)throw new Error(`Version 0 CID must use dag-pb (code: ${xn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Eu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,xn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=he(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Nr(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]=bn(t.subarray(e));return e+=d,f},o=n(),s=xn;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]=jp(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 oa(s).set(n,t),s}};function jp(r,t){switch(r[0]){case"Q":{let e=t??q;return[q.prefix,e.decode(`${q.prefix}${r}`)]}case q.prefix:{let e=t??q;return[q.prefix,e.decode(r)]}case Kt.prefix:{let e=t??Kt;return[Kt.prefix,e.decode(r)]}case yn.prefix:{let e=t??yn;return[yn.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 Xp(r,t,e){let{prefix:n}=e;if(n!==q.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 Zp(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 xn=112,Yp=18;function Eu(r,t,e){let n=Rr(r),o=n+Rr(t),s=new Uint8Array(o+e.byteLength);return Mr(r,s,0),Mr(t,s,n),s.set(e,o),s}var Qp=Symbol.for("@ipld/js-cid/CID");var sa={};Bt(sa,{identity:()=>Yt});var vu=0,Jp="identity",Su=he;function tm(r){return Zt(vu,Su(r))}var Yt={code:vu,name:Jp,encode:Su,digest:tm};function Q(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 at(r=0){return new Uint8Array(r)}function vt(r=0){return new Uint8Array(r)}function Pt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=vt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var _u=Symbol.for("@achingbrain/uint8arraylist");function Au(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 Ro(r){return!!r?.[_u]}var W=class r{bufs;length;[_u]=!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(Ro(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(Ro(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=Au(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Au(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(Ro(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 Pt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Pt(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(!Ro(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=vt(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=at(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=at(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=at(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=vt(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=at(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=at(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=at(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=at(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=at(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(!Q(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 ia={};Bt(ia,{base10:()=>em});var em=De({prefix:"9",name:"base10",alphabet:"0123456789"});var aa={};Bt(aa,{base16:()=>rm,base16upper:()=>nm});var rm=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nm=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ca={};Bt(ca,{base2:()=>om});var om=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var la={};Bt(la,{base256emoji:()=>lm});var Iu=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}"),sm=Iu.reduce((r,t,e)=>(r[e]=t,r),[]),im=Iu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function am(r){return r.reduce((t,e)=>(t+=sm[e],t),"")}function cm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=im[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var lm=kr({prefix:"\u{1F680}",name:"base256emoji",encode:am,decode:cm});var da={};Bt(da,{base64:()=>ua,base64pad:()=>um,base64url:()=>fa,base64urlpad:()=>fm});var ua=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),um=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fa=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fm=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ha={};Bt(ha,{base8:()=>dm});var dm=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pa={};Bt(pa,{identity:()=>hm});var hm=kr({prefix:"\0",name:"identity",encode:r=>fu(r),decode:r=>uu(r)});var Xb=new TextEncoder,Zb=new TextDecoder;var ya={};Bt(ya,{sha256:()=>Or,sha512:()=>gm});function ga({name:r,code:t,encode:e}){return new ma(r,t,e)}var ma=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?Zt(this.code,e):e.then(n=>Zt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Pu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Or=ga({name:"sha2-256",code:18,encode:Pu("SHA-256")}),gm=ga({name:"sha2-512",code:19,encode:Pu("SHA-512")});var En={...pa,...ca,...ha,...ia,...aa,...ea,...ra,...ta,...da,...la},cx={...ya,...sa};function Lu(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Tu=Lu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),wa=Lu("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=vt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ym={utf8:Tu,"utf-8":Tu,hex:En.base16,latin1:wa,ascii:wa,binary:wa,...En},No=ym;function P(r,t="utf8"){let e=No[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function O(r,t="utf8"){let e=No[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var wm=parseInt("11111",2),ba=parseInt("10000000",2),bm=parseInt("01111111",2),Du={0:vn,1:vn,2:xm,3:Sm,4:Am,5:vm,6:Em,16:vn,22:vn,48:vn};function pe(r,t={offset:0}){let e=r[t.offset]&wm;if(t.offset++,Du[e]!=null)return Du[e](r,t);throw new Error("No decoder for tag "+e)}function Sn(r,t){let e=0;if((r[t.offset]&ba)===ba){let n=r[t.offset]&bm,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function vn(r,t){Sn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=pe(r,t);if(n===null)break;e.push(n)}return e}function xm(r,t){let e=Sn(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 Em(r,t){let e=Sn(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function vm(r,t){return t.offset++,null}function Sm(r,t){let e=Sn(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Am(r,t){let e=Sn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function _m(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new W;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Oo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=_m(r.byteLength);return new W(Uint8Array.from([t.byteLength|ba]),t)}function Tt(r){let t=new W,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new W(Uint8Array.from([2]),Oo(t),t)}function An(r){let t=Uint8Array.from([0]),e=new W(t,r);return new W(Uint8Array.from([3]),Oo(e),e)}function ku(r){return new W(Uint8Array.from([4]),Oo(r),r)}function Qt(r,t=48){let e=new W;for(let n of r)e.append(n);return new W(Uint8Array.from([t]),Oo(e),e)}async function Mu(r="P-256"){let t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}async function Ru(r,t){let e=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]),n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Nu(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var Im=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Cm=Uint8Array.from([6,5,43,129,4,0,34]),Pm=Uint8Array.from([6,5,43,129,4,0,35]),Tm={ext:!0,kty:"EC",crv:"P-256"},Lm={ext:!0,kty:"EC",crv:"P-384"},Dm={ext:!0,kty:"EC",crv:"P-521"},xa=32,Ea=48,va=66;function Sa(r){let t=pe(r);return Ou(t)}function Ou(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===xa*2+1)return n=O(t.subarray(e,e+xa),"base64url"),o=O(t.subarray(e+xa),"base64url"),new We({...Tm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ea*2+1)return n=O(t.subarray(e,e+Ea),"base64url"),o=O(t.subarray(e+Ea),"base64url"),new We({...Lm,key_ops:["verify"],x:n,y:o});if(t.byteLength===va*2+1)return n=O(t.subarray(e,e+va),"base64url"),o=O(t.subarray(e+va),"base64url"),new We({...Dm,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Bu(r){return Qt([Tt(Uint8Array.from([1])),ku(P(r.d??"","base64url")),Qt([Uu(r.crv)],160),Qt([An(new W(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function Fu(r){return Qt([Tt(Uint8Array.from([1])),Qt([Uu(r.crv)],160),Qt([An(new W(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function Uu(r){if(r==="P-256")return Im;if(r==="P-384")return Cm;if(r==="P-521")return Pm;throw new R(`Invalid curve ${r}`)}async function Ku(r="P-256"){let t=await Mu(r);return new Bo(t.privateKey)}var We=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Fu(this.jwk)),this._raw}toMultihash(){return Yt.digest($t(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}async verify(t,e){return Nu(this.jwk,e,t)}},Bo=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new We({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Bu(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}async sign(t){return Ru(this.jwk,t)}};var je=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function km(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Fo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Xe(r,...t){if(!km(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 qu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Fo(r.outputLen),Fo(r.blockLen)}function Fr(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 zu(r,t){Xe(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function me(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Uo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Jt(r,t){return r<<32-t|r>>>t}function Vu(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function _n(r){return typeof r=="string"&&(r=Vu(r)),Xe(r),r}function Aa(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Xe(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Br=class{};function _a(r){let t=n=>r().update(_n(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Ur(r=32){if(je&&typeof je.getRandomValues=="function")return je.getRandomValues(new Uint8Array(r));if(je&&typeof je.randomBytes=="function")return Uint8Array.from(je.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Mm(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 Hu(r,t,e){return r&t^~r&e}function $u(r,t,e){return r&t^r&e^t&e}var In=class extends Br{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Uo(this.buffer)}update(t){Fr(this),t=_n(t),Xe(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Uo(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){Fr(this),zu(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,me(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Mm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Uo(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.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ge=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ko=BigInt(4294967295),Gu=BigInt(32);function Rm(r,t=!1){return t?{h:Number(r&Ko),l:Number(r>>Gu&Ko)}:{h:Number(r>>Gu&Ko)|0,l:Number(r&Ko)|0}}function Wu(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Rm(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Ia=(r,t,e)=>r>>>e,Ca=(r,t,e)=>r<<32-e|t>>>e,Ze=(r,t,e)=>r>>>e|t<<32-e,Ye=(r,t,e)=>r<<32-e|t>>>e,Cn=(r,t,e)=>r<<64-e|t>>>e-32,Pn=(r,t,e)=>r>>>e-32|t<<64-e;function ie(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var ju=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Xu=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Zu=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Yu=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Qu=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Ju=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Om=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ke=new Uint32Array(64),qo=class extends In{constructor(t=32){super(64,t,8,!1),this.A=ge[0]|0,this.B=ge[1]|0,this.C=ge[2]|0,this.D=ge[3]|0,this.E=ge[4]|0,this.F=ge[5]|0,this.G=ge[6]|0,this.H=ge[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)ke[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=ke[f-15],m=ke[f-2],p=Jt(d,7)^Jt(d,18)^d>>>3,g=Jt(m,17)^Jt(m,19)^m>>>10;ke[f]=g+ke[f-7]+p+ke[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=Jt(a,6)^Jt(a,11)^Jt(a,25),m=u+d+Hu(a,c,l)+Om[f]+ke[f]|0,g=(Jt(n,2)^Jt(n,13)^Jt(n,22))+$u(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(){me(ke)}destroy(){this.set(0,0,0,0,0,0,0,0),me(this.buffer)}};var tf=Wu(["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))),Bm=tf[0],Fm=tf[1],Me=new Uint32Array(80),Re=new Uint32Array(80),Pa=class extends In{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}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)Me[y]=t.getUint32(e),Re[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let E=Me[y-15]|0,_=Re[y-15]|0,k=Ze(E,_,1)^Ze(E,_,8)^Ia(E,_,7),I=Ye(E,_,1)^Ye(E,_,8)^Ca(E,_,7),T=Me[y-2]|0,D=Re[y-2]|0,et=Ze(T,D,19)^Cn(T,D,61)^Ia(T,D,6),X=Ye(T,D,19)^Pn(T,D,61)^Ca(T,D,6),F=Zu(I,X,Re[y-7],Re[y-16]),pt=Yu(F,k,et,Me[y-7],Me[y-16]);Me[y]=pt|0,Re[y]=F|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=Ze(f,d,14)^Ze(f,d,18)^Cn(f,d,41),_=Ye(f,d,14)^Ye(f,d,18)^Pn(f,d,41),k=f&m^~f&g,I=d&p^~d&h,T=Qu(x,_,I,Fm[y],Re[y]),D=Ju(T,w,E,k,Bm[y],Me[y]),et=T|0,X=Ze(n,o,28)^Cn(n,o,34)^Cn(n,o,39),F=Ye(n,o,28)^Pn(n,o,34)^Pn(n,o,39),pt=n&s^n&a^s&a,A=o&i^o&c^i&c;w=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=ie(l|0,u|0,D|0,et|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let L=ju(et,F,A);n=Xu(L,D,X,pt),o=L|0}({h:n,l:o}=ie(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ie(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ie(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ie(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ie(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:p}=ie(this.Fh|0,this.Fl|0,m|0,p|0),{h:g,l:h}=ie(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=ie(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(){me(Me,Re)}destroy(){me(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var zo=_a(()=>new qo);var ef=_a(()=>new Pa);var ka=BigInt(0),Da=BigInt(1);function Qe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ma(r){if(!Qe(r))throw new Error("Uint8Array expected")}function ae(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Tn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function of(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ka:BigInt("0x"+r)}var sf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Um=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Ne(r){if(Ma(r),sf)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Um[r[e]];return t}var ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function rf(r){if(r>=ye._0&&r<=ye._9)return r-ye._0;if(r>=ye.A&&r<=ye.F)return r-(ye.A-10);if(r>=ye.a&&r<=ye.f)return r-(ye.a-10)}function Ln(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(sf)return Uint8Array.fromHex(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=rf(r.charCodeAt(s)),a=rf(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 we(r){return of(Ne(r))}function Je(r){return Ma(r),of(Ne(Uint8Array.from(r).reverse()))}function tr(r,t){return Ln(r.toString(16).padStart(t*2,"0"))}function Kr(r,t){return tr(r,t).reverse()}function st(r,t,e){let n;if(typeof t=="string")try{n=Ln(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Qe(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 Oe(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ma(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 Ta=r=>typeof r=="bigint"&&ka<=r;function Vo(r,t,e){return Ta(r)&&Ta(t)&&Ta(e)&&t<=r&&r<e}function zt(r,t,e,n){if(!Vo(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function af(r){let t;for(t=0;r>ka;r>>=Da,t+=1);return t}var er=r=>(Da<<BigInt(r))-Da,La=r=>new Uint8Array(r),nf=r=>Uint8Array.from(r);function cf(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=La(r),o=La(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=La(0))=>{o=a(nf([0]),f),n=a(),f.length!==0&&(o=a(nf([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 Oe(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Km={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"||Qe(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 be(r,t,e={}){let n=(o,s,i)=>{let a=Km[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}function qr(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 Lt=BigInt(0),mt=BigInt(1),rr=BigInt(2),qm=BigInt(3),Ra=BigInt(4),lf=BigInt(5),uf=BigInt(8),zm=BigInt(9),Vm=BigInt(16);function tt(r,t){let e=r%t;return e>=Lt?e:t+e}function rt(r,t,e){let n=r;for(;t-- >Lt;)n*=n,n%=e;return n}function Ho(r,t){if(r===Lt)throw new Error("invert: expected non-zero number");if(t<=Lt)throw new Error("invert: expected positive modulus, got "+t);let e=tt(r,t),n=t,o=Lt,s=mt,i=mt,a=Lt;for(;e!==Lt;){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!==mt)throw new Error("invert: does not exist");return tt(o,t)}function Hm(r){let t=r-mt,e=0;for(;t%rr===Lt;)t/=rr,e++;let n=rr,o=xe(r);for(;n<r&&ff(o,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1){let i=(r+mt)/Ra;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=(t+mt)/rr;return function(a,c){if(!ff(a,c))throw new Error("Cannot find square root");let l=e,u=a.pow(a.mul(a.ONE,n),t),f=a.pow(c,s),d=a.pow(c,t);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,mt<<BigInt(l-m-1));u=a.sqr(p),f=a.mul(f,p),d=a.mul(d,u),l=m}return f}}function $m(r){return r%Ra===qm?function(e,n){let o=(r+mt)/Ra,s=e.pow(n,o);if(!e.eql(e.sqr(s),n))throw new Error("Cannot find square root");return s}:r%uf===lf?function(e,n){let o=e.mul(n,rr),s=(r-lf)/uf,i=e.pow(o,s),a=e.mul(n,i),c=e.mul(e.mul(a,rr),i),l=e.mul(a,e.sub(c,e.ONE));if(!e.eql(e.sqr(l),n))throw new Error("Cannot find square root");return l}:(r%Vm,Hm(r))}var df=(r,t)=>(tt(r,t)&mt)===mt,Gm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Na(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Gm.reduce((n,o)=>(n[o]="function",n),t);return be(r,e)}function Wm(r,t,e){if(e<Lt)throw new Error("invalid exponent, negatives unsupported");if(e===Lt)return r.ONE;if(e===mt)return t;let n=r.ONE,o=t;for(;e>Lt;)e&mt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=mt;return n}function zr(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function jm(r,t){let e=(r.ORDER-mt)/rr,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("Cannot find square root: probably non-prime P");return o?1:s?0:-1}function ff(r,t){let e=jm(r,t);return e===0||e===1}function Oa(r,t){t!==void 0&&Fo(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function xe(r,t,e=!1,n={}){if(r<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Oa(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:er(o),ZERO:Lt,ONE:mt,create:c=>tt(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Lt<=c&&c<r},is0:c=>c===Lt,isOdd:c=>(c&mt)===mt,neg:c=>tt(-c,r),eql:(c,l)=>c===l,sqr:c=>tt(c*c,r),add:(c,l)=>tt(c+l,r),sub:(c,l)=>tt(c-l,r),mul:(c,l)=>tt(c*l,r),pow:(c,l)=>Wm(a,c,l),div:(c,l)=>tt(c*Ho(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Ho(c,r),sqrt:n.sqrt||(c=>(i||(i=$m(r)),i(a,c))),toBytes:c=>e?Kr(c,s):tr(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Je(c):we(c)},invertBatch:c=>zr(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function hf(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 Ba(r){let t=hf(r);return t+Math.ceil(t/2)}function pf(r,t,e=!1){let n=r.length,o=hf(t),s=Ba(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Je(r):we(r),a=tt(i,t-mt)+mt;return e?Kr(a,o):tr(a,o)}var mf=BigInt(0),za=BigInt(1);function Fa(r,t){let e=t.negate();return r?e:t}function yf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ua(r,t){yf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=er(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function gf(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=za);let l=t*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,m=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:m,offsetF:l}}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 Zm(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 Ka=new WeakMap,wf=new WeakMap;function qa(r){return wf.get(r)||1}function $o(r,t){return{constTimeNegate:Fa,hasPrecomputes(e){return qa(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>mf;)n&za&&(o=o.add(s)),s=s.double(),n>>=za;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Ua(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 s=r.ZERO,i=r.BASE,a=Ua(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:d,isNegF:m,offsetF:p}=gf(o,c,a);o=l,f?i=i.add(Fa(m,n[p])):s=s.add(Fa(d,n[u]))}return{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=Ua(e,t);for(let a=0;a<i.windows&&o!==mf;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=gf(o,a,i);if(o=c,!u){let d=n[l];s=s.add(f?d.negate():d)}}return s},getPrecomputes(e,n,o){let s=Ka.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Ka.set(n,o(s))),s},wNAFCached(e,n,o){let s=qa(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=qa(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){yf(n,t),wf.set(e,n),Ka.delete(e)}}}function Go(r,t,e,n){if(Xm(e,r),Zm(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=af(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=er(i),c=new Array(Number(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)&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 Dn(r){return Na(r.Fp),be(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Oa(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ce=BigInt(0),Dt=BigInt(1),bf=BigInt(2),Ym=BigInt(8),Qm={zip215:!0};function Jm(r){let t=Dn(r);return be(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function xf(r){let t=Jm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=bf<<BigInt(a*8)-Dt,u=e.create,f=xe(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:ce}}}),m=t.adjustScalarBytes||(v=>v),p=t.domain||((v,b,S)=>{if(ae("phflag",S),b.length||S)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b,S=!1){let C=S?Dt:ce;zt("coordinate "+v,b,C,l)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let w=qr((v,b)=>{let{ex:S,ey:C,ez:N}=v,B=v.is0();b==null&&(b=B?Ym:e.inv(N));let U=u(S*b),K=u(C*b),G=u(N*b);if(B)return{x:ce,y:Dt};if(G!==Dt)throw new Error("invZ was invalid");return{x:U,y:K}}),x=qr(v=>{let{a:b,d:S}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:C,ey:N,ez:B,et:U}=v,K=u(C*C),G=u(N*N),Y=u(B*B),dt=u(Y*Y),lt=u(K*b),wt=u(Y*u(lt+G)),Ot=u(dt+u(S*u(K*G)));if(wt!==Ot)throw new Error("bad point: equation left != right (1)");let gt=u(C*N),Et=u(B*U);if(gt!==Et)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(b,S,C,N){g("x",b),g("y",S),g("z",C,!0),g("t",N),this.ex=b,this.ey=S,this.ez=C,this.et=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,Dt,u(S*C))}static normalizeZ(b){let S=zr(e,b.map(C=>C.ez));return b.map((C,N)=>C.toAffine(S[N])).map(y.fromAffine)}static msm(b,S){return Go(y,f,b,S)}_setWindowSize(b){k.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:S,ey:C,ez:N}=this,{ex:B,ey:U,ez:K}=b,G=u(S*K),Y=u(B*N),dt=u(C*K),lt=u(U*N);return G===Y&&dt===lt}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,B=u(S*S),U=u(C*C),K=u(bf*u(N*N)),G=u(b*B),Y=S+C,dt=u(u(Y*Y)-B-U),lt=G+U,wt=lt-K,Ot=G-U,gt=u(dt*wt),Et=u(lt*Ot),Ut=u(dt*Ot),jt=u(wt*lt);return new y(gt,Et,jt,Ut)}add(b){h(b);let{a:S,d:C}=t,{ex:N,ey:B,ez:U,et:K}=this,{ex:G,ey:Y,ez:dt,et:lt}=b,wt=u(N*G),Ot=u(B*Y),gt=u(K*C*lt),Et=u(U*dt),Ut=u((N+B)*(G+Y)-wt-Ot),jt=Et-gt,dn=Et+gt,ou=u(Ot-S*wt),sp=u(Ut*jt),ip=u(dn*ou),ap=u(Ut*ou),cp=u(jt*dn);return new y(sp,ip,cp,ap)}subtract(b){return this.add(b.negate())}wNAF(b){return k.wNAFCached(this,b,y.normalizeZ)}multiply(b){let S=b;zt("scalar",S,Dt,n);let{p:C,f:N}=this.wNAF(S);return y.normalizeZ([C,N])[0]}multiplyUnsafe(b,S=y.ZERO){let C=b;return zt("scalar",C,ce,n),C===ce?_:this.is0()||C===Dt?this:k.wNAFCachedUnsafe(this,C,y.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return k.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=t;return b===Dt?this:this.multiplyUnsafe(b)}static fromHex(b,S=!1){let{d:C,a:N}=t,B=e.BYTES;b=st("pointHex",b,B),ae("zip215",S);let U=b.slice(),K=b[B-1];U[B-1]=K&-129;let G=Je(U),Y=S?l:e.ORDER;zt("pointHex.y",G,ce,Y);let dt=u(G*G),lt=u(dt-Dt),wt=u(C*dt-N),{isValid:Ot,value:gt}=d(lt,wt);if(!Ot)throw new Error("Point.fromHex: invalid y coordinate");let Et=(gt&Dt)===Dt,Ut=(K&128)!==0;if(!S&&gt===ce&&Ut)throw new Error("Point.fromHex: x=0 and x_0=1");return Ut!==Et&&(gt=u(-gt)),y.fromAffine({x:gt,y:G})}static fromPrivateKey(b){let{scalar:S}=D(b);return E.multiply(S)}toRawBytes(){let{x:b,y:S}=this.toAffine(),C=Kr(S,e.BYTES);return C[C.length-1]|=b&Dt?128:0,C}toHex(){return Ne(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,Dt,u(t.Gx*t.Gy)),y.ZERO=new y(ce,Dt,Dt,ce);let{BASE:E,ZERO:_}=y,k=$o(y,a*8);function I(v){return tt(v,n)}function T(v){return I(Je(v))}function D(v){let b=e.BYTES;v=st("private key",v,b);let S=st("hashed private key",s(v),2*b),C=m(S.slice(0,b)),N=S.slice(b,2*b),B=T(C);return{head:C,prefix:N,scalar:B}}function et(v){let{head:b,prefix:S,scalar:C}=D(v),N=E.multiply(C),B=N.toRawBytes();return{head:b,prefix:S,scalar:C,point:N,pointBytes:B}}function X(v){return et(v).pointBytes}function F(v=Uint8Array.of(),...b){let S=Oe(...b);return T(s(p(S,st("context",v),!!o)))}function pt(v,b,S={}){v=st("message",v),o&&(v=o(v));let{prefix:C,scalar:N,pointBytes:B}=et(b),U=F(S.context,C,v),K=E.multiply(U).toRawBytes(),G=F(S.context,K,B,v),Y=I(U+G*N);zt("signature.s",Y,ce,n);let dt=Oe(K,Kr(Y,e.BYTES));return st("result",dt,e.BYTES*2)}let A=Qm;function L(v,b,S,C=A){let{context:N,zip215:B}=C,U=e.BYTES;v=st("signature",v,2*U),b=st("message",b),S=st("publicKey",S,U),B!==void 0&&ae("zip215",B),o&&(b=o(b));let K=Je(v.slice(U,2*U)),G,Y,dt;try{G=y.fromHex(S,B),Y=y.fromHex(v.slice(0,U),B),dt=E.multiplyUnsafe(K)}catch{return!1}if(!B&&G.isSmallOrder())return!1;let lt=F(N,Y.toRawBytes(),G.toRawBytes(),b);return Y.add(G.multiplyUnsafe(lt)).subtract(dt).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:X,sign:pt,verify:L,ExtendedPoint:y,utils:{getExtendedPublicKey:et,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,b=y.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var Va=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ef=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),c1=BigInt(0),tg=BigInt(1),vf=BigInt(2),l1=BigInt(3),eg=BigInt(5),rg=BigInt(8);function ng(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Va,a=r*r%s*r%s,c=rt(a,vf,s)*a%s,l=rt(c,tg,s)*r%s,u=rt(l,eg,s)*l%s,f=rt(u,t,s)*u%s,d=rt(f,e,s)*f%s,m=rt(d,n,s)*d%s,p=rt(m,o,s)*m%s,g=rt(p,o,s)*m%s,h=rt(g,t,s)*u%s;return{pow_p_5_8:rt(h,vf,s)*r%s,b2:a}}function og(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function sg(r,t){let e=Va,n=tt(t*t*t,e),o=tt(n*n*t,e),s=ng(r*o).pow_p_5_8,i=tt(r*n*s,e),a=tt(t*i*i,e),c=i,l=tt(i*Ef,e),u=a===r,f=a===tt(-r,e),d=a===tt(-r*Ef,e);return u&&(i=c),(f||d)&&(i=l),df(i,e)&&(i=tt(-i,e)),{isValid:u||f,value:i}}var Sf=xe(Va,void 0,!0),ig={a:Sf.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Sf,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:rg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ef,randomBytes:Ur,adjustScalarBytes:og,uvRatio:sg},kn=xf(ig);var Wo=32,jo=64,Ha=32;function Af(){let r=kn.utils.randomPrivateKey(),t=kn.getPublicKey(r);return{privateKey:ag(r,t),publicKey:t}}function _f(r,t){let e=r.subarray(0,Ha);return kn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function If(r,t,e){return kn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function ag(r,t){let e=new Uint8Array(jo);for(let n=0;n<Ha;n++)e[n]=r[n],e[Ha+n]=t[n];return e}var Mn=class{type="Ed25519";raw;constructor(t){this.raw=Zo(t,Wo)}toMultihash(){return Yt.digest($t(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}verify(t,e){return If(this.raw,e,t)}},Xo=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Zo(t,jo),this.publicKey=new Mn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}sign(t){return _f(this.raw,t)}};function $a(r){return r=Zo(r,Wo),new Mn(r)}async function Pf(){let{privateKey:r,publicKey:t}=Af();return new Xo(r,t)}function Zo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var cg=Math.pow(2,7),lg=Math.pow(2,14),ug=Math.pow(2,21),Ga=Math.pow(2,28),Wa=Math.pow(2,35),ja=Math.pow(2,42),Xa=Math.pow(2,49),Z=128,St=127;function ht(r){if(r<cg)return 1;if(r<lg)return 2;if(r<ug)return 3;if(r<Ga)return 4;if(r<Wa)return 5;if(r<ja)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 Za(r,t,e=0){switch(ht(r)){case 8:t[e++]=r&255|Z,r/=128;case 7:t[e++]=r&255|Z,r/=128;case 6:t[e++]=r&255|Z,r/=128;case 5:t[e++]=r&255|Z,r/=128;case 4:t[e++]=r&255|Z,r>>>=7;case 3:t[e++]=r&255|Z,r>>>=7;case 2:t[e++]=r&255|Z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function fg(r,t,e=0){switch(ht(r)){case 8:t.set(e++,r&255|Z),r/=128;case 7:t.set(e++,r&255|Z),r/=128;case 6:t.set(e++,r&255|Z),r/=128;case 5:t.set(e++,r&255|Z),r/=128;case 4:t.set(e++,r&255|Z),r>>>=7;case 3:t.set(e++,r&255|Z),r>>>=7;case 2:t.set(e++,r&255|Z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ya(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)*Ga,e<Z)||(e=r[t+5],n+=(e&St)*Wa,e<Z)||(e=r[t+6],n+=(e&St)*ja,e<Z)||(e=r[t+7],n+=(e&St)*Xa,e<Z))return n;throw new RangeError("Could not decode varint")}function dg(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)*Ga,e<Z)||(e=r.get(t+5),n+=(e&St)*Wa,e<Z)||(e=r.get(t+6),n+=(e&St)*ja,e<Z)||(e=r.get(t+7),n+=(e&St)*Xa,e<Z))return n;throw new RangeError("Could not decode varint")}function At(r,t,e=0){return t==null&&(t=vt(ht(r))),t instanceof Uint8Array?Za(r,t,e):fg(r,t,e)}function te(r,t=0){return r instanceof Uint8Array?Ya(r,t):dg(r,t)}var Qa=new Float32Array([-0]),Be=new Uint8Array(Qa.buffer);function Tf(r,t,e){Qa[0]=r,t[e]=Be[0],t[e+1]=Be[1],t[e+2]=Be[2],t[e+3]=Be[3]}function Lf(r,t){return Be[0]=r[t],Be[1]=r[t+1],Be[2]=r[t+2],Be[3]=r[t+3],Qa[0]}var Ja=new Float64Array([-0]),_t=new Uint8Array(Ja.buffer);function Df(r,t,e){Ja[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 kf(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],Ja[0]}var hg=BigInt(Number.MAX_SAFE_INTEGER),pg=BigInt(Number.MIN_SAFE_INTEGER),Vt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return or;if(t<hg&&t>pg)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>Mf&&(o=0n,++n>Mf&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return or;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):or}},or=new Vt(0,0);or.toBigInt=function(){return 0n};or.zzEncode=or.zzDecode=function(){return this};or.length=function(){return 1};var Mf=4294967296n;function Rf(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 Nf(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 tc(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 ee(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Yo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ec=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,ee(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 ee(this,4);return Yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ee(this,4);return Yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ee(this,4);let t=Lf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ee(this,4);let t=kf(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 ee(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Nf(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ee(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ee(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Vt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ee(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 ee(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 ee(this,8);let t=Yo(this.buf,this.pos+=4),e=Yo(this.buf,this.pos+=4);return new Vt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ya(this.buf,this.pos);return this.pos+=ht(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function rc(r){return new ec(r instanceof Uint8Array?r:r.subarray())}function kt(r,t,e){let n=rc(r);return t.decode(n,void 0,e)}function nc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return vt(i);o+i>t&&(n=vt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var sr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function oc(){}var ic=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},mg=nc();function gg(r){return globalThis.Buffer!=null?vt(r):mg(r)}var Nn=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(oc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new sr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ac((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(Qo,10,Vt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Vt.fromBigInt(t);return this._push(Qo,e.length(),e)}uint64Number(t){return this._push(Za,ht(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Vt.fromBigInt(t).zzEncode();return this._push(Qo,e.length(),e)}sint64Number(t){let e=Vt.fromNumber(t).zzEncode();return this._push(Qo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(sc,1,t?1:0)}fixed32(t){return this._push(Rn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Vt.fromBigInt(t);return this._push(Rn,4,e.lo)._push(Rn,4,e.hi)}fixed64Number(t){let e=Vt.fromNumber(t);return this._push(Rn,4,e.lo)._push(Rn,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(Tf,4,t)}double(t){return this._push(Df,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(sc,1,0):this.uint32(e)._push(wg,e,t)}string(t){let e=Rf(t);return e!==0?this.uint32(e)._push(tc,e,t):this._push(sc,1,0)}fork(){return this.states=new ic(this),this.head=this.tail=new sr(oc,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 sr(oc,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=gg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function sc(r,t,e){t[e]=r&255}function yg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ac=class extends sr{next;constructor(t,e){super(yg,t,e),this.next=void 0}};function Qo(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 Rn(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 wg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Nn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(bg,t,r),this},Nn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(xg,t,r),this});function bg(r,t,e){t.set(r,e)}function xg(r,t,e){r.length<40?tc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function cc(){return new Nn}function Mt(r,t){let e=cc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Vr;(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"})(Vr||(Vr={}));function Jo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function lc(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 Jo("enum",Vr.VARINT,e,n)}function Rt(r,t){return Jo("message",Vr.LENGTH_DELIMITED,r,t)}var ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},On=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var uc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(uc||(uc={}));(function(r){r.codec=()=>lc(uc)})(ut||(ut={}));var le;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(le||(le={}));var fc;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.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=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(fc||(fc={}));function Hr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Ur(r)}var Bn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Fn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ts=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ff={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ts("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 Fe=Ff;var Kn={};Bt(Kn,{MAX_RSA_KEY_SIZE:()=>dc,generateRSAKeyPair:()=>Ec,jwkToJWKKeyPair:()=>zf,jwkToPkcs1:()=>Ag,jwkToPkix:()=>gc,jwkToRSAPrivateKey:()=>xc,pkcs1MessageToJwk:()=>pc,pkcs1MessageToRSAPrivateKey:()=>yc,pkcs1ToJwk:()=>Sg,pkcs1ToRSAPrivateKey:()=>qf,pkixMessageToJwk:()=>mc,pkixMessageToRSAPublicKey:()=>bc,pkixToJwk:()=>_g,pkixToRSAPublicKey:()=>wc});var es=zo;var $r=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Kn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ot.createV1(114,this._multihash)}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}verify(t,e){return Kf(this.jwk,e,t)}},Un=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Kn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}sign(t){return Uf(this.jwk,t)}};var dc=8192,hc=18,Eg=1062,vg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Sg(r){let t=pe(r);return pc(t)}function pc(r){return{n:O(r[1],"base64url"),e:O(r[2],"base64url"),d:O(r[3],"base64url"),p:O(r[4],"base64url"),q:O(r[5],"base64url"),dp:O(r[6],"base64url"),dq:O(r[7],"base64url"),qi:O(r[8],"base64url"),kty:"RSA"}}function Ag(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 Qt([Tt(Uint8Array.from([0])),Tt(P(r.n,"base64url")),Tt(P(r.e,"base64url")),Tt(P(r.d,"base64url")),Tt(P(r.p,"base64url")),Tt(P(r.q,"base64url")),Tt(P(r.dp,"base64url")),Tt(P(r.dq,"base64url")),Tt(P(r.qi,"base64url"))]).subarray()}function _g(r){let t=pe(r,{offset:0});return mc(t)}function mc(r){let t=pe(r[1],{offset:0});return{kty:"RSA",n:O(t[0],"base64url"),e:O(t[1],"base64url")}}function gc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Qt([vg,An(Qt([Tt(P(r.n,"base64url")),Tt(P(r.e,"base64url"))]))]).subarray()}function qf(r){let t=pe(r);return yc(t)}function yc(r){let t=pc(r);return xc(t)}function wc(r,t){if(r.byteLength>=Eg)throw new Cr("Key size is too large");let e=pe(r,{offset:0});return bc(e,r,t)}function bc(r,t,e){let n=mc(r);if(e==null){let o=es(le.encode({Type:ut.RSA,Data:t}));e=Zt(hc,o)}return new $r(n,e)}function xc(r){if(Hf(r)>dc)throw new R("Key size is too large");let t=zf(r),e=es(le.encode({Type:ut.RSA,Data:gc(t.publicKey)})),n=Zt(hc,e);return new Un(t.privateKey,new $r(t.publicKey,n))}async function Ec(r){if(r>dc)throw new R("Key size is too large");let t=await Vf(r),e=es(le.encode({Type:ut.RSA,Data:gc(t.publicKey)})),n=Zt(hc,e);return new Un(t.privateKey,new $r(t.publicKey,n))}function zf(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Vf(r){let t=await Fe.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 Ig(t);return{privateKey:e[0],publicKey:e[1]}}async function Uf(r,t){let e=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Fe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Kf(r,t,e){let n=await Fe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Fe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Ig(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([Fe.get().subtle.exportKey("jwk",r.privateKey),Fe.get().subtle.exportKey("jwk",r.publicKey)])}function Hf(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return P(r.n,"base64url").length*8}var rs=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,qu(t);let n=_n(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),me(s)}update(t){return Fr(this),this.iHash.update(t),this}digestInto(t){Fr(this),Xe(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}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vc=(r,t,e)=>new rs(r,t).update(e).digest();vc.create=(r,t)=>new rs(r,t);function $f(r){r.lowS!==void 0&&ae("lowS",r.lowS),r.prehash!==void 0&&ae("prehash",r.prehash)}function Cg(r){let t=Dn(r);be(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 Sc=class extends Error{constructor(t=""){super(t)}},Ee={Err:Sc,_tlv:{encode:(r,t)=>{let{Err:e}=Ee;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=Tn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Tn(o.length/2|128):"";return Tn(r)+s+o+t},decode(r,t){let{Err:e}=Ee,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}=Ee;if(r<ve)throw new t("integer: negative integers are not allowed");let e=Tn(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}=Ee;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 we(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ee,o=st("signature",r),{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}=Ee,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},ve=BigInt(0),yt=BigInt(1),F2=BigInt(2),Gf=BigInt(3),U2=BigInt(4);function Pg(r){let t=Cg(r),{Fp:e}=t,n=xe(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let x=h.toAffine();return Oe(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 Vo(g,yt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=t;if(h&&typeof g!="bigint"){if(Qe(g)&&(g=Ne(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:we(st("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=tt(E,y)),zt("private key",E,yt,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=qr((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),k=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:k}}),f=qr(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(h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w)||e.is0(w))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");this.px=h,this.py=w,this.pz=x,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=zr(e,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(st("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return Go(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:k}=h,I=e.eql(e.mul(w,k),e.mul(E,y)),T=e.eql(e.mul(x,k),e.mul(_,y));return I&&T}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,x=e.mul(w,Gf),{px:y,py:E,pz:_}=this,k=e.ZERO,I=e.ZERO,T=e.ZERO,D=e.mul(y,y),et=e.mul(E,E),X=e.mul(_,_),F=e.mul(y,E);return F=e.add(F,F),T=e.mul(y,_),T=e.add(T,T),k=e.mul(h,T),I=e.mul(x,X),I=e.add(k,I),k=e.sub(et,I),I=e.add(et,I),I=e.mul(k,I),k=e.mul(F,k),T=e.mul(x,T),X=e.mul(h,X),F=e.sub(D,X),F=e.mul(h,F),F=e.add(F,T),T=e.add(D,D),D=e.add(T,D),D=e.add(D,X),D=e.mul(D,F),I=e.add(I,D),X=e.mul(E,_),X=e.add(X,X),D=e.mul(X,F),k=e.sub(k,D),T=e.mul(X,et),T=e.add(T,T),T=e.add(T,T),new d(k,I,T)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:k}=h,I=e.ZERO,T=e.ZERO,D=e.ZERO,et=t.a,X=e.mul(t.b,Gf),F=e.mul(w,E),pt=e.mul(x,_),A=e.mul(y,k),L=e.add(w,x),M=e.add(E,_);L=e.mul(L,M),M=e.add(F,pt),L=e.sub(L,M),M=e.add(w,y);let v=e.add(E,k);return M=e.mul(M,v),v=e.add(F,A),M=e.sub(M,v),v=e.add(x,y),I=e.add(_,k),v=e.mul(v,I),I=e.add(pt,A),v=e.sub(v,I),D=e.mul(et,M),I=e.mul(X,A),D=e.add(I,D),I=e.sub(pt,D),D=e.add(pt,D),T=e.mul(I,D),pt=e.add(F,F),pt=e.add(pt,F),A=e.mul(et,A),M=e.mul(X,M),pt=e.add(pt,A),A=e.sub(F,A),A=e.mul(et,A),M=e.add(M,A),F=e.mul(pt,M),T=e.add(T,F),F=e.mul(v,M),I=e.mul(L,I),I=e.sub(I,F),F=e.mul(L,pt),D=e.mul(v,D),D=e.add(D,F),new d(I,T,D)}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;zt("scalar",h,ve,x);let y=d.ZERO;if(h===ve)return y;if(this.is0()||h===yt)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:k,k2:I}=w.splitScalar(h),T=y,D=y,et=this;for(;_>ve||I>ve;)_&yt&&(T=T.add(et)),I&yt&&(D=D.add(et)),et=et.double(),_>>=yt,I>>=yt;return E&&(T=T.negate()),k&&(D=D.negate()),D=new d(e.mul(D.px,w.beta),D.py,D.pz),T.add(D)}multiply(h){let{endo:w,n:x}=t;zt("scalar",h,yt,x);let y,E;if(w){let{k1neg:_,k1:k,k2neg:I,k2:T}=w.splitScalar(h),{p:D,f:et}=this.wNAF(k),{p:X,f:F}=this.wNAF(T);D=p.constTimeNegate(_,D),X=p.constTimeNegate(I,X),X=new d(e.mul(X.px,w.beta),X.py,X.pz),y=D.add(X),E=et.add(F)}else{let{p:_,f:k}=this.wNAF(h);y=_,E=k}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(k,I)=>I===ve||I===yt||!k.equals(y)?k.multiplyUnsafe(I):k.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===yt)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===yt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return ae("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return ae("isCompressed",h),Ne(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=$o(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Tg(r){let t=Dn(r);return be(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Wf(r){let t=Tg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(A){return tt(A,n)}function a(A){return Ho(A,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Pg({...t,toBytes(A,L,M){let v=L.toAffine(),b=e.toBytes(v.x),S=Oe;return ae("isCompressed",M),M?S(Uint8Array.from([L.hasEvenY()?2:3]),b):S(Uint8Array.from([4]),b,e.toBytes(v.y))},fromBytes(A){let L=A.length,M=A[0],v=A.subarray(1);if(L===o&&(M===2||M===3)){let b=we(v);if(!Vo(b,yt,e.ORDER))throw new Error("Point is not on curve");let S=u(b),C;try{C=e.sqrt(S)}catch(U){let K=U instanceof Error?": "+U.message:"";throw new Error("Point is not on curve"+K)}let N=(C&yt)===yt;return(M&1)===1!==N&&(C=e.neg(C)),{x:b,y:C}}else if(L===s&&M===4){let b=e.fromBytes(v.subarray(0,e.BYTES)),S=e.fromBytes(v.subarray(e.BYTES,2*e.BYTES));return{x:b,y:S}}else{let b=o,S=s;throw new Error("invalid Point, expected length of "+b+", or uncompressed "+S+", got "+L)}}}),d=A=>Ne(tr(A,t.nByteLength));function m(A){let L=n>>yt;return A>L}function p(A){return m(A)?i(-A):A}let g=(A,L,M)=>we(A.slice(L,M));class h{constructor(L,M,v){zt("r",L,yt,n),zt("s",M,yt,n),this.r=L,this.s=M,v!=null&&(this.recovery=v),Object.freeze(this)}static fromCompact(L){let M=t.nByteLength;return L=st("compactSignature",L,M*2),new h(g(L,0,M),g(L,M,2*M))}static fromDER(L){let{r:M,s:v}=Ee.toSig(st("DER",L));return new h(M,v)}assertValidity(){}addRecoveryBit(L){return new h(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:v,recovery:b}=this,S=k(st("msgHash",L));if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");let C=b===2||b===3?M+t.n:M;if(C>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let N=(b&1)===0?"02":"03",B=c.fromHex(N+d(C)),U=a(C),K=i(-S*U),G=i(v*U),Y=c.BASE.multiplyAndAddUnsafe(B,K,G);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ln(this.toDERHex())}toDERHex(){return Ee.hexFromSig(this)}toCompactRawBytes(){return Ln(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=Ba(t.n);return pf(t.randomBytes(A),t.n)},precompute(A=8,L=c.BASE){return L._setWindowSize(A),L.multiply(BigInt(3)),L}};function x(A,L=!0){return c.fromPrivateKey(A).toRawBytes(L)}function y(A){let L=Qe(A),M=typeof A=="string",v=(L||M)&&A.length;return L?v===o||v===s:M?v===2*o||v===2*s:A instanceof c}function E(A,L,M=!0){if(y(A))throw new Error("first arg must be private key");if(!y(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(l(A)).toRawBytes(M)}let _=t.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");let L=we(A),M=A.length*8-t.nBitLength;return M>0?L>>BigInt(M):L},k=t.bits2int_modN||function(A){return i(_(A))},I=er(t.nBitLength);function T(A){return zt("num < 2^"+t.nBitLength,A,ve,I),tr(A,t.nByteLength)}function D(A,L,M=et){if(["recovered","canonical"].some(lt=>lt in M))throw new Error("sign() legacy options not supported");let{hash:v,randomBytes:b}=t,{lowS:S,prehash:C,extraEntropy:N}=M;S==null&&(S=!0),A=st("msgHash",A),$f(M),C&&(A=st("prehashed msgHash",v(A)));let B=k(A),U=l(L),K=[T(U),T(B)];if(N!=null&&N!==!1){let lt=N===!0?b(e.BYTES):N;K.push(st("extraEntropy",lt))}let G=Oe(...K),Y=B;function dt(lt){let wt=_(lt);if(!f(wt))return;let Ot=a(wt),gt=c.BASE.multiply(wt).toAffine(),Et=i(gt.x);if(Et===ve)return;let Ut=i(Ot*i(Y+Et*U));if(Ut===ve)return;let jt=(gt.x===Et?0:2)|Number(gt.y&yt),dn=Ut;return S&&m(Ut)&&(dn=p(Ut),jt^=1),new h(Et,dn,jt)}return{seed:G,k2sig:dt}}let et={lowS:t.lowS,prehash:!1},X={lowS:t.lowS,prehash:!1};function F(A,L,M=et){let{seed:v,k2sig:b}=D(A,L,M),S=t;return cf(S.hash.outputLen,S.nByteLength,S.hmac)(v,b)}c.BASE._setWindowSize(8);function pt(A,L,M,v=X){let b=A;L=st("msgHash",L),M=st("publicKey",M);let{lowS:S,prehash:C,format:N}=v;if($f(v),"strict"in v)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 B=typeof b=="string"||Qe(b),U=!B&&!N&&typeof b=="object"&&b!==null&&typeof b.r=="bigint"&&typeof b.s=="bigint";if(!B&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,G;try{if(U&&(K=new h(b.r,b.s)),B){try{N!=="compact"&&(K=h.fromDER(b))}catch(jt){if(!(jt instanceof Ee.Err))throw jt}!K&&N!=="der"&&(K=h.fromCompact(b))}G=c.fromHex(M)}catch{return!1}if(!K||S&&K.hasHighS())return!1;C&&(L=t.hash(L));let{r:Y,s:dt}=K,lt=k(L),wt=a(dt),Ot=i(lt*wt),gt=i(Y*wt),Et=c.BASE.multiplyAndAddUnsafe(G,Ot,gt)?.toAffine();return Et?i(Et.x)===Y:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:F,verify:pt,ProjectivePoint:c,Signature:h,utils:w}}function Lg(r){return{hash:r,hmac:(t,...e)=>vc(r,t,Aa(...e)),randomBytes:Ur}}function jf(r,t){let e=n=>Wf({...r,...Lg(n)});return{...e(t),create:e}}var Yf=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Dg=BigInt(1),Ac=BigInt(2),Zf=(r,t)=>(r+t/Ac)/t;function kg(r){let t=Yf,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=rt(u,e,t)*u%t,d=rt(f,e,t)*u%t,m=rt(d,Ac,t)*l%t,p=rt(m,o,t)*m%t,g=rt(p,s,t)*p%t,h=rt(g,a,t)*g%t,w=rt(h,c,t)*h%t,x=rt(w,a,t)*g%t,y=rt(x,e,t)*u%t,E=rt(y,i,t)*p%t,_=rt(E,n,t)*l%t,k=rt(_,Ac,t);if(!_c.eql(_c.sqr(k),r))throw new Error("Cannot find square root");return k}var _c=xe(Yf,void 0,void 0,{sqrt:kg}),Gt=jf({a:BigInt(0),b:BigInt(7),Fp:_c,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=-Dg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Zf(s*r,t),c=Zf(-n*r,t),l=tt(r-a*e-c*o,t),u=tt(-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}}}},zo),j2=BigInt(0);var X2=Gt.ProjectivePoint;function Ic(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Qf(r,t){let e=Or.digest(t instanceof Uint8Array?t:t.subarray());if(Ic(e))return e.then(({digest:n})=>Gt.sign(n,r).toDERRawBytes()).catch(n=>{throw new Bn(String(n))});try{return Gt.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Bn(String(n))}}function Jf(r,t,e){let n=Or.digest(e instanceof Uint8Array?e:e.subarray());if(Ic(n))return n.then(({digest:o})=>Gt.verify(t,o,r)).catch(o=>{throw new Fn(String(o))});try{return Gt.verify(t,n.digest,r)}catch(o){throw new Fn(String(o))}}var qn=class{type="secp256k1";raw;_key;constructor(t){this._key=rd(t),this.raw=td(this._key)}toMultihash(){return Yt.digest($t(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return q.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}verify(t,e){return Jf(this._key,e,t)}},ns=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=ed(t),this.publicKey=new qn(e??nd(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Q(this.raw,t.raw)}sign(t){return Qf(this.raw,t)}};function Cc(r){return new qn(r)}async function od(){let r=Mg();return new ns(r)}function td(r){return Gt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ed(r){try{return Gt.getPublicKey(r,!0),r}catch(t){throw new pn(String(t))}}function rd(r){try{return Gt.ProjectivePoint.fromHex(r),r}catch(t){throw new Cr(String(t))}}function nd(r){try{return Gt.getPublicKey(r,!0)}catch(t){throw new pn(String(t))}}function Mg(){return Gt.utils.randomPrivateKey()}async function sd(r,t){if(r==="Ed25519")return Pf();if(r==="secp256k1")return od();if(r==="RSA")return Ec(Rg(t));if(r==="ECDSA")return Ku(Ng(t));throw new Le}function Gr(r,t){let{Type:e,Data:n}=le.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return wc(o,t);case ut.Ed25519:return $a(o);case ut.secp256k1:return Cc(o);case ut.ECDSA:return Sa(o);default:throw new Le}}function id(r){let{Type:t,Data:e}=le.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return $a(n);case ut.secp256k1:return Cc(n);case ut.ECDSA:return Sa(n);default:throw new Le}}function $t(r){return le.encode({Type:ut[r.type],Data:r.raw})}function Rg(r){return r==null?2048:parseInt(r,10)}function Ng(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new R("Unsupported curve, should be P-256, P-384 or P-521")}var ad=Symbol.for("nodejs.util.inspect.custom"),Og=114,zn=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()})`}[So]=!0;toString(){return this.string==null&&(this.string=q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(Og,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Q(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Q(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[ad](){return`PeerId(${this.toString()})`}},Vn=class extends zn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Hn=class extends zn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},$n=class extends zn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Bg=2336,Gn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Yt.digest(P(this.url))}[ad](){return`PeerId(${this.url})`}[So]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(Bg,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=O(t)),t.toString()===this.toString())}};var Fg=114,cd=2336;function ue(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=qt(q.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wn(ot.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 Wr(e)}function Pc(r){if(r.type==="Ed25519")return new Hn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new $n({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Vn({multihash:r.toCID().multihash,publicKey:r});throw new Le}function ld(r){return Pc(r.publicKey)}function Wr(r){if(Kg(r))return new Vn({multihash:r});if(Ug(r))try{let t=id(r);if(t.type==="Ed25519")return new Hn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new $n({multihash:r,publicKey:t})}catch{let e=O(r.digest);return new Gn(new URL(e))}throw new Co("Supplied PeerID Multihash is invalid")}function Wn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Fg&&r.code!==cd)throw new Io("Supplied PeerID CID is invalid");if(r.code===cd){let t=O(r.multihash.digest);return new Gn(new URL(t))}return Wr(r.multihash)}function Ug(r){return r.code===Yt.code}function Kg(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 Lc=hn(fd(),1);var Xn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Dc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},dd=r=>globalThis.DOMException===void 0?new Dc(r):new DOMException(r),hd=r=>{let t=r.reason===void 0?dd("This operation was aborted."):r.reason;return t instanceof Error?t:dd(t)};function Zn(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(hd(m)),a=()=>{f(hd(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Xn;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 kc(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 Yn=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=kc(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 Ue=class extends Lc.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:Yn,...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#E(){return this.#s<this.#u}#v(){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.#E){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=Zn(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 Xn&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},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 ss(r){let t=[Ht.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Mc=60;function is(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:Ht[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Ht[t.type],TTL:t.TTL??t.ttl??Mc,data:t.data instanceof Uint8Array?O(t.data):t.data}))}}var Vg=4;function Rc(r,t={}){let e=new Ue({concurrency:t.queryConcurrency??Vg});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ss(o.types).forEach(a=>{s.append("type",Ht[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=is(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 pd(){return[Rc("https://cloudflare-dns.com/dns-query"),Rc("https://dns.google/resolve")]}var yd=hn(gd(),1);var Nc=class{lru;constructor(t){this.lru=(0,yd.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 is({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:Ht[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??Mc)*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 wd(r){return new Nc(r)}var Hg=1e3,as=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=wd(t.cacheSize??Hg),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["."]=pd())}async query(t,e={}){let n=ss(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 Ht;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ht||(Ht={}));function bd(r={}){return new as(r)}var cs=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 xd=45,$g=15,jr=new cs;function ls(r){if(!(r.length>$g))return jr.new(r).parseWith(()=>jr.readIPv4Addr())}function us(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>xd))return jr.new(r).parseWith(()=>jr.readIPv6Addr())}function ar(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>xd)return;let e=jr.new(r).parseWith(()=>jr.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 Ed(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 vd(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 Oc(r){switch(r.length){case cr:return r.join(".");case lr:{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 Sd(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 Ad(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var cr=4,lr=16,Mv=parseInt("0xFFFF",16),Gg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Qn(r,t){t.length===lr&&r.length===cr&&Ed(t,0,11)&&(t=t.slice(12)),t.length===cr&&r.length===lr&&vd(r,Gg,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 _d(r,t){if(typeof t=="string"&&(t=ar(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 Bc(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=cr,o=ls(t);if(o==null&&(n=lr,o=us(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=Fc(s,8*n);return{network:Qn(o,i),mask:i}}function Fc(r,t){if(t!==8*cr&&t!==8*lr)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 Xr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Bc(t));else{let n=ar(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=ar(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Fc(o,8*n.length);this.network=Qn(n,this.mask)}}contains(t){return _d({network:this.network,mask:this.mask},t)}toString(){let t=Sd(this.mask),e=t!==-1?String(t):Ad(this.mask);return Oc(this.network)+"/"+e}};function re(r){return!!ls(r)}function Zr(r){return!!us(r)}function fs(r){return!!ar(r)}var Id=re,Wg=Zr,Uc=function(r){let t=0;if(r=r.toString().trim(),Id(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Wg(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Id(e[n]),i;s&&(i=Uc(e[n]),e[n]=O(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,O(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")},Cd=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Yr={},Kc={},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);Kc[t.code]=t,Yr[t.name]=t});function Zg(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function H(r){if(typeof r=="number"){if(Kc[r]!=null)return Kc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Yr[r]!=null)return Yr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Yg=H("ip4"),Qg=H("ip6"),Jg=H("ipcidr");function Hc(r,t){switch(H(r).code){case 4:case 41:return e0(t);case 42:return Vc(t);case 43:return O(t,"base10");case 6:case 273:case 33:case 132:return Ld(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Vc(t);case 421:return s0(t);case 444:return Td(t);case 445:return Td(t);case 466:return o0(t);case 481:return globalThis.encodeURIComponent(Vc(t));default:return O(t,"base16")}}function $c(r,t){switch(H(r).code){case 4:return Pd(t);case 41:return Pd(t);case 42:return zc(t);case 43:return P(t,"base10");case 6:case 273:case 33:case 132:return Wc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return zc(t);case 421:return r0(t);case 444:return i0(t);case 445:return a0(t);case 466:return n0(t);case 481:return zc(globalThis.decodeURIComponent(t));default:return P(t,"base16")}}function Gc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===Yg.code||n===Qg.code)&&(e=o),n===Jg.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new Xr(e,t)}var qc=Object.values(En).map(r=>r.decoder),t0=function(){let r=qc[0].or(qc[1]);return qc.slice(2).forEach(t=>r=r.or(t)),r}();function Pd(r){if(!fs(r))throw new Error("invalid ip address");return Uc(r)}function e0(r){let t=Cd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!fs(t))throw new Error("invalid ip address");return t}function Wc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Ld(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function zc(r){let t=P(r),e=Uint8Array.from(At(t.length));return Pt([e,t],e.length+t.length)}function Vc(r){let t=te(r);if(r=r.slice(ht(t)),r.length!==t)throw new Error("inconsistent lengths");return O(r)}function r0(r){let t;r[0]==="Q"||r[0]==="1"?t=qt(q.decode(`z${r}`)).bytes:t=ot.parse(r).multihash.bytes;let e=Uint8Array.from(At(t.length));return Pt([e,t],e.length+t.length)}function n0(r){let t=t0.decode(r),e=Uint8Array.from(At(t.length));return Pt([e,t],e.length+t.length)}function o0(r){let t=te(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+O(e,"base64url")}function s0(r){let t=te(r),e=r.slice(ht(t));if(e.length!==t)throw new Error("inconsistent lengths");return O(e,"base58btc")}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!==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=Wc(n);return Pt([e,o],e.length+o.length)}function a0(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=Wc(n);return Pt([e,o],e.length+o.length)}function Td(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=O(t,"base32"),o=Ld(e);return`${n}:${o}`}function Dd(r){r=jc(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=H(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new ds("invalid address: "+r);if(a.path===!0){n=jc(o.slice(s).join("/")),t.push([a.code,$c(a.code,n)]),e.push([a.code,n]);break}let c=$c(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Hc(a.code,c)])}return{string:kd(e),bytes:hs(t),tuples:t,stringTuples:e,path:n}}function Xc(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=te(r,o),i=ht(s),a=H(s),c=c0(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 ds("Invalid address Uint8Array: "+O(r,"base16"));t.push([s,l]);let u=Hc(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:kd(e),tuples:t,stringTuples:e,path:n}}function kd(r){let t=[];return r.map(e=>{let n=H(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),jc(t.join("/"))}function hs(r){return Pt(r.map(t=>{let e=H(t[0]),n=Uint8Array.from(At(e.code));return t.length>1&&t[1]!=null&&(n=Pt([n,t[1]])),n}))}function c0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=te(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ht(e)}}function jc(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ds=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var l0=Symbol.for("nodejs.util.inspect.custom"),Yc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),u0=[H("dns").code,H("dns4").code,H("dns6").code,H("dnsaddr").code],Zc=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ps=class r{bytes;#t;#e;#r;#a;[Yc]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Xc(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Dd(t)}else if(Ke(t))e=Xc(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=H("tcp"),a=H("udp"),c=H("ip4"),l=H("ip6"),u=H("dns6"),f=H("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(s=`%${p??""}`),u0.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=H(m).name==="tcp"?"tcp":"udp",o=parseInt(p??"")),(m===c.code||m===l.code)&&(e=H(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({},H(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>H(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(hs(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Yr.p2p.code&&t.push([n,o]),n===Yr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?O(q.decode(`z${n}`),"base58btc"):O(ot.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return Q(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Qr.get(e.name);if(n==null)throw new Zc(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>$(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)}[l0](){return`Multiaddr(${this.#t})`}};var Qr=new Map;function Ke(r){return!!r?.[Yc]}function $(r){return new ps(r)}var f0=32,{code:d0}=H("dnsaddr"),Qc=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},ur=async function(t,e={}){let n=e.maxRecursiveDepth??f0;if(n===0)throw new Qc("Max recursive depth reached");let[,o]=t.stringTuples().find(([l])=>l===d0)??[],i=await(e?.dns??bd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Ht.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=$(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 qd=hn(Kd(),1),ys=qd.default;var w0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:ur}},transportManager:{faultTolerance:$e.FATAL_ALL}};async function zd(r){let t=ys(w0,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 b0(r,t){try{if(typeof r=="string"&&r.length>0)return x0(r);if(typeof r=="number"&&isFinite(r))return t?.long?v0(r):E0(r);throw new Error("Value is not a string or number.")}catch(e){let n=S0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function x0(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 bs=b0;function E0(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?ws(r,t,864e5,"day"):t>=36e5?ws(r,t,36e5,"hour"):t>=6e4?ws(r,t,6e4,"minute"):t>=1e3?ws(r,t,1e3,"second"):`${r} ms`}function ws(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function S0(r){return typeof r=="object"&&r!==null&&"message"in r}function tl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=bs,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,(k,I)=>{if(k==="%%")return"%";E++;let T=e.formatters[I];if(typeof T=="function"){let D=h[E];k=T.call(w,D),h.splice(E,1),E--}return k}),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 xs=L0(),A0=["#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 _0(){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 I0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+bs(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 C0=console.debug??console.log??(()=>{});function P0(r){try{r?xs?.setItem("debug",r):xs?.removeItem("debug")}catch{}}function T0(){let r;try{r=xs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function L0(){try{return localStorage}catch{}}function D0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Vd=tl({formatArgs:I0,save:P0,load:T0,useColors:_0,setupFormatters:D0,colors:A0,storage:xs,log:C0});var Ft=Vd;Ft.formatters.b=r=>r==null?"undefined":q.baseEncode(r);Ft.formatters.t=r=>r==null?"undefined":Kt.baseEncode(r);Ft.formatters.m=r=>r==null?"undefined":ua.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":Hd(r.stack)??Hd(r.message)??r.toString();function k0(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 Es(){return{forComponent(r){return M0(r)}}}function M0(r){let t=k0(`${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 Hd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function fr(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 vs(r){let t=qt(q.decode(`z${r}`));return Wr(t)}var Se=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 fr(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 fr(this.map.values(),t=>t.key)}values(){return fr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var dr=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 fr(this.set.entries(),t=>{let e=vs(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=vs(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return fr(this.set.values(),t=>vs(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 el={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},$d={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Gd=new globalThis.TextEncoder;function R0(r,t){let e=el[t],n=$d[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=el[t],o=$d[t],s=r;for(;s.length>0;){let i=Gd.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 rl(r,{size:t=32,utf8Buffer:e}={}){if(!el[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=Gd.encode(r)}return R0(r,t)}var Jn={hash:r=>Number(rl(r,{size:32})),hashV:(r,t)=>O0(Jn.hash(r,t))};function O0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var nl=64,ne=class{fp;h;seed;constructor(t,e,n,o=2){if(o>nl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=at(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?Q(this.fp,t.fp):!1}};function hr(r,t){return Math.floor(Math.random()*(t-r))+r}var pr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ne))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 ne))throw new TypeError("Invalid Fingerprint");let e=hr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ne))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,to=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??Jn,this.seed=t.seed??hr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new ne(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 pr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new pr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[hr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new pr(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 pr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=P(t));let e=new ne(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=P(t));let e=new ne(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}},F0={1:.5,2:.84,4:.95,8:.98};function U0(r=.001){return r>.002?2:r>1e-5?4:8}function Wd(r,t=.001){let e=U0(t),n=F0[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),nl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Ss=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??Jn,this.seed=t.seed??hr(0,Math.pow(2,10)),this.filterSeries=[new to({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=P(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 to({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=P(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=P(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 eo(r,t=.001,e){return new Ss({...Wd(r,t),...e??{}})}var ro;(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:at(0),payloadType:at(0),payload:at(0),signature:at(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(ro||(ro={}));var As=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var en=class r{static createFromProtobuf=async t=>{let e=ro.decode(t),n=Gr(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=jd(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 As("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=ro.encode({publicKey:$t(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return Q(this.marshal(),t.marshal())}async validate(t){let e=jd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},jd=(r,t,e)=>{let n=P(r),o=At(n.byteLength),s=At(t.length),i=At(e.length);return new W(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 Zd="libp2p-peer-record",Yd=Uint8Array.from([3,1]);var no;(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:at(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Mt(s,n.codec()),n.decode=(s,i)=>kt(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:at(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 ir('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Mt(n,r.codec()),r.decode=(n,o)=>kt(n,r.codec(),o)})(no||(no={}));var mr=class r{static createFromProtobuf=t=>{let e=no.decode(t),n=Wr(qt(e.peerId)),o=(e.addresses??[]).map(i=>$(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Yd;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=no.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 K0(r){return r[Symbol.asyncIterator]!=null}function q0(r){if(K0(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 oo=q0;var qe={},rn=r=>{r.addEventListener("message",t=>{rn.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{rn.dispatchEvent("message",r,t)})};rn.addEventListener=(r,t)=>{qe[r]==null&&(qe[r]=[]),qe[r].push(t)};rn.removeEventListener=(r,t)=>{qe[r]!=null&&(qe[r]=qe[r].filter(e=>e===t))};rn.dispatchEvent=function(r,t,e){qe[r]!=null&&qe[r].forEach(n=>n(t,e))};var ol=rn;var sl="lock:worker:request-read",il="lock:worker:release-read",al="lock:master:grant-read",cl="lock:worker:request-write",ll="lock:worker:release-write",ul="lock:master:grant-write";var Qd=(r=21)=>Math.random().toString().substring(2);var Jd=(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)})}}}))},th=(r,t,e,n)=>async()=>{let o=Qd();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)})},z0={singleProcess:!1},eh=r=>{if(r=Object.assign({},z0,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return ol.addEventListener("message",Jd(e,"requestReadLock",sl,il,al)),ol.addEventListener("message",Jd(e,"requestWriteLock",cl,ll,ul)),e}return{isWorker:!0,readLock:e=>th(e,sl,al,il),writeLock:e=>th(e,cl,ul,ll)}};var gr={},ze;async function fl(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>Zn((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var V0=(r,t)=>{if(ze.isWorker===!0)return{readLock:ze.readLock(r,t),writeLock:ze.writeLock(r,t)};let e=new Ue({concurrency:1}),n;return{async readLock(){if(n!=null)return fl(n,t);n=new Ue({concurrency:t.concurrency,autoStart:!1});let o=n,s=fl(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,fl(e,t)}}},H0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function dl(r){let t=Object.assign({},H0,r);return ze==null&&(ze=eh(t),ze.isWorker!==!0&&(ze.addEventListener("requestReadLock",e=>{gr[e.data.name]!=null&&gr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),ze.addEventListener("requestWriteLock",async e=>{gr[e.data.name]!=null&&gr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),gr[t.name]==null&&(gr[t.name]=V0(t.name,t)),gr[t.name]}var Ae;(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:at(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>kt(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),Is.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=Is.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>kt(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),_s.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 ir('Decode error - map field "addresses" had too many elements');a.addresses.push(_s.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 ir('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 On('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 On('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Mt(o,r.codec()),r.decode=(o,s)=>kt(o,r.codec(),s)})(Ae||(Ae={}));var _s;(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:at(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(_s||(_s={}));var Is;(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=>Mt(e,r.codec()),r.decode=(e,n)=>kt(e,r.codec(),n)})(Is||(Is={}));function $0(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=q.decode(`z${r}`);e=qt(o)}let n=Gr(t.publicKey,e);return Pc(n)}function Cs(r,t,e){let n=Ae.decode(t);return Ps(r,n,e)}function Ps(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:$(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function rh(r,t){return G0(r.addresses,t.addresses)&&W0(r.protocols,t.protocols)&&j0(r.publicKey,t.publicKey)&&X0(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Z0(r.metadata,t.metadata)&&Y0(r.tags,t.tags)}function G0(r,t){return oh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!Q(e.multiaddr,n.multiaddr)))}function W0(r,t){return oh(r,t,(e,n)=>e===n)}function j0(r,t){return nh(r,t)}function X0(r,t){return nh(r,t)}function Z0(r,t){return sh(r,t,(e,n)=>Q(e,n))}function Y0(r,t){return sh(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function nh(r,t){return r==null&&t==null?!0:r!=null&&t!=null?Q(r,t):!1}function oh(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 sh(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 _e="/",ih=new TextEncoder().encode(_e),Ts=ih[0],yr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(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]!==Ts)throw new Error("Invalid key")}toString(t="utf8"){return O(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(_e))}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=ih),this._buf[0]!==Ts){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ts,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ts;)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(_e).slice(1)}type(){return Q0(this.baseNamespace())}name(){return J0(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(_e)||(t+=_e),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(_e):new r(t.slice(0,-1).join(_e))}child(t){return this.toString()===_e?t:t.toString()===_e?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(),...ty(t.map(e=>e.namespaces()))])}};function Q0(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function J0(r){let t=r.split(":");return t[t.length-1]}function ty(r){return[].concat(...r)}var hl="/peers/";function so(r){if(!Ao(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new yr(`${hl}${t}`)}async function ah(r,t,e,n){let o=new Map;for(let s of e){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=$(s.multiaddr)),!Ke(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 Ds(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=Ls(d,{validate:ch})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Ls(d,{validate:lh,map:uh})}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=Ls([...a.entries()],{validate:ch})}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=Ls([...m.entries()],{validate:lh,map:uh})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=$t(o.id.publicKey):t.publicKey!=null?u=$t(t.publicKey):r.publicKey!=null&&(u=$t(r.publicKey));let f={addresses:await ah(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=>Q(m.multiaddr,m.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Ls(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 ch(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 lh(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 uh(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 fh(r){let t=r.toString().split("/")[2],e=ot.parse(t,Kt);return Wn(e)}function pl(r,t,e){let n=fh(r);return Cs(n,t,e)}function ey(r,t){return{prefix:hl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(pl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(pl(n.key,n.value,t),pl(o.key,o.value,t)))}}var ks=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=dl({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(so(t))}async load(t){let e=so(t),n=await this.datastore.get(e),o=Ae.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new Ge;return Ps(t,o,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e){let n=await this.#t(t),o=await Ds(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,o,n)}async patch(t,e){let n=await this.#t(t),o=await Ds(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 Ds(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(ey(t??{},this.maxAddressAge))){let o=fh(e);if(o.equals(this.peerId))continue;let s=Ae.decode(n);if(this.#r(o,s)){await this.datastore.delete(e);continue}yield Ps(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t){try{let e=so(t),n=await this.datastore.get(e),o=Ae.decode(n);if(this.#r(t,o))throw await this.datastore.delete(e),new Ge;return{peerPB:o,peer:Cs(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=Ae.encode(e);return await this.datastore.put(so(t),o),{peer:Cs(t,o,this.maxAddressAge),previous:n?.peer,updated:n==null||!rh(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 ml=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 ks(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 oo(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 en.openAndCertify(t,mr.DOMAIN),o=Wn(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=mr.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 en.createFromProtobuf(i.peerRecordEnvelope),c=mr.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 dh(r,t={}){return new ml(r,t)}var Ms=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 ry(r){return r[Symbol.asyncIterator]!=null}function ny(r){if(ry(r))return(async()=>{for await(let t of r);})();for(let t of r);}var gl=ny;function oy(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 hh=oy;function sy(r){return r[Symbol.asyncIterator]!=null}function iy(r,t){let e=0;if(sy(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=hh(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 wr=iy;function ay(r){return r[Symbol.asyncIterator]!=null}function cy(r,t){return ay(r)?async function*(){yield*(await oo(r)).sort(t)}():function*(){yield*oo(r).sort(t)}()}var yl=cy;function ly(r){return r[Symbol.asyncIterator]!=null}function uy(r,t){return ly(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 wl=uy;var Rs=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 gl(this.putMany(t,n)),t=[],await gl(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=wr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>yl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=wr(n,()=>o++>=s)}return t.limit!=null&&(n=wl(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=wr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>yl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=wr(n,()=>s++>=o)}return t.limit!=null&&(n=wl(n,t.limit)),n}};var Ns=class extends Rs{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 Ms;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 yr(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new yr(t)}};function ph(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 gh=hn(mh(),1),fy=["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"],dy=fy.map(r=>new gh.Netmask(r));function bl(r){for(let t of dy)if(t.contains(r))return!0;return!1}function hy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function py(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 bl(o)}function my(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function gy(r){let t=r.split(":"),e=t[t.length-1];return bl(e)}function yy(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 Ve(r){return re(r)?bl(r):hy(r)?py(r):my(r)?gy(r):Zr(r)?yy(r):void 0}var wy=r=>r.toString().split("/").slice(1),nn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>nn(e=>e===r).match(t),pattern:r}),br=()=>({match:r=>nn(t=>typeof t=="string").match(r),pattern:"{string}"}),ao=()=>({match:r=>nn(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{q.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),co=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{fa.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),j=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 nt(...r){function t(o){let s=wy(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 by=J(),yh=nt(by),Bs=V(z("dns4"),br()),Fs=V(z("dns6"),br()),Us=V(z("dnsaddr"),br()),El=V(z("dns"),br()),G6=nt(Bs,j(J())),W6=nt(Fs,j(J())),j6=nt(Us,j(J())),X6=nt(Ct(El,Us,Bs,Fs),j(J())),wh=V(z("ip4"),nn(re)),bh=V(z("ip6"),nn(Zr)),vl=Ct(wh,bh),Ie=Ct(vl,El,Bs,Fs,Us),Z6=nt(Ct(vl,V(Ct(El,Us,Bs,Fs),j(J())))),Sl=nt(wh),Al=nt(bh),Y6=nt(vl),_l=V(Ie,z("tcp"),ao()),lo=V(Ie,z("udp"),ao()),uo=nt(V(_l,j(J()))),Q6=nt(lo),Il=V(lo,z("quic"),j(J())),Ks=V(lo,z("quic-v1"),j(J())),xy=Ct(Il,Ks),J6=nt(Il),xh=nt(Ks),xl=Ct(Ie,_l,lo,Il,Ks),Eh=Ct(V(xl,z("ws"),j(J()))),xr=nt(Eh),vh=Ct(V(xl,z("wss"),j(J())),V(xl,z("tls"),j(V(z("sni"),br())),z("ws"),j(J()))),fo=nt(vh),Sh=V(lo,z("webrtc-direct"),j(co()),j(co()),j(J())),Cl=nt(Sh),Ah=V(Ks,z("webtransport"),j(co()),j(co()),j(J())),Pl=nt(Ah),Os=Ct(Eh,vh,V(_l,j(J())),V(xy,j(J())),V(Ie,j(J())),Sh,Ah,J()),t4=nt(Os),Ey=V(Os,z("p2p-circuit"),J()),ho=nt(Ey),vy=Ct(V(Os,z("p2p-circuit"),z("webrtc"),j(J())),V(Os,z("webrtc"),j(J())),V(z("webrtc"),j(J()))),Tl=nt(vy),Sy=Ct(V(Ie,z("tcp"),ao(),z("http"),j(J())),V(Ie,z("http"),j(J()))),e4=nt(Sy),Ay=Ct(V(Ie,z("tcp"),Ct(V(z("443"),z("http")),V(ao(),z("https"))),j(J())),V(Ie,z("tls"),z("http"),j(J())),V(Ie,z("https"),j(J()))),r4=nt(Ay),_y=Ct(V(z("memory"),br(),j(J()))),n4=nt(_y);var _h=864e13;var Iy=448,Ll=449,Cy=53,Py=54,Ty=55,Ly=56,qs=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=Ve(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?_h-Date.now():0,lastVerified:o?_h-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:$(`/${s.map(u=>[H(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]===Iy&&t[n+1]?.[0]!==Ll)return t.splice(n+1,0,[Ll,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]===Ll||e[0]===Cy||e[0]===Py||e[0]===Ty||e[0]===Ly)return e[1]}};var Dl=4,kl=41,Ml=6,Dy=273,zs=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:re(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]===Ml?"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]===Dl||o[0][0]===kl)&&o[1][0]===Ml?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Dl||o[0][0]===kl)&&o[1][0]===Dy&&(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?Dl:kl,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:$(`/${o.map(c=>[H(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]===Ml?"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 Ih(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 Vs(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function Er(r){try{if(!Vs(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:Ve(t)??!1}catch{}return!0}var ky={maxObservedAddresses:10},Hs=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}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&&(Er(t)||Ih(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:$(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 My=[4,41,53,54,55,56];function Rl(r){try{let[[t]]=r.stringTuples();return My.includes(t)}catch{}return!1}var Ry={maxObservedAddresses:10},$s=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??Ry.maxObservedAddresses}get(t,e){if(Er(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:!Rl(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(Rl(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Ch=6e4,Ph={maxObservedAddresses:10,addressVerificationTTL:Ch*10,addressVerificationRetry:Ch*5},Ny=r=>r;function Nl(r,t){let e=r.getPeerId();return e!=null&&ue(e).equals(t)&&(r=r.decapsulate($(`/p2p/${t.toString()}`))),r}var Gs=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 Hs(t,e),this.dnsMappings=new qs(t,e),this.ipMappings=new zs(t,e),this.transportAddresses=new $s(t,e),this.announceFilter=e.announceFilter??Ny,this.observedAddressFilter=eo(1024),this.addressVerificationTTL=e.addressVerificationTTL??Ph.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Ph.addressVerificationRetry,this._updatePeerStoreAddresses=ph(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=>$(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>$(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>$(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=Nl(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=Nl(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=Nl(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=$(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(o=>{o.updateAnnounceAddrs(t)}),t.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];e=e.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),e=e.concat(n.map(o=>({multiaddr:o,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($(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${re(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove($(`/ip${re(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"||Ve(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>xr.exactMatch(s)||fo.exactMatch(s),s=>uo.exactMatch(s),s=>xh.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 Th;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Th||(Th={}));var Ws=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},js=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},on=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},po=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Xs=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"}},Ys=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},mo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Qs=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Js=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},ti=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},ei=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},ri=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},vr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Sr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},ni=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var Ol=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=Es())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>ko(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")}},By=["metrics","connectionProtector","dns"],Fy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Lh(r={}){let t=new Ol(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Fy.includes(o)){let i=t.components[o];if(i==null&&!By.includes(o))throw new Ws(`${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 Dh(r){let t={};for(let e of Object.values(r.components))for(let n of Uy(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Ky(e))if(t[n]!==!0)throw new js(`Service "${qy(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Uy(r){return Array.isArray(r?.[gn])?r[gn]:[]}function Ky(r){return Array.isArray(r?.[Xi])?r[Xi]:[]}function qy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var zy=4,Vy=41;function kh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(xr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===zy||e[0][0]===Vy?!!Ve(`${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 Mh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Hy=new WeakMap;function $y({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Mh());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(Mh())},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}),Hy.set(f,()=>{c(s),s=null,i()}),f}}var Gy=$y(),Rh=Gy;var oi=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}},si=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ii=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 Bl}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 oi("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 Rh(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)}},Bl=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 ai(r){if(Ao(r))return{peerId:r,multiaddrs:[]};let t=Array.isArray(r)?r:[r],e;if(t.length>0){let n=t[0].getPeerId();e=n==null?void 0:ue(n),t.forEach(o=>{if(!Ke(o))throw new Te("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ue(s);if(e?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!yh.exactMatch(n)),{peerId:e,multiaddrs:t}}var Wy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Nh(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Wy;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var Oh="last-dial-failure",Bh="last-dial-success";var ci=100,li=50;async function Fh(r,t){let e=!1;for(let o of Qr.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 go(r){try{let t;if(typeof r=="string"?t=$(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return Gc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var jy={maxConnections:ci,allow:[]},ui=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??jy.maxConnections,this.allow=(e.allow??[]).map(n=>go(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 Se;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 Nh(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 ct(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var fi=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}},sn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new fi(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 fi(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 Fl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Uh(r={}){return Xy(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 Xy(r,t){t=t??{};let e=t.onEnd,n=new sn,o,s,i,a=ct(),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=ct()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new sn,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 sn,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 Fl)},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 Ul=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 an(r,t,e,n){let o=new Ul(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 di=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 oe(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new di(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new di(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 hi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ct(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Xt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Zy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var pi=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Zy(),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 Xt),this.cleanup())}async join(t={}){let e=new hi(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 oe(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 ln=class extends de{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new si;let n=new pi(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 Xt)}),this.clear()}async onEmpty(t){this.size!==0&&await an(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await an(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await an(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=Uh({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 Xt("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 mi=class extends ln{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ce(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 Kh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Kl(r){if(!Vs(r))return!1;let{address:t}=r.nodeAddress();return Kh(t)}function Yy(r,t){let e=uo.exactMatch(r.multiaddr),n=uo.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=fo.exactMatch(r.multiaddr),s=fo.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=xr.exactMatch(r.multiaddr),a=xr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Tl.exactMatch(r.multiaddr),l=Tl.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Cl.exactMatch(r.multiaddr),f=Cl.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Pl.exactMatch(r.multiaddr),m=Pl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function Qy(r,t){let e=Kl(r.multiaddr),n=Kl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Jy(r,t){let e=Er(r.multiaddr),n=Er(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function tw(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function ew(r,t){let e=ho.exactMatch(r.multiaddr),n=ho.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function qh(r){return r.sort(Yy).sort(tw).sort(ew).sort(Jy).sort(Qy)}var gi={maxParallelDials:li,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ur}},yi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??gi.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??gi.maxDialQueueLength,this.dialTimeout=e.dialTimeout??gi.dialTimeout,this.connections=e.connections??new Se,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??{}))Qr.set(n,o);this.queue=new mi({concurrency:e.maxParallelDials??gi.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==Xt.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}=ai(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 Lr("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=Ce([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Hl,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 Lr("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:{[Bh]:P(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:{[Oh]:P(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new To(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:$(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Lr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new mo("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 Fh(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 ti("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?qh(l):l.sort(this.addressSorter);if(u.length===0)throw new mo("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=>!ho.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var wi=class extends ln{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var jh=hn(Gh(),1);var nw=Object.prototype.toString,ow=r=>nw.call(r)==="[object Error]",sw=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 $l(r){return r&&ow(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:sw.has(r.message):!1}var Gl=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}},Wh=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Wl(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=jh.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 Gl)throw c.originalError;if(c instanceof TypeError&&!$l(c))throw c;if(Wh(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Wh(l,a,t),i(),n(l)}}})})}var bi=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 wi({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);Xh(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Wl(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(ji)&&(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=>Xh(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 Xh(r){for(let t of r.tags.keys())if(t.startsWith(ji))return!0;return!1}var Hl=50,jl={maxConnections:ci,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},xi=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??jl.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Se,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=>go(n)),this.deny=(e.deny??[]).map(n=>go(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??jl.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ii({points:e.inboundConnectionThreshold??jl.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ui({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>$(n))}),this.dialQueue=new yi(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??li,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:ur},connections:this.connections}),this.reconnectQueue=new bi({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 au(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 cu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new fe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=ai(t);if(this.peerId.equals(n))throw new Tr("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??Hl});if(o.status!=="open")throw new Pr("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 Te("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=>$(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var un=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 cw=1.2,lw=2,uw=2e3,Ei=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new un(t.interval??5e3),this.failure=new un(t.interval??5e3),this.next=new un(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??lw,this.timeoutMultiplier=t.timeoutMultiplier??cw,this.minTimeout=t.minTimeout??uw,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=Ce([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 Xl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ct(),this.haveNext=ct()}[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=ct(),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=ct(),await oe(this.readNext.promise,e?.signal,e)}};function vi(){return new Xl}var Si=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ai(r,t){let e=vi();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 W;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await oe(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await oe(n.next(),i?.signal);if(l===!0)throw new Si("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 fw=1e4,dw="1.0.0",hw="ping",pw="ipfs",Zh=32,mw=!0,_i=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??pw}/${hw}/${dw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??fw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??mw,this.timeout=new Ei({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[gn]=["@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=Ai(o);e=Date.now(),await Promise.all([s.write(Hr(Zh),{signal:n}),s.read({bytes:Zh,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 gw(r){return r[Symbol.asyncIterator]!=null}async function yw(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*ww(r){let t=vi();yw(r,t).catch(()=>{}),yield*t}function*bw(r){for(let t of r)yield*t}function xw(...r){let t=[];for(let e of r)gw(e)||t.push(e);return t.length===r.length?bw(t):ww(r)}var yo=xw;var Ii=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:O(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:O(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 on("No content routers available");let n=this,o=new dr;for await(let s of yo(...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 on("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 on("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new fe;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new fe;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var Ci=globalThis.CustomEvent??Event;async function*Zl(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=ct(),a=ct(),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=ct(),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 Ci("task-complete"))},h=>{g.done=!0,g.err=h,o.dispatchEvent(new Ci("task-complete"))})}c=!0,o.dispatchEvent(new Ci("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ci("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=ct(),await a.promise),l!=null)throw l;if(n?yield*d():yield*m(),c&&s.length===0)break}}var Pi=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:O(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 po("No peer routers available");if(t.toString()===this.peerId.toString())throw new Xs("Should not try to find self");let n=this,o=yo(...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 Ge}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new po("No peer routers available");let n=this,o=eo(1024);for await(let s of Zl(async function*(){let i=yo(...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 Ti=class extends de{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Ce([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ct(),yield(await an(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=Ce([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=Hr(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 oe(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 Yl=32,Ql=64,Li=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 Ys(`Handler already registered for protocol ${t}`);let o=ys.bind({ignoreUndefined:!0})({maxInboundStreams:Yl,maxOutboundStreams:Ql},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 Jl=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 Yh(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Jl({name:t,metrics:e}):n=new Map,n}var Di=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=Yh({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 ni(`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 fe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new Qs)});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})}),Sl.matches(c)?e.ipv4.attempts++:Al.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),Sl.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 Js(`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(`
@@ -17,7 +17,7 @@ ${[...e.errors.entries()].map(([s,i])=>`
17
17
  `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new W(...t.map(i=>Ki.single(P(`${i}
18
18
  `))),P(`
19
19
  `));e.log.trace('handle: respond with "%s" for %s',t,o),await _r(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 _r(n,P(`na
20
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var Iw=500,nu=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";[iu]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new _o("the connection is being closed");if(this.status==="closed")throw new Pr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Dr("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(Iw);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 ep(r){return new nu(r)}function Pw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Yl}function Tw(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??Ql}function rp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var qi=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 ei(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Ce([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 ri("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=ue(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 Te(`${e} connection that skipped encryption must have a peer id`);let f=ue(u);c="native",s=f}if(s.equals(this.components.peerId)){let u=new Tr("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 Eo(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=Pw(x,this.components.registrar);if(rp(x,"inbound",f)===y){let _=new Lo(`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 vr("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 bo(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=Tw(x,this.components.registrar,g),E=rp(x,"outbound",f);if(E>=y){let _=new Do(`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 vr("Connection is not multiplexed")};return f=ep({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 Dr("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 Eo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Sr(`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 Sr(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 bo(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Sr(`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 Sr(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 bo(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 vr(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 Eo(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 vr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var zi="2.8.5-9b33d202e",Vi="js-libp2p";function op(r,t){return`${r??Vi}/${t??zi} browser/${globalThis.navigator.userAgent}`}var Hi=class extends de{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new de,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??Es(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Vi,s=t.nodeInfo?.version??zi,i=this.components=Lh({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??op(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Ns,connectionGater:kh(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",dh(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 qi(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 Di(this.components,t.transportManager)),this.configureComponent("connectionManager",new xi(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new _i(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Li(this.components)),this.configureComponent("addressManager",new Gs(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 Pi(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 Ii(this.components,{routers:c})),this.configureComponent("randomWalk",new Ti(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[$i]!=null&&(this.log("registering service %s for content routing",l),c.push(f[$i])),f[Wi]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Wi])),f[Gi]!=null&&(this.log("registering service %s for peer discovery",l),f[Gi].addEventListener?.("peer",d=>{this.#t(d)}))}Dh(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 dr;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={}){Ke(t)&&(t=ue(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=Pt([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Gr(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 Lw(r={}){r.privateKey??=await sd("Ed25519");let t=new Hi({...await zd(r),peerId:ld(r.privateKey)});return r.start!==!1&&await t.start(),t}return pp(Dw);})();
20
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var Iw=500,nu=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";[iu]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new _o("the connection is being closed");if(this.status==="closed")throw new Pr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Dr("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(Iw);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 ep(r){return new nu(r)}function Pw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Yl}function Tw(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??Ql}function rp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var qi=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 ei(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Ce([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 ri("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=ue(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 Te(`${e} connection that skipped encryption must have a peer id`);let f=ue(u);c="native",s=f}if(s.equals(this.components.peerId)){let u=new Tr("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 Eo(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=Pw(x,this.components.registrar);if(rp(x,"inbound",f)===y){let _=new Lo(`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 vr("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 bo(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=Tw(x,this.components.registrar,g),E=rp(x,"outbound",f);if(E>=y){let _=new Do(`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 vr("Connection is not multiplexed")};return f=ep({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 Dr("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 Eo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Sr(`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 Sr(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 bo(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Sr(`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 Sr(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 bo(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 vr(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 Eo(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 vr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var zi="2.8.5-cdc63e6cc",Vi="js-libp2p";function op(r,t){return`${r??Vi}/${t??zi} browser/${globalThis.navigator.userAgent}`}var Hi=class extends de{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new de,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??Es(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Vi,s=t.nodeInfo?.version??zi,i=this.components=Lh({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??op(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Ns,connectionGater:kh(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",dh(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 qi(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 Di(this.components,t.transportManager)),this.configureComponent("connectionManager",new xi(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new _i(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Li(this.components)),this.configureComponent("addressManager",new Gs(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 Pi(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 Ii(this.components,{routers:c})),this.configureComponent("randomWalk",new Ti(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[$i]!=null&&(this.log("registering service %s for content routing",l),c.push(f[$i])),f[Wi]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Wi])),f[Gi]!=null&&(this.log("registering service %s for peer discovery",l),f[Gi].addEventListener?.("peer",d=>{this.#t(d)}))}Dh(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 dr;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={}){Ke(t)&&(t=ue(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=Pt([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Gr(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 Lw(r={}){r.privateKey??=await sd("Ed25519");let t=new Hi({...await zd(r),peerId:ld(r.privateKey)});return r.start!==!1&&await t.start(),t}return pp(Dw);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  @noble/hashes/esm/utils.js: